diff --git a/.gitignore b/.gitignore index 681ba2d12..5770ed110 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ __pycache__/ /docs-comparison-tool /node_modules /legacy-docs +AGENTS.md diff --git a/CampaignAssets/BubbleBuilder.png b/CampaignAssets/BubbleBuilder.png new file mode 100644 index 000000000..422e6dcd7 Binary files /dev/null and b/CampaignAssets/BubbleBuilder.png differ diff --git a/CampaignAssets/Create-Chan.png b/CampaignAssets/Create-Chan.png new file mode 100644 index 000000000..2b1a7799f Binary files /dev/null and b/CampaignAssets/Create-Chan.png differ diff --git a/CampaignAssets/Create-Temp.png b/CampaignAssets/Create-Temp.png new file mode 100644 index 000000000..409206bb5 Binary files /dev/null and b/CampaignAssets/Create-Temp.png differ diff --git a/CampaignAssets/CreateCategory.png b/CampaignAssets/CreateCategory.png new file mode 100644 index 000000000..11bca26f7 Binary files /dev/null and b/CampaignAssets/CreateCategory.png differ diff --git a/CampaignAssets/create-Camp.png b/CampaignAssets/create-Camp.png new file mode 100644 index 000000000..a42dd807c Binary files /dev/null and b/CampaignAssets/create-Camp.png differ diff --git a/ai-agents/agent-builder/overview.mdx b/ai-agents/agent-builder/overview.mdx index 9776f7c0b..00a166161 100644 --- a/ai-agents/agent-builder/overview.mdx +++ b/ai-agents/agent-builder/overview.mdx @@ -15,6 +15,10 @@ description: "Create, configure, and launch AI agents directly inside CometChat. Agent Builder provides the capability to create, configure, and customize AI agents directly within CometChat. It supports selecting models, integrating ready-to-use tools, APIs, and MCPs, and deploying agents without relying on any external management or orchestration platforms. + +**Where AI Agents respond.** Agents created in Agent Builder respond only in one-on-one conversations between an end user and the agent user. They do not respond when added to a group, even as a member or owner. If your use case requires an agent in group conversations, share your requirements on [feedback.cometchat.com](https://feedback.cometchat.com). + + ## Getting Started ### How to create an agent – step-by-step guide diff --git a/ai-agents/mastra-backend-tools-agent.mdx b/ai-agents/mastra-backend-tools-agent.mdx index 9e7431db5..c80e66359 100644 --- a/ai-agents/mastra-backend-tools-agent.mdx +++ b/ai-agents/mastra-backend-tools-agent.mdx @@ -65,7 +65,7 @@ Core files and folders for the Backend Tools Agent (browse source on GitHub): - Server - [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/index.ts) - Workflows - - [src/mastra/workflows/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-backend-tools-agent/src/mastra/workflows/index.ts) + - [src/mastra/workflows/orchestrator-workflow.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-orchestrator-agent/src/mastra/workflows/orchestrator-workflow.ts) *** @@ -191,4 +191,4 @@ curl -X POST http://localhost:4111/api/agents/deals/generate \ * Add more backend tools (e.g., get-order, create-ticket) and guard with RBAC. * Stream responses or add partial updates for long-running actions. -* Instrument and log tool invocations for tuning and observability. \ No newline at end of file +* Instrument and log tool invocations for tuning and observability. diff --git a/ai-agents/mastra-frontend-actions-agent.mdx b/ai-agents/mastra-frontend-actions-agent.mdx index f60384477..2c773e97a 100644 --- a/ai-agents/mastra-frontend-actions-agent.mdx +++ b/ai-agents/mastra-frontend-actions-agent.mdx @@ -50,9 +50,6 @@ Give your chats superpowers: let an agent trigger visual effects and UI actions Frontend sample - [widget/index.html](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-frontend-actions-agent/widget/index.html) - This keeps sensitive work on the server and visual effects on the client. - Workflows - - [src/mastra/workflows/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-frontend-actions-agent/src/mastra/workflows/index.ts) - Key components (source-linked below): the agent, the `confetti` tool, server entry, and a sample widget page. *** @@ -76,9 +73,6 @@ Key components (source-linked below): the agent, the `confetti` tool, server ent - [src/mastra/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-frontend-actions-agent/src/mastra/index.ts) - Frontend sample - [widget/index.html](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-frontend-actions-agent/widget/index.html) - - Workflows - - [src/mastra/workflows/index.ts](https://github.com/cometchat/ai-agent-mastra-examples/blob/main/mastra-frontend-actions-agent/src/mastra/workflows/index.ts) - *** ## Step 1 - Create the Agent diff --git a/assets/consent.js b/assets/consent.js new file mode 100644 index 000000000..e2ceca405 --- /dev/null +++ b/assets/consent.js @@ -0,0 +1,192 @@ +/* ------------------------------------------------------------------ */ +/* Consent gating for analytics */ +/* */ +/* Strict mode: zero requests to any analytics provider until the */ +/* user clicks Accept All on the cookie banner. GTM (and everything */ +/* it loads — GA4 G-M5KZ2NFCYL, HubSpot tracking, etc.) is NOT loaded */ +/* on page load; it is loaded inline only after an explicit Accept. */ +/* */ +/* Pairs with the removal of `integrations.gtm` from docs.json so */ +/* this file is the sole loader of GTM-59ZJRV2 on docs.cometchat.com. */ +/* ------------------------------------------------------------------ */ +(function initConsentGate() { + try { + if (window.__ccConsentGateInitialized__) return; + window.__ccConsentGateInitialized__ = true; + } catch (_) { return; } + + var GTM_ID = 'GTM-59ZJRV2'; + var STORAGE_KEY = 'cc_consent'; + var PRIVACY_URL = 'https://www.cometchat.com/privacy-policy'; + + window.dataLayer = window.dataLayer || []; + function gtag() { window.dataLayer.push(arguments); } + + // 1) Default-deny. Sets Google Consent Mode v2 defaults so that + // any downstream Google tag respects the user's not-yet-given + // consent. This is belt-and-suspenders — GTM is also not loaded + // at all until Accept, so in practice no Google script ever sees + // a denied state, it simply never runs. + gtag('consent', 'default', { + ad_storage: 'denied', + ad_user_data: 'denied', + ad_personalization: 'denied', + analytics_storage: 'denied', + wait_for_update: 500 + }); + + function applyConsent(granted) { + var v = granted ? 'granted' : 'denied'; + gtag('consent', 'update', { + ad_storage: v, + ad_user_data: v, + ad_personalization: v, + analytics_storage: v + }); + try { window.localStorage.setItem(STORAGE_KEY, v); } catch (_) {} + try { document.documentElement.setAttribute('data-cc-consent', v); } catch (_) {} + } + + var gtmLoaded = false; + function loadGTM() { + if (gtmLoaded) return; + gtmLoaded = true; + (function (w, d, s, l, i) { + w[l] = w[l] || []; + w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); + var f = d.getElementsByTagName(s)[0]; + var j = d.createElement(s); + var dl = l !== 'dataLayer' ? '&l=' + l : ''; + j.async = true; + j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; + if (f && f.parentNode) { + f.parentNode.insertBefore(j, f); + } else { + (d.head || d.documentElement).appendChild(j); + } + })(window, document, 'script', 'dataLayer', GTM_ID); + } + + function injectStyles() { + if (document.getElementById('cc-consent-styles')) return; + var style = document.createElement('style'); + style.id = 'cc-consent-styles'; + // Once the user has chosen, suppress HubSpot's own banner so it + // doesn't appear after GTM loads and HubSpot's tracking initializes. + style.textContent = + '#cc-consent-banner{position:fixed;bottom:0;left:0;right:0;z-index:2147483646;' + + 'background:#fff;color:#111827;border-top:1px solid rgba(0,0,0,0.08);' + + 'box-shadow:0 -4px 20px rgba(0,0,0,0.06);' + + 'padding:24px clamp(16px,5vw,64px);' + + 'font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;' + + 'font-size:14px;line-height:1.5;display:flex;flex-direction:column;gap:16px}' + + '@media(min-width:880px){#cc-consent-banner{flex-direction:row;align-items:center;' + + 'justify-content:space-between;gap:32px}}' + + '#cc-consent-banner__copy{flex:1;min-width:0}' + + '#cc-consent-banner__copy p{margin:0 0 8px 0;color:inherit}' + + '#cc-consent-banner__copy p:last-child{margin-bottom:0}' + + '#cc-consent-banner__copy a{color:inherit;text-decoration:underline}' + + '#cc-consent-banner__actions{display:flex;gap:8px;flex-shrink:0;' + + 'align-self:stretch;justify-content:flex-end}' + + '@media(min-width:880px){#cc-consent-banner__actions{align-self:auto}}' + + '#cc-consent-banner button{font:inherit;cursor:pointer;padding:10px 20px;' + + 'border-radius:8px;border:1px solid transparent;transition:background .15s ease;' + + 'white-space:nowrap}' + + '#cc-consent-banner__decline{background:#fff;color:#111827;border-color:#d1d5db}' + + '#cc-consent-banner__decline:hover{background:#f9fafb}' + + '#cc-consent-banner__accept{background:#111827;color:#fff}' + + '#cc-consent-banner__accept:hover{background:#1f2937}' + + '@media(prefers-color-scheme:dark){' + + '#cc-consent-banner{background:#0b0d10;color:#f3f4f6;' + + 'border-top-color:rgba(255,255,255,0.08)}' + + '#cc-consent-banner__decline{background:transparent;color:#f3f4f6;' + + 'border-color:rgba(255,255,255,0.18)}' + + '#cc-consent-banner__decline:hover{background:rgba(255,255,255,0.06)}' + + '#cc-consent-banner__accept{background:#f3f4f6;color:#0b0d10}' + + '#cc-consent-banner__accept:hover{background:#e5e7eb}}' + + 'html[data-cc-consent] #hs-banner-parent,' + + 'html[data-cc-consent] [data-hs-banner-host],' + + 'html[data-cc-consent] .hs-banner-wrapper,' + + 'html[data-cc-consent] #hs-eu-cookie-confirmation{display:none!important}'; + (document.head || document.documentElement).appendChild(style); + } + + function renderBanner() { + if (document.getElementById('cc-consent-banner')) return; + if (!document.body) return; + + injectStyles(); + + var banner = document.createElement('div'); + banner.id = 'cc-consent-banner'; + banner.setAttribute('role', 'dialog'); + banner.setAttribute('aria-live', 'polite'); + banner.setAttribute('aria-label', 'Cookie consent'); + + var copy = document.createElement('div'); + copy.id = 'cc-consent-banner__copy'; + var p1 = document.createElement('p'); + p1.appendChild(document.createTextNode( + 'This website stores cookies on your computer. These cookies are used to collect ' + + 'information about how you interact with our website and allow us to remember you. ' + + 'We use this information to improve and customize your browsing experience and for ' + + 'analytics and metrics about our visitors both on this website and other media. ' + + 'To find out more about the cookies we use, see our ' + )); + var link = document.createElement('a'); + link.href = PRIVACY_URL; + link.target = '_blank'; + link.rel = 'noopener'; + link.textContent = 'Privacy Policy'; + p1.appendChild(link); + p1.appendChild(document.createTextNode('.')); + var p2 = document.createElement('p'); + p2.textContent = + 'If you decline, your information won’t be tracked when you visit this website. ' + + 'A single cookie will be used in your browser to remember your preference not to be tracked.'; + copy.appendChild(p1); + copy.appendChild(p2); + + var actions = document.createElement('div'); + actions.id = 'cc-consent-banner__actions'; + var decline = document.createElement('button'); + decline.id = 'cc-consent-banner__decline'; + decline.type = 'button'; + decline.textContent = 'Decline All'; + var accept = document.createElement('button'); + accept.id = 'cc-consent-banner__accept'; + accept.type = 'button'; + accept.textContent = 'Accept All'; + actions.appendChild(decline); + actions.appendChild(accept); + + banner.appendChild(copy); + banner.appendChild(actions); + document.body.appendChild(banner); + + accept.addEventListener('click', function () { + applyConsent(true); + loadGTM(); + banner.remove(); + }); + decline.addEventListener('click', function () { + applyConsent(false); + banner.remove(); + }); + } + + // 2) Apply saved choice, or show banner. + var saved = null; + try { saved = window.localStorage.getItem(STORAGE_KEY); } catch (_) {} + + if (saved === 'granted') { + applyConsent(true); + loadGTM(); + } else if (saved === 'denied') { + applyConsent(false); + } else if (document.body) { + renderBanner(); + } else { + document.addEventListener('DOMContentLoaded', renderBanner); + } +})(); diff --git a/calls/android/actions.mdx b/calls/android/actions.mdx index f157f9524..0e0534980 100644 --- a/calls/android/actions.mdx +++ b/calls/android/actions.mdx @@ -1,8 +1,8 @@ --- title: "Actions" sidebarTitle: "Actions" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Actions for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Actions for Android" --- Use call actions to create your own custom controls or trigger call functionality dynamically based on your use case. All actions are called on the `CallSession` singleton instance during an active call session. diff --git a/calls/android/audio-modes.mdx b/calls/android/audio-modes.mdx index 7ada60b4c..cf5986c92 100644 --- a/calls/android/audio-modes.mdx +++ b/calls/android/audio-modes.mdx @@ -1,8 +1,8 @@ --- title: "Audio Modes" sidebarTitle: "Audio Modes" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Audio Modes for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Audio Modes for Android" --- Control audio output routing during calls. Switch between speaker, earpiece, Bluetooth, and wired headphones based on user preference or device availability. diff --git a/calls/android/authentication.mdx b/calls/android/authentication.mdx index 5d1bb327a..f64e0112d 100644 --- a/calls/android/authentication.mdx +++ b/calls/android/authentication.mdx @@ -1,8 +1,8 @@ --- title: "Authentication" sidebarTitle: "Authentication" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Authentication for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Authentication for Android" --- Before users can make or receive calls, they must be authenticated with the CometChat Calls SDK. This guide covers the login and logout methods. diff --git a/calls/android/background-handling.mdx b/calls/android/background-handling.mdx index 3bb883521..88128f6cb 100644 --- a/calls/android/background-handling.mdx +++ b/calls/android/background-handling.mdx @@ -1,8 +1,8 @@ --- title: "Background Handling" sidebarTitle: "Background Handling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Background Handling for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Background Handling for Android" --- Keep calls alive when users navigate away from your app. Background handling ensures the call continues running when users press the home button, switch to another app, or lock their device. diff --git a/calls/android/call-layouts.mdx b/calls/android/call-layouts.mdx index 436287507..4a1fb4b0f 100644 --- a/calls/android/call-layouts.mdx +++ b/calls/android/call-layouts.mdx @@ -1,8 +1,8 @@ --- title: "Call Layouts" sidebarTitle: "Call Layouts" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Layouts for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Layouts for Android" --- Choose how participants are displayed during a call. The SDK provides multiple layout options to suit different use cases like team meetings, presentations, or one-on-one calls. diff --git a/calls/android/call-logs.mdx b/calls/android/call-logs.mdx index ce00cbd2c..f36331382 100644 --- a/calls/android/call-logs.mdx +++ b/calls/android/call-logs.mdx @@ -1,8 +1,8 @@ --- title: "Call Logs" sidebarTitle: "Call Logs" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Logs for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Logs for Android" --- Retrieve call history for your application. Call logs provide detailed information about past calls including duration, participants, recordings, and status. diff --git a/calls/android/custom-control-panel.mdx b/calls/android/custom-control-panel.mdx index 24cd83aef..c67d468be 100644 --- a/calls/android/custom-control-panel.mdx +++ b/calls/android/custom-control-panel.mdx @@ -1,8 +1,8 @@ --- title: "Custom Control Panel" sidebarTitle: "Custom Control Panel" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Control Panel for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Control Panel for Android" --- Build a fully customized control panel for your call interface by hiding the default controls and implementing your own UI with call actions. This guide walks you through creating a custom control panel with essential call controls. diff --git a/calls/android/custom-participant-list.mdx b/calls/android/custom-participant-list.mdx index 9a511aa93..c3e6dd636 100644 --- a/calls/android/custom-participant-list.mdx +++ b/calls/android/custom-participant-list.mdx @@ -1,8 +1,8 @@ --- title: "Custom Participant List" sidebarTitle: "Custom Participant List" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Participant List for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Participant List for Android" --- Build a custom participant list UI that displays real-time participant information with full control over layout and interactions. This guide demonstrates how to hide the default participant list and create your own using participant events and actions. diff --git a/calls/android/events.mdx b/calls/android/events.mdx index 485f58d4e..be6aad77a 100644 --- a/calls/android/events.mdx +++ b/calls/android/events.mdx @@ -1,8 +1,8 @@ --- title: "Events" sidebarTitle: "Events" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Events for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Events for Android" --- Handle call session events to build responsive UIs. The SDK provides five event listener interfaces to monitor session status, participant activities, media changes, button clicks, and layout changes. Each listener is lifecycle-aware and automatically cleaned up when the Activity or Fragment is destroyed. diff --git a/calls/android/idle-timeout.mdx b/calls/android/idle-timeout.mdx index 55c625b2a..b7932697c 100644 --- a/calls/android/idle-timeout.mdx +++ b/calls/android/idle-timeout.mdx @@ -1,8 +1,8 @@ --- title: "Idle Timeout" sidebarTitle: "Idle Timeout" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Idle Timeout for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Idle Timeout for Android" --- Configure automatic session termination when a user is alone in a call. Idle timeout helps manage resources by ending sessions that have no active participants. diff --git a/calls/android/in-call-chat.mdx b/calls/android/in-call-chat.mdx index 661fa138b..823539945 100644 --- a/calls/android/in-call-chat.mdx +++ b/calls/android/in-call-chat.mdx @@ -1,8 +1,8 @@ --- title: "In-Call Chat" sidebarTitle: "In-Call Chat" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - In-Call Chat for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - In-Call Chat for Android" --- Add real-time messaging to your call experience using CometChat UI Kit. This allows participants to send text messages, share files, and communicate via chat while on a call. diff --git a/calls/android/join-session.mdx b/calls/android/join-session.mdx index af1a62a0f..c2056ea52 100644 --- a/calls/android/join-session.mdx +++ b/calls/android/join-session.mdx @@ -1,8 +1,8 @@ --- title: "Join Session" sidebarTitle: "Join Session" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Join Session for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Join Session for Android" --- Join a call session using one of two approaches: the quick start method with a session ID, or the advanced flow with manual token generation for more control. diff --git a/calls/android/migration-guide-v5.mdx b/calls/android/migration-guide-v5.mdx index e0380b422..8555f2e73 100644 --- a/calls/android/migration-guide-v5.mdx +++ b/calls/android/migration-guide-v5.mdx @@ -1,8 +1,8 @@ --- title: "Migration Guide" sidebarTitle: "v4 to v5 Migration" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Migration Guide for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Migration Guide for Android" --- This guide covers migrating from Calls SDK v4 to v5 for Android. diff --git a/calls/android/overview.mdx b/calls/android/overview.mdx index 017a89a9b..e27eaf981 100644 --- a/calls/android/overview.mdx +++ b/calls/android/overview.mdx @@ -1,13 +1,10 @@ --- title: "Calls SDK" sidebarTitle: "Overview" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Calls SDK for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Calls SDK for Android" --- - - This is a **beta release** of the Calls SDK v5. APIs and features may change before the stable release. For the current stable version, see the [Calls SDK v4 docs →](/calls/v4/android/overview). - The CometChat Calls SDK enables real-time voice and video calling capabilities in your Android application. Built on top of WebRTC, it provides a complete calling solution with built-in UI components and extensive customization options. ## Prerequisites diff --git a/calls/android/participant-management.mdx b/calls/android/participant-management.mdx index cce1dd320..22cb7cfd1 100644 --- a/calls/android/participant-management.mdx +++ b/calls/android/participant-management.mdx @@ -1,8 +1,8 @@ --- title: "Participant Management" sidebarTitle: "Participant Management" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Participant Management for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Participant Management for Android" --- Manage participants during a call with actions like muting, pausing video, and pinning. These features help maintain order in group calls and highlight important speakers. diff --git a/calls/android/picture-in-picture.mdx b/calls/android/picture-in-picture.mdx index 81409c888..4ab366402 100644 --- a/calls/android/picture-in-picture.mdx +++ b/calls/android/picture-in-picture.mdx @@ -1,8 +1,8 @@ --- title: "Picture-in-Picture" sidebarTitle: "Picture-in-Picture" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Picture-in-Picture for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Picture-in-Picture for Android" --- Enable Picture-in-Picture (PiP) mode to allow users to continue their call in a floating window while using other apps. PiP provides a seamless multitasking experience during calls. diff --git a/calls/android/raise-hand.mdx b/calls/android/raise-hand.mdx index d407de2ca..3a930fab8 100644 --- a/calls/android/raise-hand.mdx +++ b/calls/android/raise-hand.mdx @@ -1,8 +1,8 @@ --- title: "Raise Hand" sidebarTitle: "Raise Hand" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Raise Hand for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Raise Hand for Android" --- Allow participants to raise their hand to get attention during calls. This feature is useful for large meetings, webinars, or any scenario where participants need to signal they want to speak. diff --git a/calls/android/recording.mdx b/calls/android/recording.mdx index 8e815ccf0..6e585ecb2 100644 --- a/calls/android/recording.mdx +++ b/calls/android/recording.mdx @@ -1,8 +1,8 @@ --- title: "Recording" sidebarTitle: "Recording" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Recording for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Recording for Android" --- Record call sessions for later playback. Recordings are stored server-side and can be accessed through call logs or the CometChat Dashboard. diff --git a/calls/android/ringing.mdx b/calls/android/ringing.mdx index c95bc51f1..2ed81950e 100644 --- a/calls/android/ringing.mdx +++ b/calls/android/ringing.mdx @@ -1,8 +1,8 @@ --- title: "Ringing" sidebarTitle: "Ringing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Ringing for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Ringing for Android" --- Implement incoming and outgoing call notifications with accept/reject functionality. Ringing enables real-time call signaling between users, allowing them to initiate calls and respond to incoming call requests. diff --git a/calls/android/screen-sharing.mdx b/calls/android/screen-sharing.mdx index f732fb7e3..b3a3a65a2 100644 --- a/calls/android/screen-sharing.mdx +++ b/calls/android/screen-sharing.mdx @@ -1,8 +1,8 @@ --- title: "Screen Sharing" sidebarTitle: "Screen Sharing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Screen Sharing for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Screen Sharing for Android" --- View screen shares from other participants during a call. The Android SDK can receive and display screen shares initiated from web clients. diff --git a/calls/android/session-settings.mdx b/calls/android/session-settings.mdx index a75ee94f7..aef0e74ca 100644 --- a/calls/android/session-settings.mdx +++ b/calls/android/session-settings.mdx @@ -1,8 +1,8 @@ --- title: "SessionSettingsBuilder" sidebarTitle: "SessionSettingsBuilder" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - SessionSettingsBuilder for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - SessionSettingsBuilder for Android" --- The `SessionSettingsBuilder` is a powerful configuration tool that allows you to customize every aspect of your call session before participants join. From controlling the initial audio/video state to customizing the UI layout and hiding specific controls, this builder gives you complete control over the call experience. diff --git a/calls/android/setup.mdx b/calls/android/setup.mdx index e19b62a01..80360fc47 100644 --- a/calls/android/setup.mdx +++ b/calls/android/setup.mdx @@ -1,8 +1,8 @@ --- title: "Setup" sidebarTitle: "Setup" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Setup for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Setup for Android" --- @@ -59,14 +59,14 @@ Add the Calls SDK dependency to your **app level** `build.gradle` file: ```groovy dependencies { - implementation "com.cometchat:calls-sdk-android:5.0.0-beta.1" + implementation "com.cometchat:calls-sdk-android:5.0.0" } ``` ```kotlin dependencies { - implementation("com.cometchat:calls-sdk-android:5.0.0-beta.1") + implementation("com.cometchat:calls-sdk-android:5.0.0") } ``` diff --git a/calls/android/share-invite.mdx b/calls/android/share-invite.mdx index c837a2c79..7b3dbd120 100644 --- a/calls/android/share-invite.mdx +++ b/calls/android/share-invite.mdx @@ -1,8 +1,8 @@ --- title: "Share Invite" sidebarTitle: "Share Invite" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Share Invite for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Share Invite for Android" --- Enable participants to invite others to join a call by sharing a meeting link. The share invite button opens the system share sheet, allowing users to send the invite via any messaging app, email, or social media. diff --git a/calls/android/troubleshooting.mdx b/calls/android/troubleshooting.mdx index c5af2d9ee..fc395d558 100644 --- a/calls/android/troubleshooting.mdx +++ b/calls/android/troubleshooting.mdx @@ -1,7 +1,7 @@ --- title: "Troubleshooting" -description: "CometChat Calling SDK v5 - Beta Release - Troubleshooting for Android" -sdk_version: "5.x (Beta)" +description: "CometChat Calling SDK v5 - Troubleshooting for Android" +sdk_version: "5.x" --- ## Installation & Setup diff --git a/calls/android/voip-calling.mdx b/calls/android/voip-calling.mdx index 1608a66e5..55e37f4a2 100644 --- a/calls/android/voip-calling.mdx +++ b/calls/android/voip-calling.mdx @@ -1,8 +1,8 @@ --- title: "VoIP Calling" sidebarTitle: "VoIP Calling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - VoIP Calling for Android" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - VoIP Calling for Android" --- Implement native VoIP calling that works when your app is in the background or killed. This guide shows how to integrate Android's Telecom framework with CometChat to display system call UI, handle calls from the lock screen, and provide a native calling experience. diff --git a/calls/flutter/actions.mdx b/calls/flutter/actions.mdx index 5dfc499a3..4813f9946 100644 --- a/calls/flutter/actions.mdx +++ b/calls/flutter/actions.mdx @@ -1,8 +1,8 @@ --- title: "Actions" sidebarTitle: "Actions" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Actions for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Actions for Flutter" --- Use call actions to create your own custom controls or trigger call functionality dynamically based on your use case. All actions are called on the `CallSession` singleton instance during an active call session. diff --git a/calls/flutter/audio-modes.mdx b/calls/flutter/audio-modes.mdx index 6fc5d6f68..d9e7c9db4 100644 --- a/calls/flutter/audio-modes.mdx +++ b/calls/flutter/audio-modes.mdx @@ -1,8 +1,8 @@ --- title: "Audio Modes" sidebarTitle: "Audio Modes" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Audio Modes for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Audio Modes for Flutter" --- Control audio output routing during calls. Switch between speaker, earpiece, and Bluetooth based on user preference or device availability. diff --git a/calls/flutter/authentication.mdx b/calls/flutter/authentication.mdx index 69dc93d33..24dac0d9d 100644 --- a/calls/flutter/authentication.mdx +++ b/calls/flutter/authentication.mdx @@ -1,8 +1,8 @@ --- title: "Authentication" sidebarTitle: "Authentication" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Authentication for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Authentication for Flutter" --- Before users can make or receive calls, they must be authenticated with the CometChat Calls SDK. This guide covers the login and logout methods. diff --git a/calls/flutter/background-handling.mdx b/calls/flutter/background-handling.mdx index 2bc4e4490..433ab7b89 100644 --- a/calls/flutter/background-handling.mdx +++ b/calls/flutter/background-handling.mdx @@ -1,8 +1,8 @@ --- title: "Background Handling" sidebarTitle: "Background Handling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Background Handling for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Background Handling for Flutter" --- Keep calls alive when users navigate away from your app. Background handling ensures the call continues running when users press the home button, switch to another app, or lock their device. diff --git a/calls/flutter/call-layouts.mdx b/calls/flutter/call-layouts.mdx index 1e4ce9640..f4d3a0c40 100644 --- a/calls/flutter/call-layouts.mdx +++ b/calls/flutter/call-layouts.mdx @@ -1,8 +1,8 @@ --- title: "Call Layouts" sidebarTitle: "Call Layouts" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Layouts for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Layouts for Flutter" --- Choose how participants are displayed during a call. The SDK provides multiple layout options to suit different use cases like team meetings, presentations, or one-on-one calls. diff --git a/calls/flutter/call-logs.mdx b/calls/flutter/call-logs.mdx index 02bc0cd79..8c2d1286e 100644 --- a/calls/flutter/call-logs.mdx +++ b/calls/flutter/call-logs.mdx @@ -1,8 +1,8 @@ --- title: "Call Logs" sidebarTitle: "Call Logs" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Logs for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Logs for Flutter" --- Retrieve call history for your application. Call logs provide detailed information about past calls including duration, participants, recordings, and status. diff --git a/calls/flutter/custom-control-panel.mdx b/calls/flutter/custom-control-panel.mdx index 9b2c5cc3f..6bd472539 100644 --- a/calls/flutter/custom-control-panel.mdx +++ b/calls/flutter/custom-control-panel.mdx @@ -1,8 +1,8 @@ --- title: "Custom Control Panel" sidebarTitle: "Custom Control Panel" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Control Panel for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Control Panel for Flutter" --- Build a fully customized control panel for your call interface by hiding the default controls and implementing your own UI with call actions. This guide walks you through creating a custom control panel with essential call controls. diff --git a/calls/flutter/custom-participant-list.mdx b/calls/flutter/custom-participant-list.mdx index d4fb98bfc..0a2df56fa 100644 --- a/calls/flutter/custom-participant-list.mdx +++ b/calls/flutter/custom-participant-list.mdx @@ -1,8 +1,8 @@ --- title: "Custom Participant List" sidebarTitle: "Custom Participant List" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Participant List for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Participant List for Flutter" --- Build a custom participant list UI that displays real-time participant information with full control over layout and interactions. This guide demonstrates how to hide the default participant list and create your own using participant events and actions. diff --git a/calls/flutter/events.mdx b/calls/flutter/events.mdx index fad3a3b72..c3e5a5b85 100644 --- a/calls/flutter/events.mdx +++ b/calls/flutter/events.mdx @@ -1,8 +1,8 @@ --- title: "Events" sidebarTitle: "Events" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Events for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Events for Flutter" --- Handle call session events to build responsive UIs. The SDK provides five event listener interfaces to monitor session status, participant activities, media changes, button clicks, and layout changes. Unlike Android, Flutter listeners are not lifecycle-aware and must be manually removed in `dispose()` to prevent memory leaks. diff --git a/calls/flutter/idle-timeout.mdx b/calls/flutter/idle-timeout.mdx index 07d64ee64..5420ddf70 100644 --- a/calls/flutter/idle-timeout.mdx +++ b/calls/flutter/idle-timeout.mdx @@ -1,8 +1,8 @@ --- title: "Idle Timeout" sidebarTitle: "Idle Timeout" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Idle Timeout for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Idle Timeout for Flutter" --- Configure automatic session termination when a user is alone in a call. Idle timeout helps manage resources by ending sessions that have no active participants. diff --git a/calls/flutter/in-call-chat.mdx b/calls/flutter/in-call-chat.mdx index db4d4bc8b..35b759f1c 100644 --- a/calls/flutter/in-call-chat.mdx +++ b/calls/flutter/in-call-chat.mdx @@ -1,8 +1,8 @@ --- title: "In-Call Chat" sidebarTitle: "In-Call Chat" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - In-Call Chat for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - In-Call Chat for Flutter" --- Add real-time messaging to your call experience using CometChat UI Kit. This allows participants to send text messages, share files, and communicate via chat while on a call. diff --git a/calls/flutter/join-session.mdx b/calls/flutter/join-session.mdx index b8bc1866e..35d13a231 100644 --- a/calls/flutter/join-session.mdx +++ b/calls/flutter/join-session.mdx @@ -1,8 +1,8 @@ --- title: "Join Session" sidebarTitle: "Join Session" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Join Session for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Join Session for Flutter" --- Join a call session using one of two approaches: the quick start method with a session ID, or the advanced flow with manual token generation for more control. diff --git a/calls/flutter/migration-guide-v5.mdx b/calls/flutter/migration-guide-v5.mdx index 4a080c86d..9fdfd98f4 100644 --- a/calls/flutter/migration-guide-v5.mdx +++ b/calls/flutter/migration-guide-v5.mdx @@ -1,8 +1,8 @@ --- title: "Migration Guide" sidebarTitle: "v4 to v5 Migration" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Migration Guide for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Migration Guide for Flutter" --- This guide covers migrating from Calls SDK v4 to v5 for Flutter. diff --git a/calls/flutter/overview.mdx b/calls/flutter/overview.mdx index 27fe8a710..fce8bdafe 100644 --- a/calls/flutter/overview.mdx +++ b/calls/flutter/overview.mdx @@ -1,13 +1,10 @@ --- title: "Calls SDK" sidebarTitle: "Overview" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Calls SDK for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Calls SDK for Flutter" --- - - This is a **beta release** of the Calls SDK v5. APIs and features may change before the stable release. For the current stable version, see the [Calls SDK v4 docs →](/calls/v4/flutter/overview). - The CometChat Calls SDK enables real-time voice and video calling capabilities in your Flutter application. Built on top of WebRTC, it provides a complete calling solution with built-in UI components and extensive customization options. ## Prerequisites diff --git a/calls/flutter/participant-management.mdx b/calls/flutter/participant-management.mdx index 6a42b8ad2..52a36d97a 100644 --- a/calls/flutter/participant-management.mdx +++ b/calls/flutter/participant-management.mdx @@ -1,8 +1,8 @@ --- title: "Participant Management" sidebarTitle: "Participant Management" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Participant Management for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Participant Management for Flutter" --- Manage participants during a call with actions like muting, pausing video, and pinning. These features help maintain order in group calls and highlight important speakers. diff --git a/calls/flutter/picture-in-picture.mdx b/calls/flutter/picture-in-picture.mdx index 78db57bed..10a663127 100644 --- a/calls/flutter/picture-in-picture.mdx +++ b/calls/flutter/picture-in-picture.mdx @@ -1,8 +1,8 @@ --- title: "Picture-in-Picture" sidebarTitle: "Picture-in-Picture" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Picture-in-Picture for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Picture-in-Picture for Flutter" --- Enable Picture-in-Picture (PiP) mode to allow users to continue their call in a floating window while using other apps. PiP provides a seamless multitasking experience during calls. diff --git a/calls/flutter/raise-hand.mdx b/calls/flutter/raise-hand.mdx index af73fc1b5..8711746a8 100644 --- a/calls/flutter/raise-hand.mdx +++ b/calls/flutter/raise-hand.mdx @@ -1,8 +1,8 @@ --- title: "Raise Hand" sidebarTitle: "Raise Hand" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Raise Hand for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Raise Hand for Flutter" --- Allow participants to raise their hand to get attention during calls. This feature is useful for large meetings, webinars, or any scenario where participants need to signal they want to speak. diff --git a/calls/flutter/recording.mdx b/calls/flutter/recording.mdx index f3c6d3b67..89a7a85ef 100644 --- a/calls/flutter/recording.mdx +++ b/calls/flutter/recording.mdx @@ -1,8 +1,8 @@ --- title: "Recording" sidebarTitle: "Recording" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Recording for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Recording for Flutter" --- Record call sessions for later playback. Recordings are stored server-side and can be accessed through call logs or the CometChat Dashboard. diff --git a/calls/flutter/ringing.mdx b/calls/flutter/ringing.mdx index 26ce57da0..564978060 100644 --- a/calls/flutter/ringing.mdx +++ b/calls/flutter/ringing.mdx @@ -1,8 +1,8 @@ --- title: "Ringing" sidebarTitle: "Ringing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Ringing for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Ringing for Flutter" --- Implement incoming and outgoing call notifications with accept/reject functionality. Ringing enables real-time call signaling between users, allowing them to initiate calls and respond to incoming call requests. diff --git a/calls/flutter/screen-sharing.mdx b/calls/flutter/screen-sharing.mdx index 0cefe5e8a..2702a6de1 100644 --- a/calls/flutter/screen-sharing.mdx +++ b/calls/flutter/screen-sharing.mdx @@ -1,8 +1,8 @@ --- title: "Screen Sharing" sidebarTitle: "Screen Sharing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Screen Sharing for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Screen Sharing for Flutter" --- View screen shares from other participants during a call. The Flutter SDK can receive and display screen shares initiated from web clients. diff --git a/calls/flutter/session-settings.mdx b/calls/flutter/session-settings.mdx index 819d2254e..a66d27684 100644 --- a/calls/flutter/session-settings.mdx +++ b/calls/flutter/session-settings.mdx @@ -1,8 +1,8 @@ --- title: "SessionSettingsBuilder" sidebarTitle: "SessionSettingsBuilder" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - SessionSettingsBuilder for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - SessionSettingsBuilder for Flutter" --- The `SessionSettingsBuilder` is a powerful configuration tool that allows you to customize every aspect of your call session before participants join. From controlling the initial audio/video state to customizing the UI layout and hiding specific controls, this builder gives you complete control over the call experience. diff --git a/calls/flutter/setup.mdx b/calls/flutter/setup.mdx index 197b6f4d8..e01b67542 100644 --- a/calls/flutter/setup.mdx +++ b/calls/flutter/setup.mdx @@ -1,8 +1,8 @@ --- title: "Setup" sidebarTitle: "Setup" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Setup for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Setup for Flutter" --- @@ -30,7 +30,7 @@ Add the CometChat Cloudsmith hosted source to your `pubspec.yaml` file: dependencies: cometchat_calls_sdk: hosted: https://dart.cloudsmith.io/cometchat/cometchat/ - version: ^5.0.0-beta.2 + version: ^5.0.2 ``` ### Step 2: Install Dependencies diff --git a/calls/flutter/share-invite.mdx b/calls/flutter/share-invite.mdx index 28337198a..77698aada 100644 --- a/calls/flutter/share-invite.mdx +++ b/calls/flutter/share-invite.mdx @@ -1,8 +1,8 @@ --- title: "Share Invite" sidebarTitle: "Share Invite" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Share Invite for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Share Invite for Flutter" --- Enable participants to invite others to join a call by sharing a meeting link. The share invite button opens the platform's native share sheet, allowing users to send the invite via any messaging app, email, or social media. diff --git a/calls/flutter/troubleshooting.mdx b/calls/flutter/troubleshooting.mdx index d9e2d6816..d9936ece1 100644 --- a/calls/flutter/troubleshooting.mdx +++ b/calls/flutter/troubleshooting.mdx @@ -1,7 +1,7 @@ --- title: "Troubleshooting" -description: "CometChat Calling SDK v5 - Beta Release - Troubleshooting for Flutter" -sdk_version: "5.x (Beta)" +description: "CometChat Calling SDK v5 - Troubleshooting for Flutter" +sdk_version: "5.x" --- ## Installation & Setup diff --git a/calls/flutter/voip-calling.mdx b/calls/flutter/voip-calling.mdx index d83c30508..2cd52223c 100644 --- a/calls/flutter/voip-calling.mdx +++ b/calls/flutter/voip-calling.mdx @@ -1,8 +1,8 @@ --- title: "VoIP Calling" sidebarTitle: "VoIP Calling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - VoIP Calling for Flutter" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - VoIP Calling for Flutter" --- Implement native VoIP calling that works when your app is in the background or killed. This guide shows how to integrate platform-specific push notification services with CometChat to display system call UI and provide a native calling experience. diff --git a/calls/ionic/overview.mdx b/calls/ionic/overview.mdx index e20d3cb71..48f34258e 100644 --- a/calls/ionic/overview.mdx +++ b/calls/ionic/overview.mdx @@ -4,9 +4,6 @@ sidebarTitle: "Overview" description: "Overview of Calls SDK in CometChat." --- - - This is a **beta release** of the standalone Calls SDK. APIs and features may change before the stable release. For the current stable calling integration, see the [Ionic Calling Overview](/sdk/ionic-legacy/calling-overview). - Documentation coming soon for Ionic Calls SDK. diff --git a/calls/ios/actions.mdx b/calls/ios/actions.mdx index b0273601d..4c5049b0a 100644 --- a/calls/ios/actions.mdx +++ b/calls/ios/actions.mdx @@ -1,8 +1,8 @@ --- title: "Actions" sidebarTitle: "Actions" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Actions for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Actions for iOS" --- Use call actions to create your own custom controls or trigger call functionality dynamically based on your use case. All actions are called on the `CallSession.shared` singleton instance during an active call session. @@ -54,12 +54,12 @@ Unmutes your local microphone, resuming audio transmission. ```swift -CallSession.shared.unMuteAudio() +CallSession.shared.unmuteAudio() ``` ```objectivec -[[CallSession shared] unMuteAudio]; +[[CallSession shared] unmuteAudio]; ``` @@ -226,12 +226,12 @@ Pins a participant to keep them prominently displayed regardless of who is speak ```swift -CallSession.shared.pinParticipant() +CallSession.shared.pinParticipant(participantId: "PARTICIPANT_UID", type: "pin") ``` ```objectivec -[[CallSession shared] pinParticipant]; +[[CallSession shared] pinParticipantWithParticipantId:@"PARTICIPANT_UID" type:@"pin"]; ``` @@ -243,12 +243,12 @@ Removes the pin, returning to automatic speaker highlighting. ```swift -CallSession.shared.unPinParticipant() +CallSession.shared.unpinParticipant() ``` ```objectivec -[[CallSession shared] unPinParticipant]; +[[CallSession shared] unpinParticipant]; ``` diff --git a/calls/ios/audio-modes.mdx b/calls/ios/audio-modes.mdx index 7b19230fc..c3387cc9e 100644 --- a/calls/ios/audio-modes.mdx +++ b/calls/ios/audio-modes.mdx @@ -1,8 +1,8 @@ --- title: "Audio Modes" sidebarTitle: "Audio Modes" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Audio Modes for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Audio Modes for iOS" --- Control audio output routing during calls. Switch between speaker, earpiece, Bluetooth, and wired headphones based on user preference or device availability. diff --git a/calls/ios/authentication.mdx b/calls/ios/authentication.mdx index 91089b46b..a1109c89c 100644 --- a/calls/ios/authentication.mdx +++ b/calls/ios/authentication.mdx @@ -1,8 +1,8 @@ --- title: "Authentication" sidebarTitle: "Authentication" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Authentication for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Authentication for iOS" --- Before users can make or receive calls, they must be authenticated with the CometChat Calls SDK. This guide covers the login and logout methods. diff --git a/calls/ios/background-handling.mdx b/calls/ios/background-handling.mdx index 88b4a0994..6730b8652 100644 --- a/calls/ios/background-handling.mdx +++ b/calls/ios/background-handling.mdx @@ -1,8 +1,8 @@ --- title: "Background Handling" sidebarTitle: "Background Handling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Background Handling for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Background Handling for iOS" --- Keep calls alive when users navigate away from your app. Background handling ensures the call continues running when users press the home button, switch to another app, or lock their device. diff --git a/calls/ios/call-layouts.mdx b/calls/ios/call-layouts.mdx index 8a85de4e0..3acab446d 100644 --- a/calls/ios/call-layouts.mdx +++ b/calls/ios/call-layouts.mdx @@ -1,8 +1,8 @@ --- title: "Call Layouts" sidebarTitle: "Call Layouts" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Layouts for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Layouts for iOS" --- Choose how participants are displayed during a call. The SDK provides multiple layout options to suit different use cases like team meetings, presentations, or one-on-one calls. diff --git a/calls/ios/call-logs.mdx b/calls/ios/call-logs.mdx index 7d21250cb..d479c26d9 100644 --- a/calls/ios/call-logs.mdx +++ b/calls/ios/call-logs.mdx @@ -1,8 +1,8 @@ --- title: "Call Logs" sidebarTitle: "Call Logs" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Logs for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Logs for iOS" --- Retrieve call history for your application. Call logs provide detailed information about past calls including duration, participants, recordings, and status. diff --git a/calls/ios/custom-control-panel.mdx b/calls/ios/custom-control-panel.mdx index dde56a39f..6991d9721 100644 --- a/calls/ios/custom-control-panel.mdx +++ b/calls/ios/custom-control-panel.mdx @@ -1,8 +1,8 @@ --- title: "Custom Control Panel" sidebarTitle: "Custom Control Panel" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Control Panel for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Control Panel for iOS" --- Build a fully customized control panel for your call interface by hiding the default controls and implementing your own UI with call actions. This guide walks you through creating a custom control panel with essential call controls. @@ -241,7 +241,7 @@ private func setupControlListeners() { @objc private func toggleAudio() { if isAudioMuted { - CallSession.shared.unMuteAudio() + CallSession.shared.unmuteAudio() } else { CallSession.shared.muteAudio() } @@ -281,7 +281,7 @@ private func setupControlListeners() { - (void)toggleAudio { if (self.isAudioMuted) { - [[CallSession shared] unMuteAudio]; + [[CallSession shared] unmuteAudio]; } else { [[CallSession shared] muteAudio]; } diff --git a/calls/ios/custom-participant-list.mdx b/calls/ios/custom-participant-list.mdx index cdddee85f..81403e4b1 100644 --- a/calls/ios/custom-participant-list.mdx +++ b/calls/ios/custom-participant-list.mdx @@ -1,8 +1,8 @@ --- title: "Custom Participant List" sidebarTitle: "Custom Participant List" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Participant List for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Participant List for iOS" --- Build a custom participant list UI that displays real-time participant information with full control over layout and interactions. This guide demonstrates how to hide the default participant list and create your own using participant events and actions. @@ -514,9 +514,9 @@ extension ParticipantListViewController: UITableViewDelegate, UITableViewDataSou cell.onPinAction = { [weak self] participant in if participant.isPinned { - CallSession.shared.unPinParticipant() + CallSession.shared.unpinParticipant() } else { - CallSession.shared.pinParticipant(participant.uid) + CallSession.shared.pinParticipant(participantId: participant.uid, type: "pin") } } @@ -558,9 +558,9 @@ extension ParticipantListViewController: UISearchBarDelegate { cell.onPinAction = ^(Participant *p) { if (p.isPinned) { - [[CallSession shared] unPinParticipant]; + [[CallSession shared] unpinParticipant]; } else { - [[CallSession shared] pinParticipant:p.uid]; + [[CallSession shared] pinParticipantWithParticipantId:p.uid type:@"pin"]; } }; diff --git a/calls/ios/events.mdx b/calls/ios/events.mdx index c51d41ed6..b03b00648 100644 --- a/calls/ios/events.mdx +++ b/calls/ios/events.mdx @@ -1,8 +1,8 @@ --- title: "Events" sidebarTitle: "Events" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Events for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Events for iOS" --- Handle call session events to build responsive UIs. The SDK provides five event listener protocols to monitor session status, participant activities, media changes, button clicks, and layout changes. diff --git a/calls/ios/idle-timeout.mdx b/calls/ios/idle-timeout.mdx index f2cca78c6..0c52c11b1 100644 --- a/calls/ios/idle-timeout.mdx +++ b/calls/ios/idle-timeout.mdx @@ -1,8 +1,8 @@ --- title: "Idle Timeout" sidebarTitle: "Idle Timeout" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Idle Timeout for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Idle Timeout for iOS" --- Configure automatic session termination when a user is alone in a call. Idle timeout helps manage resources by ending sessions that have no active participants. diff --git a/calls/ios/in-call-chat.mdx b/calls/ios/in-call-chat.mdx index de337faa6..f1401f069 100644 --- a/calls/ios/in-call-chat.mdx +++ b/calls/ios/in-call-chat.mdx @@ -1,8 +1,8 @@ --- title: "In-Call Chat" sidebarTitle: "In-Call Chat" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - In-Call Chat for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - In-Call Chat for iOS" --- Add real-time messaging to your call experience using CometChat UI Kit. This allows participants to send text messages, share files, and communicate via chat while on a call. diff --git a/calls/ios/join-session.mdx b/calls/ios/join-session.mdx index 2f2d13b85..c222e54cb 100644 --- a/calls/ios/join-session.mdx +++ b/calls/ios/join-session.mdx @@ -1,8 +1,8 @@ --- title: "Join Session" sidebarTitle: "Join Session" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Join Session for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Join Session for iOS" --- Join a call session using one of two approaches: the quick start method with a session ID, or the advanced flow with manual token generation for more control. diff --git a/calls/ios/migration-guide-v5.mdx b/calls/ios/migration-guide-v5.mdx index cd2428804..0a620d5c0 100644 --- a/calls/ios/migration-guide-v5.mdx +++ b/calls/ios/migration-guide-v5.mdx @@ -1,8 +1,8 @@ --- title: "Migration Guide" sidebarTitle: "v4 to v5 Migration" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Migration Guide for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Migration Guide for iOS" --- This guide covers migrating from Calls SDK v4 to v5 for iOS. diff --git a/calls/ios/overview.mdx b/calls/ios/overview.mdx index d3b9a33dd..ff687bea7 100644 --- a/calls/ios/overview.mdx +++ b/calls/ios/overview.mdx @@ -1,13 +1,10 @@ --- title: "Calls SDK" sidebarTitle: "Overview" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Calls SDK for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Calls SDK for iOS" --- - - This is a **beta release** of the Calls SDK v5. APIs and features may change before the stable release. For the current stable version, see the [Calls SDK v4 docs →](/calls/v4/ios/overview). - The CometChat Calls SDK enables real-time voice and video calling capabilities in your iOS application. Built on top of WebRTC, it provides a complete calling solution with built-in UI components and extensive customization options. ## Prerequisites diff --git a/calls/ios/participant-management.mdx b/calls/ios/participant-management.mdx index a35709f4d..72c1040ae 100644 --- a/calls/ios/participant-management.mdx +++ b/calls/ios/participant-management.mdx @@ -1,8 +1,8 @@ --- title: "Participant Management" sidebarTitle: "Participant Management" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Participant Management for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Participant Management for iOS" --- Manage participants during a call with actions like muting, pausing video, and pinning. These features help maintain order in group calls and highlight important speakers. @@ -53,19 +53,19 @@ Pin a participant to keep them prominently displayed regardless of who is speaki ```swift // Pin a participant -CallSession.shared.pinParticipant() +CallSession.shared.pinParticipant(participantId: "PARTICIPANT_UID", type: "pin") // Unpin (returns to automatic speaker highlighting) -CallSession.shared.unPinParticipant() +CallSession.shared.unpinParticipant() ``` ```objectivec // Pin a participant -[[CallSession shared] pinParticipant]; +[[CallSession shared] pinParticipantWithParticipantId:@"PARTICIPANT_UID" type:@"pin"]; // Unpin (returns to automatic speaker highlighting) -[[CallSession shared] unPinParticipant]; +[[CallSession shared] unpinParticipant]; ``` diff --git a/calls/ios/picture-in-picture.mdx b/calls/ios/picture-in-picture.mdx index 434120faa..02909983b 100644 --- a/calls/ios/picture-in-picture.mdx +++ b/calls/ios/picture-in-picture.mdx @@ -1,8 +1,8 @@ --- title: "Picture-in-Picture" sidebarTitle: "Picture-in-Picture" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Picture-in-Picture for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Picture-in-Picture for iOS" --- Enable Picture-in-Picture (PiP) mode to allow users to continue their call in a floating window while using other apps. PiP provides a seamless multitasking experience during calls. diff --git a/calls/ios/raise-hand.mdx b/calls/ios/raise-hand.mdx index 3d12c79ca..7128fdbec 100644 --- a/calls/ios/raise-hand.mdx +++ b/calls/ios/raise-hand.mdx @@ -1,8 +1,8 @@ --- title: "Raise Hand" sidebarTitle: "Raise Hand" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Raise Hand for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Raise Hand for iOS" --- Allow participants to raise their hand to get attention during calls. This feature is useful for large meetings, webinars, or any scenario where participants need to signal they want to speak. diff --git a/calls/ios/recording.mdx b/calls/ios/recording.mdx index 279e9ab19..27f01260d 100644 --- a/calls/ios/recording.mdx +++ b/calls/ios/recording.mdx @@ -1,8 +1,8 @@ --- title: "Recording" sidebarTitle: "Recording" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Recording for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Recording for iOS" --- Record call sessions for later playback. Recordings are stored server-side and can be accessed through call logs or the CometChat Dashboard. diff --git a/calls/ios/ringing.mdx b/calls/ios/ringing.mdx index 6ec784860..b57fba96d 100644 --- a/calls/ios/ringing.mdx +++ b/calls/ios/ringing.mdx @@ -1,8 +1,8 @@ --- title: "Ringing" sidebarTitle: "Ringing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Ringing for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Ringing for iOS" --- Implement incoming and outgoing call notifications with accept/reject functionality. Ringing enables real-time call signaling between users, allowing them to initiate calls and respond to incoming call requests. diff --git a/calls/ios/screen-sharing.mdx b/calls/ios/screen-sharing.mdx index 3701a4b24..6b0d8ffdb 100644 --- a/calls/ios/screen-sharing.mdx +++ b/calls/ios/screen-sharing.mdx @@ -1,8 +1,8 @@ --- title: "Screen Sharing" sidebarTitle: "Screen Sharing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Screen Sharing for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Screen Sharing for iOS" --- View screen shares from other participants during a call. The iOS SDK can receive and display screen shares initiated from web clients. diff --git a/calls/ios/session-settings.mdx b/calls/ios/session-settings.mdx index 23e4ed3ad..185ea7cd9 100644 --- a/calls/ios/session-settings.mdx +++ b/calls/ios/session-settings.mdx @@ -1,8 +1,8 @@ --- title: "SessionSettingsBuilder" sidebarTitle: "SessionSettingsBuilder" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - SessionSettingsBuilder for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - SessionSettingsBuilder for iOS" --- The `SessionSettingsBuilder` is a powerful configuration tool that allows you to customize every aspect of your call session before participants join. From controlling the initial audio/video state to customizing the UI layout and hiding specific controls, this builder gives you complete control over the call experience. diff --git a/calls/ios/setup.mdx b/calls/ios/setup.mdx index 3850b140d..190a1bf41 100644 --- a/calls/ios/setup.mdx +++ b/calls/ios/setup.mdx @@ -1,8 +1,8 @@ --- title: "Setup" sidebarTitle: "Setup" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Setup for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Setup for iOS" --- @@ -31,7 +31,7 @@ platform :ios, '16.0' use_frameworks! target 'YourApp' do - pod 'CometChatCallsSDK', '~> 5.0.0-beta.2' + pod 'CometChatCallsSDK', '~> 5.0.0' end ``` diff --git a/calls/ios/share-invite.mdx b/calls/ios/share-invite.mdx index b87852b8d..311d4b0d5 100644 --- a/calls/ios/share-invite.mdx +++ b/calls/ios/share-invite.mdx @@ -1,8 +1,8 @@ --- title: "Share Invite" sidebarTitle: "Share Invite" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Share Invite for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Share Invite for iOS" --- Enable participants to invite others to join a call by sharing a meeting link. The share invite button opens the system share sheet, allowing users to send the invite via any messaging app, email, or social media. diff --git a/calls/ios/troubleshooting.mdx b/calls/ios/troubleshooting.mdx index 929afd24b..4cb5def8b 100644 --- a/calls/ios/troubleshooting.mdx +++ b/calls/ios/troubleshooting.mdx @@ -1,7 +1,7 @@ --- title: "Troubleshooting" -description: "CometChat Calling SDK v5 - Beta Release - Troubleshooting for iOS" -sdk_version: "5.x (Beta)" +description: "CometChat Calling SDK v5 - Troubleshooting for iOS" +sdk_version: "5.x" --- ## Installation & Setup diff --git a/calls/ios/voip-calling.mdx b/calls/ios/voip-calling.mdx index a5e86aa80..86cc01603 100644 --- a/calls/ios/voip-calling.mdx +++ b/calls/ios/voip-calling.mdx @@ -1,8 +1,8 @@ --- title: "VoIP Calling" sidebarTitle: "VoIP Calling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - VoIP Calling for iOS" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - VoIP Calling for iOS" --- Implement native VoIP calling that works when your app is in the background or killed. This guide shows how to integrate Apple's CallKit framework with CometChat to display system call UI, handle calls from the lock screen, and provide a native calling experience. @@ -490,7 +490,7 @@ extension CallManager: CXProviderDelegate { if action.isMuted { CallSession.shared.muteAudio() } else { - CallSession.shared.unMuteAudio() + CallSession.shared.unmuteAudio() } action.fulfill() } @@ -581,7 +581,7 @@ extension CallManager: CXProviderDelegate { if (action.isMuted) { [[CallSession shared] muteAudio]; } else { - [[CallSession shared] unMuteAudio]; + [[CallSession shared] unmuteAudio]; } [action fulfill]; } diff --git a/calls/javascript/actions.mdx b/calls/javascript/actions.mdx index d6653bed1..b201aec79 100644 --- a/calls/javascript/actions.mdx +++ b/calls/javascript/actions.mdx @@ -1,8 +1,8 @@ --- title: "Actions" sidebarTitle: "Actions" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Actions for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Actions for JavaScript" --- Use call actions to create your own custom controls or trigger call functionality dynamically based on your use case. All actions are called on the `CometChatCalls` class during an active call session. diff --git a/calls/javascript/angular-integration.mdx b/calls/javascript/angular-integration.mdx index b1b7dce66..23eacef13 100644 --- a/calls/javascript/angular-integration.mdx +++ b/calls/javascript/angular-integration.mdx @@ -1,8 +1,8 @@ --- title: "Angular Integration" sidebarTitle: "Angular" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Angular Integration for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Angular Integration for JavaScript" --- This guide walks you through integrating the CometChat Calls SDK into an Angular application. By the end, you'll have a working video call implementation with proper service architecture and lifecycle management. diff --git a/calls/javascript/authentication.mdx b/calls/javascript/authentication.mdx index aac6c07ca..e4d70f671 100644 --- a/calls/javascript/authentication.mdx +++ b/calls/javascript/authentication.mdx @@ -1,8 +1,8 @@ --- title: "Authentication" sidebarTitle: "Authentication" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Authentication for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Authentication for JavaScript" --- Before users can make or receive calls, they must be authenticated with the CometChat Calls SDK. This guide covers the login and logout methods. diff --git a/calls/javascript/call-layouts.mdx b/calls/javascript/call-layouts.mdx index 8c1f10869..afe1909c0 100644 --- a/calls/javascript/call-layouts.mdx +++ b/calls/javascript/call-layouts.mdx @@ -1,8 +1,8 @@ --- title: "Call Layouts" sidebarTitle: "Call Layouts" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Layouts for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Layouts for JavaScript" --- The CometChat Calls SDK provides three layout modes to display participants during a call. Each participant can independently choose their preferred layout without affecting others. diff --git a/calls/javascript/call-logs.mdx b/calls/javascript/call-logs.mdx index e9a59c029..d7357e115 100644 --- a/calls/javascript/call-logs.mdx +++ b/calls/javascript/call-logs.mdx @@ -1,8 +1,8 @@ --- title: "Call Logs" sidebarTitle: "Call Logs" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Logs for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Logs for JavaScript" --- Retrieve call history and details using the CometChat REST API. Call logs provide information about past calls including participants, duration, and recording URLs. diff --git a/calls/javascript/custom-control-panel.mdx b/calls/javascript/custom-control-panel.mdx index baa390c08..fa07fe8cb 100644 --- a/calls/javascript/custom-control-panel.mdx +++ b/calls/javascript/custom-control-panel.mdx @@ -1,8 +1,8 @@ --- title: "Custom Control Panel" sidebarTitle: "Custom Control Panel" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Control Panel for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Control Panel for JavaScript" --- Build a custom control panel by hiding the default UI and using the SDK's action methods to control call functionality. diff --git a/calls/javascript/device-management.mdx b/calls/javascript/device-management.mdx index 7e9c840e4..109b4f661 100644 --- a/calls/javascript/device-management.mdx +++ b/calls/javascript/device-management.mdx @@ -1,8 +1,8 @@ --- title: "Device Management" sidebarTitle: "Device Management" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Device Management for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Device Management for JavaScript" --- Manage audio and video devices during calls, including selecting microphones, speakers, and cameras. diff --git a/calls/javascript/events.mdx b/calls/javascript/events.mdx index 94e5a7d46..a93f09651 100644 --- a/calls/javascript/events.mdx +++ b/calls/javascript/events.mdx @@ -1,8 +1,8 @@ --- title: "Events" sidebarTitle: "Events" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Events for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Events for JavaScript" --- Handle call session events to build responsive UIs. The SDK provides event listeners to monitor session status, participant activities, media changes, button clicks, and layout changes. diff --git a/calls/javascript/idle-timeout.mdx b/calls/javascript/idle-timeout.mdx index 18ceaa34f..fe3099618 100644 --- a/calls/javascript/idle-timeout.mdx +++ b/calls/javascript/idle-timeout.mdx @@ -1,8 +1,8 @@ --- title: "Idle Timeout" sidebarTitle: "Idle Timeout" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Idle Timeout for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Idle Timeout for JavaScript" --- The idle timeout feature automatically ends a call session when you're the only participant remaining. This prevents sessions from running indefinitely and consuming resources. diff --git a/calls/javascript/in-call-chat.mdx b/calls/javascript/in-call-chat.mdx index fcf3abf9a..a08c3f4a9 100644 --- a/calls/javascript/in-call-chat.mdx +++ b/calls/javascript/in-call-chat.mdx @@ -1,8 +1,8 @@ --- title: "In-Call Chat" sidebarTitle: "In-Call Chat" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - In-Call Chat for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - In-Call Chat for JavaScript" --- Enable text messaging during calls by integrating the in-call chat feature. The SDK provides a chat button in the control panel and events to help you build a custom chat experience. diff --git a/calls/javascript/ionic-integration.mdx b/calls/javascript/ionic-integration.mdx index 8fa1ff35b..4b4f4fa88 100644 --- a/calls/javascript/ionic-integration.mdx +++ b/calls/javascript/ionic-integration.mdx @@ -1,8 +1,8 @@ --- title: "Ionic Integration" sidebarTitle: "Ionic" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Ionic Integration for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Ionic Integration for JavaScript" --- This guide walks you through integrating the CometChat Calls SDK into an Ionic application. By the end, you'll have a working video call implementation with proper authentication and lifecycle handling. This guide covers Ionic with Angular, React, and Vue. diff --git a/calls/javascript/join-session.mdx b/calls/javascript/join-session.mdx index e7396fee9..690da5d66 100644 --- a/calls/javascript/join-session.mdx +++ b/calls/javascript/join-session.mdx @@ -1,8 +1,8 @@ --- title: "Join Session" sidebarTitle: "Join Session" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Join Session for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Join Session for JavaScript" --- Join a call session using one of two approaches: the quick start method with a session ID, or the advanced flow with manual token generation for more control. diff --git a/calls/javascript/migration-guide-v5.mdx b/calls/javascript/migration-guide-v5.mdx index 637b1df2e..ab15d5ee2 100644 --- a/calls/javascript/migration-guide-v5.mdx +++ b/calls/javascript/migration-guide-v5.mdx @@ -1,8 +1,8 @@ --- title: "Migration Guide" sidebarTitle: "v4 to v5 Migration" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Migration Guide for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Migration Guide for JavaScript" --- This guide covers migrating from Calls SDK v4 to v5 for JavaScript (React, Vue, Angular, etc.). diff --git a/calls/javascript/nextjs-integration.mdx b/calls/javascript/nextjs-integration.mdx index 8673eb2a4..20d5aa520 100644 --- a/calls/javascript/nextjs-integration.mdx +++ b/calls/javascript/nextjs-integration.mdx @@ -1,8 +1,8 @@ --- title: "Next.js Integration" sidebarTitle: "Next.js" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Next.js Integration for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Next.js Integration for JavaScript" --- This guide walks you through integrating the CometChat Calls SDK into a Next.js application. By the end, you'll have a working video call implementation with proper server-side rendering handling and authentication. diff --git a/calls/javascript/overview.mdx b/calls/javascript/overview.mdx index 0ece45264..6bd8adb7d 100644 --- a/calls/javascript/overview.mdx +++ b/calls/javascript/overview.mdx @@ -1,13 +1,10 @@ --- title: "Calls SDK" sidebarTitle: "Overview" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Calls SDK for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Calls SDK for JavaScript" --- - - This is a **beta release** of the Calls SDK v5. APIs and features may change before the stable release. For the current stable version, see the [Calls SDK v4 docs →](/calls/v4/javascript/overview). - The CometChat Calls SDK enables real-time voice and video calling capabilities in your web application. Built on top of WebRTC, it provides a complete calling solution with built-in UI components and extensive customization options. ## Prerequisites diff --git a/calls/javascript/participant-management.mdx b/calls/javascript/participant-management.mdx index 173a39983..72d35ae54 100644 --- a/calls/javascript/participant-management.mdx +++ b/calls/javascript/participant-management.mdx @@ -1,8 +1,8 @@ --- title: "Participant Management" sidebarTitle: "Participant Management" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Participant Management for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Participant Management for JavaScript" --- Manage call participants including muting, pinning, and monitoring their status during a call. diff --git a/calls/javascript/permissions-handling.mdx b/calls/javascript/permissions-handling.mdx index f49ffe09b..d3b850562 100644 --- a/calls/javascript/permissions-handling.mdx +++ b/calls/javascript/permissions-handling.mdx @@ -1,8 +1,8 @@ --- title: "Permissions Handling" sidebarTitle: "Permissions Handling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Permissions Handling for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Permissions Handling for JavaScript" --- Handle camera and microphone permissions gracefully to provide a good user experience when joining calls. diff --git a/calls/javascript/picture-in-picture.mdx b/calls/javascript/picture-in-picture.mdx index 0a27d92eb..914115a7b 100644 --- a/calls/javascript/picture-in-picture.mdx +++ b/calls/javascript/picture-in-picture.mdx @@ -1,8 +1,8 @@ --- title: "Picture-in-Picture" sidebarTitle: "Picture-in-Picture" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Picture-in-Picture for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Picture-in-Picture for JavaScript" --- Picture-in-Picture (PiP) allows the call video to continue playing in a floating window while users interact with other content on the page or other browser tabs. diff --git a/calls/javascript/raise-hand.mdx b/calls/javascript/raise-hand.mdx index fde77fc5e..11051ba16 100644 --- a/calls/javascript/raise-hand.mdx +++ b/calls/javascript/raise-hand.mdx @@ -1,8 +1,8 @@ --- title: "Raise Hand" sidebarTitle: "Raise Hand" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Raise Hand for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Raise Hand for JavaScript" --- The raise hand feature allows participants to signal that they want to speak or get attention during a call without interrupting the current speaker. diff --git a/calls/javascript/react-integration.mdx b/calls/javascript/react-integration.mdx index 14f6609ba..676310e97 100644 --- a/calls/javascript/react-integration.mdx +++ b/calls/javascript/react-integration.mdx @@ -1,8 +1,8 @@ --- title: "React Integration" sidebarTitle: "React" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - React Integration for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - React Integration for JavaScript" --- This guide walks you through integrating the CometChat Calls SDK into a React application. By the end, you'll have a working video call implementation with proper state management and lifecycle handling. diff --git a/calls/javascript/recording.mdx b/calls/javascript/recording.mdx index f13414edf..d9ee2a6ec 100644 --- a/calls/javascript/recording.mdx +++ b/calls/javascript/recording.mdx @@ -1,8 +1,8 @@ --- title: "Recording" sidebarTitle: "Recording" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Recording for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Recording for JavaScript" --- Record call sessions for later playback, compliance, or training purposes. Recordings are stored server-side and can be accessed through the CometChat dashboard. diff --git a/calls/javascript/ringing.mdx b/calls/javascript/ringing.mdx index 3b4abfe7f..2dd1715a0 100644 --- a/calls/javascript/ringing.mdx +++ b/calls/javascript/ringing.mdx @@ -1,8 +1,8 @@ --- title: "Ringing" sidebarTitle: "Ringing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Ringing for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Ringing for JavaScript" --- Implement incoming and outgoing call notifications by integrating the Calls SDK with the CometChat Chat SDK for call signaling. diff --git a/calls/javascript/screen-sharing.mdx b/calls/javascript/screen-sharing.mdx index e53cc95af..416b4f42e 100644 --- a/calls/javascript/screen-sharing.mdx +++ b/calls/javascript/screen-sharing.mdx @@ -1,8 +1,8 @@ --- title: "Screen Sharing" sidebarTitle: "Screen Sharing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Screen Sharing for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Screen Sharing for JavaScript" --- Share your screen with other participants during a call. The browser will prompt users to select which screen, window, or browser tab to share. diff --git a/calls/javascript/session-settings.mdx b/calls/javascript/session-settings.mdx index f3ff5c8b9..ee82edfca 100644 --- a/calls/javascript/session-settings.mdx +++ b/calls/javascript/session-settings.mdx @@ -1,8 +1,8 @@ --- title: "Session Settings" sidebarTitle: "Session Settings" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Session Settings for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Session Settings for JavaScript" --- The session settings object allows you to customize every aspect of your call session before participants join. From controlling the initial audio/video state to customizing the UI layout and hiding specific controls, these settings give you complete control over the call experience. diff --git a/calls/javascript/setup.mdx b/calls/javascript/setup.mdx index 1ed23242f..c25333b5e 100644 --- a/calls/javascript/setup.mdx +++ b/calls/javascript/setup.mdx @@ -1,8 +1,8 @@ --- title: "Setup" sidebarTitle: "Setup" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Setup for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Setup for JavaScript" --- @@ -27,12 +27,12 @@ Install the CometChat Calls SDK using npm or yarn: ```bash -npm install @cometchat/calls-sdk-javascript@5.0.0-beta.1 +npm install @cometchat/calls-sdk-javascript@5.0.0 ``` ```bash -yarn add @cometchat/calls-sdk-javascript@5.0.0-beta.1 +yarn add @cometchat/calls-sdk-javascript@5.0.0 ``` diff --git a/calls/javascript/share-invite.mdx b/calls/javascript/share-invite.mdx index 341e31080..be323baee 100644 --- a/calls/javascript/share-invite.mdx +++ b/calls/javascript/share-invite.mdx @@ -1,8 +1,8 @@ --- title: "Share Invite" sidebarTitle: "Share Invite" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Share Invite for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Share Invite for JavaScript" --- Allow participants to share call invitations with others using the share invite feature. diff --git a/calls/javascript/troubleshooting.mdx b/calls/javascript/troubleshooting.mdx index 01280c289..5ff361c46 100644 --- a/calls/javascript/troubleshooting.mdx +++ b/calls/javascript/troubleshooting.mdx @@ -1,7 +1,7 @@ --- title: "Troubleshooting" -description: "CometChat Calling SDK v5 - Beta Release - Troubleshooting for JavaScript" -sdk_version: "5.x (Beta)" +description: "CometChat Calling SDK v5 - Troubleshooting for JavaScript" +sdk_version: "5.x" --- ## Installation & Setup diff --git a/calls/javascript/virtual-background.mdx b/calls/javascript/virtual-background.mdx index ce9457a92..89b0e914c 100644 --- a/calls/javascript/virtual-background.mdx +++ b/calls/javascript/virtual-background.mdx @@ -1,8 +1,8 @@ --- title: "Virtual Background" sidebarTitle: "Virtual Background" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Virtual Background for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Virtual Background for JavaScript" --- Apply virtual backgrounds to your video feed during calls. You can blur your background or replace it with a custom image. diff --git a/calls/javascript/vue-integration.mdx b/calls/javascript/vue-integration.mdx index e8d9c4445..24fb251c4 100644 --- a/calls/javascript/vue-integration.mdx +++ b/calls/javascript/vue-integration.mdx @@ -1,8 +1,8 @@ --- title: "Vue Integration" sidebarTitle: "Vue" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Vue Integration for JavaScript" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Vue Integration for JavaScript" --- This guide walks you through integrating the CometChat Calls SDK into a Vue.js application. By the end, you'll have a working video call implementation with proper state management and lifecycle handling. diff --git a/calls/react-native/actions.mdx b/calls/react-native/actions.mdx index 62aa250ae..2b05d3c5e 100644 --- a/calls/react-native/actions.mdx +++ b/calls/react-native/actions.mdx @@ -1,8 +1,8 @@ --- title: "Actions" sidebarTitle: "Actions" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Actions for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Actions for React Native" --- Control the active call session programmatically using the static methods on `CometChatCalls`. These methods allow you to manage audio, video, screen sharing, and other call features. diff --git a/calls/react-native/audio-modes.mdx b/calls/react-native/audio-modes.mdx index 055f04055..010000f31 100644 --- a/calls/react-native/audio-modes.mdx +++ b/calls/react-native/audio-modes.mdx @@ -1,8 +1,8 @@ --- title: "Audio Modes" sidebarTitle: "Audio Modes" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Audio Modes for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Audio Modes for React Native" --- The CometChat Calls SDK supports multiple audio output modes on mobile devices. Users can switch between speaker, earpiece, Bluetooth, and wired headphones. diff --git a/calls/react-native/authentication.mdx b/calls/react-native/authentication.mdx index d4ccb26f0..1d3952161 100644 --- a/calls/react-native/authentication.mdx +++ b/calls/react-native/authentication.mdx @@ -1,8 +1,8 @@ --- title: "Authentication" sidebarTitle: "Authentication" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Authentication for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Authentication for React Native" --- This guide covers initializing the CometChat Calls SDK and authenticating users in your React Native application. diff --git a/calls/react-native/background-handling.mdx b/calls/react-native/background-handling.mdx index 6b88ecb86..4370938e3 100644 --- a/calls/react-native/background-handling.mdx +++ b/calls/react-native/background-handling.mdx @@ -1,8 +1,8 @@ --- title: "Background Handling" sidebarTitle: "Background Handling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Background Handling for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Background Handling for React Native" --- Keep calls active when your app goes to the background. This requires platform-specific configuration to maintain audio/video streams and handle system interruptions. diff --git a/calls/react-native/call-layouts.mdx b/calls/react-native/call-layouts.mdx index 3c9f96d09..a97cf0bae 100644 --- a/calls/react-native/call-layouts.mdx +++ b/calls/react-native/call-layouts.mdx @@ -1,8 +1,8 @@ --- title: "Call Layouts" sidebarTitle: "Call Layouts" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Layouts for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Layouts for React Native" --- The CometChat Calls SDK provides three layout modes for displaying participants during a call. You can set the initial layout in call settings or change it programmatically during the call. diff --git a/calls/react-native/call-logs.mdx b/calls/react-native/call-logs.mdx index 5e6f5e115..2da20e665 100644 --- a/calls/react-native/call-logs.mdx +++ b/calls/react-native/call-logs.mdx @@ -1,8 +1,8 @@ --- title: "Call Logs" sidebarTitle: "Call Logs" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Call Logs for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Call Logs for React Native" --- Call logs provide a history of calls made through your application. You can retrieve call logs using the CometChat Chat SDK's call log APIs. diff --git a/calls/react-native/custom-control-panel.mdx b/calls/react-native/custom-control-panel.mdx index 1e935299a..bd54ef4cb 100644 --- a/calls/react-native/custom-control-panel.mdx +++ b/calls/react-native/custom-control-panel.mdx @@ -1,8 +1,8 @@ --- title: "Custom Control Panel" sidebarTitle: "Custom Control Panel" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Control Panel for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Control Panel for React Native" --- Build a custom control panel to replace or extend the default call controls. Hide the default layout and implement your own UI using the SDK's action methods. diff --git a/calls/react-native/custom-participant-list.mdx b/calls/react-native/custom-participant-list.mdx index 05f79521b..2133c202c 100644 --- a/calls/react-native/custom-participant-list.mdx +++ b/calls/react-native/custom-participant-list.mdx @@ -1,8 +1,8 @@ --- title: "Custom Participant List" sidebarTitle: "Custom Participant List" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Custom Participant List for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Custom Participant List for React Native" --- Build a custom participant list UI to display and manage call participants. Listen for participant events and use the SDK's management methods. diff --git a/calls/react-native/events.mdx b/calls/react-native/events.mdx index b92ecf30e..99ab6254c 100644 --- a/calls/react-native/events.mdx +++ b/calls/react-native/events.mdx @@ -1,8 +1,8 @@ --- title: "Events" sidebarTitle: "Events" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Events for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Events for React Native" --- The CometChat Calls SDK provides two ways to listen for call events: the `OngoingCallListener` class for legacy-style callbacks, and the `addEventListener` method for modern event subscriptions. diff --git a/calls/react-native/idle-timeout.mdx b/calls/react-native/idle-timeout.mdx index 6645ff983..8e48aaded 100644 --- a/calls/react-native/idle-timeout.mdx +++ b/calls/react-native/idle-timeout.mdx @@ -1,8 +1,8 @@ --- title: "Idle Timeout" sidebarTitle: "Idle Timeout" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Idle Timeout for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Idle Timeout for React Native" --- The idle timeout feature automatically ends a call session when a participant is alone for a specified period. This prevents abandoned calls from running indefinitely. diff --git a/calls/react-native/in-call-chat.mdx b/calls/react-native/in-call-chat.mdx index 7cb784d7a..d209b699a 100644 --- a/calls/react-native/in-call-chat.mdx +++ b/calls/react-native/in-call-chat.mdx @@ -1,8 +1,8 @@ --- title: "In-Call Chat" sidebarTitle: "In-Call Chat" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - In-Call Chat for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - In-Call Chat for React Native" --- Enable messaging during calls by integrating the CometChat Chat SDK. Users can send and receive text messages while on a call. diff --git a/calls/react-native/join-session.mdx b/calls/react-native/join-session.mdx index 2be9d29e5..eaf39652c 100644 --- a/calls/react-native/join-session.mdx +++ b/calls/react-native/join-session.mdx @@ -1,8 +1,8 @@ --- title: "Join Session" sidebarTitle: "Join Session" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Join Session for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Join Session for React Native" --- This guide covers generating call tokens and joining call sessions using the CometChat Calls SDK. diff --git a/calls/react-native/migration-guide-v5.mdx b/calls/react-native/migration-guide-v5.mdx index 0500ac2ad..28fb1e58a 100644 --- a/calls/react-native/migration-guide-v5.mdx +++ b/calls/react-native/migration-guide-v5.mdx @@ -1,8 +1,8 @@ --- title: "Migration Guide" sidebarTitle: "v4 to v5 Migration" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Migration Guide for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Migration Guide for React Native" --- This guide covers migrating from Calls SDK v4 to v5 for React Native. diff --git a/calls/react-native/overview.mdx b/calls/react-native/overview.mdx index 427d72b22..ebbc90d55 100644 --- a/calls/react-native/overview.mdx +++ b/calls/react-native/overview.mdx @@ -1,13 +1,10 @@ --- title: "Calls SDK" sidebarTitle: "Overview" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Calls SDK for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Calls SDK for React Native" --- - - This is a **beta release** of the Calls SDK v5. APIs and features may change before the stable release. For the current stable version, see the [Calls SDK v4 docs →](/calls/v4/react-native/overview). - The CometChat Calls SDK enables real-time voice and video calling capabilities in your React Native application. Built on top of WebRTC, it provides a complete calling solution with built-in UI components and extensive customization options. ## Prerequisites diff --git a/calls/react-native/participant-management.mdx b/calls/react-native/participant-management.mdx index 644106203..7164e26e1 100644 --- a/calls/react-native/participant-management.mdx +++ b/calls/react-native/participant-management.mdx @@ -1,8 +1,8 @@ --- title: "Participant Management" sidebarTitle: "Participant Management" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Participant Management for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Participant Management for React Native" --- Manage call participants by muting, pinning, and monitoring their status during a call. diff --git a/calls/react-native/picture-in-picture.mdx b/calls/react-native/picture-in-picture.mdx index 5d2aef02a..53d48409e 100644 --- a/calls/react-native/picture-in-picture.mdx +++ b/calls/react-native/picture-in-picture.mdx @@ -1,8 +1,8 @@ --- title: "Picture-in-Picture" sidebarTitle: "Picture-in-Picture" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Picture-in-Picture for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Picture-in-Picture for React Native" --- Picture-in-Picture (PiP) mode allows users to continue their call in a floating window while using other apps. This feature requires platform-specific configuration. diff --git a/calls/react-native/raise-hand.mdx b/calls/react-native/raise-hand.mdx index 59a050cbc..e5bffd57e 100644 --- a/calls/react-native/raise-hand.mdx +++ b/calls/react-native/raise-hand.mdx @@ -1,8 +1,8 @@ --- title: "Raise Hand" sidebarTitle: "Raise Hand" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Raise Hand for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Raise Hand for React Native" --- The raise hand feature allows participants to signal that they want attention during a call, useful for Q&A sessions or large meetings. diff --git a/calls/react-native/recording.mdx b/calls/react-native/recording.mdx index db5aa2ab3..656a39288 100644 --- a/calls/react-native/recording.mdx +++ b/calls/react-native/recording.mdx @@ -1,8 +1,8 @@ --- title: "Recording" sidebarTitle: "Recording" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Recording for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Recording for React Native" --- The CometChat Calls SDK supports recording call sessions. Recordings can be started manually or automatically when the call begins. diff --git a/calls/react-native/ringing.mdx b/calls/react-native/ringing.mdx index 9b80fac28..698551bbb 100644 --- a/calls/react-native/ringing.mdx +++ b/calls/react-native/ringing.mdx @@ -1,8 +1,8 @@ --- title: "Ringing" sidebarTitle: "Ringing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Ringing for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Ringing for React Native" --- Implement incoming and outgoing call notifications using the CometChat Chat SDK's calling features. The Calls SDK handles the actual call session, while the Chat SDK manages call signaling. diff --git a/calls/react-native/screen-sharing.mdx b/calls/react-native/screen-sharing.mdx index 31b739d8e..b8bc3cf2e 100644 --- a/calls/react-native/screen-sharing.mdx +++ b/calls/react-native/screen-sharing.mdx @@ -1,8 +1,8 @@ --- title: "Screen Sharing" sidebarTitle: "Screen Sharing" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Screen Sharing for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Screen Sharing for React Native" --- The CometChat Calls SDK supports viewing screen shares from other participants. Screen sharing initiation on React Native requires platform-specific configuration. diff --git a/calls/react-native/session-settings.mdx b/calls/react-native/session-settings.mdx index a277fd0b3..8665f2ec0 100644 --- a/calls/react-native/session-settings.mdx +++ b/calls/react-native/session-settings.mdx @@ -1,8 +1,8 @@ --- title: "Session Settings" sidebarTitle: "Session Settings" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Session Settings for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Session Settings for React Native" --- Configure call sessions using the `CallSettingsBuilder` class. This allows you to customize the call UI, behavior, and event handling. diff --git a/calls/react-native/setup.mdx b/calls/react-native/setup.mdx index c7d824cc6..020404133 100644 --- a/calls/react-native/setup.mdx +++ b/calls/react-native/setup.mdx @@ -1,8 +1,8 @@ --- title: "Setup" sidebarTitle: "Setup" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Setup for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Setup for React Native" --- @@ -25,13 +25,13 @@ This guide walks you through installing the CometChat Calls SDK and configuring ### Using npm ```bash -npm install @cometchat/calls-sdk-react-native@5.0.0-beta.3 +npm install @cometchat/calls-sdk-react-native@5.0.0 ``` ### Using Yarn ```bash -yarn add @cometchat/calls-sdk-react-native@5.0.0-beta.3 +yarn add @cometchat/calls-sdk-react-native@5.0.0 ``` ## iOS Configuration diff --git a/calls/react-native/share-invite.mdx b/calls/react-native/share-invite.mdx index 606a66cbe..db68a0043 100644 --- a/calls/react-native/share-invite.mdx +++ b/calls/react-native/share-invite.mdx @@ -1,8 +1,8 @@ --- title: "Share Invite" sidebarTitle: "Share Invite" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - Share Invite for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - Share Invite for React Native" --- Allow users to share call invite links with others. When the share invite button is clicked, you can generate and share a link that others can use to join the call. diff --git a/calls/react-native/troubleshooting.mdx b/calls/react-native/troubleshooting.mdx index 0f19358db..c3eb07bef 100644 --- a/calls/react-native/troubleshooting.mdx +++ b/calls/react-native/troubleshooting.mdx @@ -1,7 +1,7 @@ --- title: "Troubleshooting" -description: "CometChat Calling SDK v5 - Beta Release - Troubleshooting for React Native" -sdk_version: "5.x (Beta)" +description: "CometChat Calling SDK v5 - Troubleshooting for React Native" +sdk_version: "5.x" --- ## Installation & Setup diff --git a/calls/react-native/voip-calling.mdx b/calls/react-native/voip-calling.mdx index 82d264430..3782ffeaa 100644 --- a/calls/react-native/voip-calling.mdx +++ b/calls/react-native/voip-calling.mdx @@ -1,8 +1,8 @@ --- title: "VoIP Calling" sidebarTitle: "VoIP Calling" -sdk_version: "5.x (Beta)" -description: "CometChat Calling SDK v5 - Beta Release - VoIP Calling for React Native" +sdk_version: "5.x" +description: "CometChat Calling SDK v5 - VoIP Calling for React Native" --- Implement VoIP push notifications to receive incoming calls even when your app is in the background or terminated. This requires platform-specific configuration for iOS CallKit and Android ConnectionService. diff --git a/chat-builder/android/overview.mdx b/chat-builder/android/overview.mdx index 661c9dd5b..a0c14e0f9 100644 --- a/chat-builder/android/overview.mdx +++ b/chat-builder/android/overview.mdx @@ -1,7 +1,7 @@ --- title: "CometChat UI Kit Builder For Android" sidebarTitle: "Overview" -description: "CometChat UI Kit Builder for Android provides a pre-built user interface kit that developers can use to quickly integrate a reliable & fully-featured chat experience into an existing or a new app." +description: "CometChat UI Kit Builder for Android provides a pre-built interface to integrate a reliable, fully-featured chat experience into new or existing apps." --- The CometChat UI Kit Builder for Android provides a pre-built user interface kit that developers can use to quickly integrate a reliable & fully-featured chat experience into an existing or a new app. diff --git a/chat-builder/flutter/overview.mdx b/chat-builder/flutter/overview.mdx index 0cc1899c0..5a4d7a35a 100644 --- a/chat-builder/flutter/overview.mdx +++ b/chat-builder/flutter/overview.mdx @@ -1,7 +1,7 @@ --- title: "CometChat UI Kit Builder For Flutter" sidebarTitle: "Overview" -description: "CometChat UI Kit Builder for Flutter is a visual development tool that helps you design and configure chat experiences for Flutter applications without building the interface from scratch." +description: "CometChat UI Kit Builder for Flutter provides a pre-built interface to integrate a reliable, fully-featured chat experience into new or existing apps." --- It provides a set of prebuilt, production-ready messaging components backed by CometChat's real-time infrastructure. @@ -137,5 +137,5 @@ Experience the CometChat UI Kit Builder in action: ## Need Help? -- Developer Community: http://community.cometchat.com/ +- Developer Community: https://community.cometchat.com/ - Support Portal: https://help.cometchat.com/hc/en-us/requests/new diff --git a/chat-builder/ios/overview.mdx b/chat-builder/ios/overview.mdx index dd30755b5..1313ec220 100644 --- a/chat-builder/ios/overview.mdx +++ b/chat-builder/ios/overview.mdx @@ -1,7 +1,7 @@ --- title: "CometChat UI Kit Builder For iOS" sidebarTitle: "Overview" -description: "CometChat UI Kit Builder for iOS provides a pre-built user interface that developers can use to quickly integrate a reliable & fully-featured chat experience into an existing or new iOS app." +description: "CometChat UI Kit Builder for iOS provides a pre-built interface to integrate a reliable, fully-featured chat experience." --- The CometChat iOS UI Kit provides a pre-built user interface that developers can use to quickly integrate a reliable & fully-featured chat experience into an existing or new iOS app using **UI Kit Builder** configuration. @@ -98,4 +98,4 @@ Experience the CometChat UI Kit Builder in action: Get assistance from our support team with any questions or issues - \ No newline at end of file + diff --git a/chat-builder/nextjs/integration.mdx b/chat-builder/nextjs/integration.mdx index 5c5690fea..52647b38d 100644 --- a/chat-builder/nextjs/integration.mdx +++ b/chat-builder/nextjs/integration.mdx @@ -1,7 +1,7 @@ --- title: "UI Kit Builder Integration" sidebarTitle: "Integration" -description: "Step-by-step guide to integrating CometChat's UI Kit Builder into your Next.js application, including initialization, user login, SSR handling, and rendering the CometChatApp component." +description: "Step-by-step guide to integrating CometChat UI Kit Builder into your Next.js app with user login and SSR handling." --- The **UI Kit Builder** simplifies integrating CometChat's UI Kit into your Next.js application — quickly set up chat, customize UI elements, and add features without extensive coding. diff --git a/chat-builder/nextjs/overview.mdx b/chat-builder/nextjs/overview.mdx index e0bea881f..281600a4f 100644 --- a/chat-builder/nextjs/overview.mdx +++ b/chat-builder/nextjs/overview.mdx @@ -1,7 +1,7 @@ --- title: "CometChat UI Kit Builder For Next.js" sidebarTitle: "Overview" -description: "CometChat UI Kit Builder for Next.js is a visual development tool that helps you design and configure chat experiences for Next.js applications without building the interface from scratch." +description: "CometChat UI Kit Builder for Next.js is a low-code development tool to design and configure fully-featured chat experiences." --- It provides a set of prebuilt, production-ready messaging components backed by CometChat's real-time infrastructure. diff --git a/chat-builder/react-native/overview.mdx b/chat-builder/react-native/overview.mdx index 7c4ed01aa..68b527da8 100644 --- a/chat-builder/react-native/overview.mdx +++ b/chat-builder/react-native/overview.mdx @@ -137,6 +137,6 @@ Drop the configuration into your React Native project, add your CometChat creden ## Need Help? -- Developer Community: http://community.cometchat.com/ +- Developer Community: https://community.cometchat.com/ - Dashboard & Live Support: https://app.cometchat.com - UI Kit questions: https://www.cometchat.com/docs/ui-kit/react-native/5.0/getting-started diff --git a/chat-builder/react-router/integration.mdx b/chat-builder/react-router/integration.mdx index c79372269..6dbf805d8 100644 --- a/chat-builder/react-router/integration.mdx +++ b/chat-builder/react-router/integration.mdx @@ -1,7 +1,7 @@ --- title: "UI Kit Builder Integration" sidebarTitle: "Integration" -description: "Step-by-step guide to integrating CometChat's UI Kit Builder into your React Router application, including initialization, user login, SSR handling, and rendering the CometChatApp component." +description: "Add CometChat UI Kit Builder to React Router apps with configurable chat features, themes, layouts, login, and SSR support." --- The **UI Kit Builder** simplifies integrating CometChat's UI Kit into your React Router application — quickly set up chat, customize UI elements, and add features without extensive coding. diff --git a/chat-builder/react-router/overview.mdx b/chat-builder/react-router/overview.mdx index 33d9c62f1..46c5730a6 100644 --- a/chat-builder/react-router/overview.mdx +++ b/chat-builder/react-router/overview.mdx @@ -1,7 +1,7 @@ --- title: "CometChat UI Kit Builder For React Router" sidebarTitle: "Overview" -description: "CometChat UI Kit Builder for React Router is a visual development tool that helps you design and configure chat experiences for React Router applications without building the interface from scratch." +description: "CometChat UI Kit Builder for React Router is a low-code development tool to design and configure fully-featured chat experiences." --- It provides a set of prebuilt, production-ready messaging components backed by CometChat's real-time infrastructure. diff --git a/chat-builder/react/integration.mdx b/chat-builder/react/integration.mdx index 9d1732ad7..8788df838 100644 --- a/chat-builder/react/integration.mdx +++ b/chat-builder/react/integration.mdx @@ -1,7 +1,7 @@ --- title: "UI Kit Builder Integration" sidebarTitle: "Integration" -description: "Step-by-step guide to integrating CometChat's UI Kit Builder into your React application, including initialization, user login, and rendering the CometChatApp component." +description: "Step-by-step guide to integrating CometChat UI Kit Builder into your React app with user login." --- The **UI Kit Builder** simplifies integrating CometChat's UI Kit into your React application — quickly set up chat, customize UI elements, and add features without extensive coding. diff --git a/chat-builder/react/overview.mdx b/chat-builder/react/overview.mdx index 3dbaa7dd6..faf7d6b14 100644 --- a/chat-builder/react/overview.mdx +++ b/chat-builder/react/overview.mdx @@ -1,7 +1,7 @@ --- title: "CometChat UI Kit Builder For React" sidebarTitle: "Overview" -description: "CometChat UI Kit Builder for React is a visual development tool that helps you design and configure chat experiences for React applications without building the interface from scratch." +description: "CometChat UI Kit Builder for React is a low-code development tool to design and configure fully-featured chat experiences." --- It provides a set of prebuilt, production-ready messaging components backed by CometChat's real-time infrastructure. diff --git a/docs.json b/docs.json index a014a3746..ee570524d 100644 --- a/docs.json +++ b/docs.json @@ -18,9 +18,9 @@ }, "contextual": { "options": [ - "chatgpt", "claude", "cursor", + "chatgpt", "vscode", "perplexity", "mcp", @@ -450,6 +450,7 @@ "versions": [ { "version": "v6", + "default": true, "groups": [ { "group": " ", @@ -536,7 +537,7 @@ "ui-kit/react/message-template", "ui-kit/react/thread-header", "ui-kit/react/incoming-call", - "ui-kit/react/outgoing-call", + "ui-kit/react/outgoing-call", "ui-kit/react/call-buttons", "ui-kit/react/call-logs", "ui-kit/react/search", @@ -916,7 +917,7 @@ "icon": "/images/icons/react.svg", "versions": [ { - "version": "v5\u200e", + "version": "v5‎", "groups": [ { "group": " ", @@ -1027,7 +1028,7 @@ ] }, { - "version": "v4\u200e", + "version": "v4‎", "groups": [ { "group": " ", @@ -1190,7 +1191,7 @@ ] }, { - "version": "v3\u200e", + "version": "v3‎", "groups": [ { "group": " ", @@ -1212,7 +1213,7 @@ ] }, { - "version": "v2\u200e", + "version": "v2‎", "groups": [ { "group": " ", @@ -1240,7 +1241,7 @@ "icon": "/images/icons/swift.svg", "versions": [ { - "version": "v5\u200e\u200e", + "version": "v5‎‎", "groups": [ { "group": " ", @@ -1267,7 +1268,8 @@ "ui-kit/ios/ai-features" ] }, - "ui-kit/ios/call-features" + "ui-kit/ios/call-features", + "ui-kit/ios/campaigns" ] }, { @@ -1300,7 +1302,8 @@ "ui-kit/ios/call-buttons", "ui-kit/ios/call-logs", "ui-kit/ios/ai-assistant-chat-history", - "ui-kit/ios/search" + "ui-kit/ios/search", + "ui-kit/ios/notification-feed" ] }, { @@ -1347,7 +1350,7 @@ ] }, { - "version": "v4\u200e\u200e", + "version": "v4‎‎", "groups": [ { "group": " ", @@ -1511,7 +1514,7 @@ ] }, { - "version": "v3\u200e\u200e", + "version": "v3‎‎", "groups": [ { "group": " ", @@ -1533,7 +1536,7 @@ ] }, { - "version": "v2\u200e\u200e", + "version": "v2‎‎", "groups": [ { "group": " ", @@ -1561,7 +1564,124 @@ "icon": "/images/icons/android.svg", "versions": [ { - "version": "v5\u200e\u200e\u200e", + "version": "v6‎‎‎", + "groups": [ + { + "group": " ", + "pages": [ + "ui-kit/android/v6/overview", + { + "group": "Getting Started", + "pages": [ + "ui-kit/android/v6/getting-started", + "ui-kit/android/v6/getting-started-kotlin", + "ui-kit/android/v6/getting-started-jetpack", + "ui-kit/android/v6/one-to-one-chat", + "ui-kit/android/v6/tab-based-chat", + "ui-kit/android/v6/calling-integration" + ] + }, + { + "group": "Features", + "pages": [ + { + "group": "Chat", + "pages": [ + "ui-kit/android/v6/core-features", + "ui-kit/android/v6/extensions", + "ui-kit/android/v6/ai-features" + ] + }, + "ui-kit/android/v6/call-features" + ] + }, + { + "group": "Theming", + "pages": [ + "ui-kit/android/v6/theme-introduction", + "ui-kit/android/v6/color-resources", + "ui-kit/android/v6/component-styling", + "ui-kit/android/v6/message-bubble-styling", + "ui-kit/android/v6/localize", + "ui-kit/android/v6/sound-manager" + ] + }, + { + "group": "Customization", + "pages": [ + "ui-kit/android/v6/customization-overview", + "ui-kit/android/v6/customization-view-slots", + "ui-kit/android/v6/customization-styles", + "ui-kit/android/v6/customization-viewmodel-data", + "ui-kit/android/v6/customization-events", + "ui-kit/android/v6/customization-state-views", + "ui-kit/android/v6/customization-text-formatters", + "ui-kit/android/v6/customization-menu-options" + ] + }, + { + "group": "Components", + "pages": [ + "ui-kit/android/v6/components-overview", + "ui-kit/android/v6/conversations", + "ui-kit/android/v6/conversation-message-view", + "ui-kit/android/v6/users", + "ui-kit/android/v6/groups", + "ui-kit/android/v6/group-members", + "ui-kit/android/v6/message-header", + "ui-kit/android/v6/message-list", + "ui-kit/android/v6/message-composer", + "ui-kit/android/v6/message-template", + "ui-kit/android/v6/threaded-messages-header", + "ui-kit/android/v6/incoming-call", + "ui-kit/android/v6/outgoing-call", + "ui-kit/android/v6/call-buttons", + "ui-kit/android/v6/call-logs", + "ui-kit/android/v6/search", + "ui-kit/android/v6/ai-assistant-chat-history" + ] + }, + { + "group": "Reference", + "pages": [ + "ui-kit/android/v6/methods", + "ui-kit/android/v6/events" + ] + }, + { + "group": "Guides", + "pages": [ + "ui-kit/android/v6/guide-overview", + "ui-kit/android/v6/guide-threaded-messages", + "ui-kit/android/v6/guide-block-unblock-user", + "ui-kit/android/v6/guide-new-chat", + "ui-kit/android/v6/guide-message-privately", + "ui-kit/android/v6/guide-call-log-details", + "ui-kit/android/v6/guide-group-chat", + "ui-kit/android/v6/custom-text-formatter-guide", + "ui-kit/android/v6/mentions-formatter-guide", + "ui-kit/android/v6/shortcut-formatter-guide", + "ui-kit/android/v6/guide-search-messages", + "ui-kit/android/v6/guide-ai-agent" + ] + }, + "ui-kit/android/v6/architecture-data-flow", + { + "group": "Migration Guide", + "pages": [ + "ui-kit/android/v6/upgrading-from-v5" + ] + }, + "ui-kit/android/v6/troubleshooting", + "ui-kit/android/v6/link/sample", + "ui-kit/android/v6/link/figma", + "ui-kit/android/v6/link/changelog" + ] + } + ] + }, + { + "version": "v5‎‎‎", "groups": [ { "group": " ", @@ -1678,120 +1798,7 @@ ] }, { - "version": "v6\u200e\u200e\u200e", - "groups": [ - { - "group": " ", - "pages": [ - "ui-kit/android/v6/overview", - { - "group": "Getting Started", - "pages": [ - "ui-kit/android/v6/getting-started", - "ui-kit/android/v6/getting-started-kotlin", - "ui-kit/android/v6/getting-started-jetpack", - "ui-kit/android/v6/one-to-one-chat", - "ui-kit/android/v6/tab-based-chat", - "ui-kit/android/v6/calling-integration" - ] - }, - { - "group": "Features", - "pages": [ - { - "group": "Chat", - "pages": [ - "ui-kit/android/v6/core-features", - "ui-kit/android/v6/extensions", - "ui-kit/android/v6/ai-features" - ] - }, - "ui-kit/android/v6/call-features" - ] - }, - { - "group": "Theming", - "pages": [ - "ui-kit/android/v6/theme-introduction", - "ui-kit/android/v6/color-resources", - "ui-kit/android/v6/component-styling", - "ui-kit/android/v6/message-bubble-styling", - "ui-kit/android/v6/localize", - "ui-kit/android/v6/sound-manager" - ] - }, - { - "group": "Customization", - "pages": [ - "ui-kit/android/v6/customization-overview", - "ui-kit/android/v6/customization-view-slots", - "ui-kit/android/v6/customization-styles", - "ui-kit/android/v6/customization-viewmodel-data", - "ui-kit/android/v6/customization-events", - "ui-kit/android/v6/customization-state-views", - "ui-kit/android/v6/customization-text-formatters", - "ui-kit/android/v6/customization-menu-options" - ] - }, - { - "group": "Components", - "pages": [ - "ui-kit/android/v6/components-overview", - "ui-kit/android/v6/conversations", - "ui-kit/android/v6/conversation-message-view", - "ui-kit/android/v6/users", - "ui-kit/android/v6/groups", - "ui-kit/android/v6/group-members", - "ui-kit/android/v6/message-header", - "ui-kit/android/v6/message-list", - "ui-kit/android/v6/message-composer", - "ui-kit/android/v6/message-template", - "ui-kit/android/v6/threaded-messages-header", - "ui-kit/android/v6/incoming-call", - "ui-kit/android/v6/outgoing-call", - "ui-kit/android/v6/call-buttons", - "ui-kit/android/v6/call-logs" - ] - }, - { - "group": "Reference", - "pages": [ - "ui-kit/android/v6/methods", - "ui-kit/android/v6/events" - ] - }, - { - "group": "Guides", - "pages": [ - "ui-kit/android/v6/guide-overview", - "ui-kit/android/v6/guide-threaded-messages", - "ui-kit/android/v6/guide-block-unblock-user", - "ui-kit/android/v6/guide-new-chat", - "ui-kit/android/v6/guide-message-privately", - "ui-kit/android/v6/guide-call-log-details", - "ui-kit/android/v6/guide-group-chat", - "ui-kit/android/v6/custom-text-formatter-guide", - "ui-kit/android/v6/mentions-formatter-guide", - "ui-kit/android/v6/shortcut-formatter-guide" - ] - }, - "ui-kit/android/v6/architecture-data-flow", - { - "group": "Migration Guide", - "pages": [ - "ui-kit/android/v6/upgrading-from-v5" - ] - }, - "ui-kit/android/v6/troubleshooting", - "ui-kit/android/v6/link/sample", - "ui-kit/android/v6/link/figma", - "ui-kit/android/v6/link/changelog" - ] - } - ] - }, - { - "version": "v4\u200e\u200e\u200e", + "version": "v4‎‎‎", "groups": [ { "group": " ", @@ -1948,7 +1955,7 @@ ] }, { - "version": "v3\u200e\u200e\u200e", + "version": "v3‎‎‎", "groups": [ { "group": " ", @@ -1973,7 +1980,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e", + "version": "v2‎‎‎", "groups": [ { "group": " ", @@ -2002,7 +2009,7 @@ "icon": "/images/icons/flutter.svg", "versions": [ { - "version": "v5\u200e\u200e\u200e\u200e", + "version": "v6‎‎‎‎", "groups": [ { "group": " ", @@ -2014,8 +2021,7 @@ "ui-kit/flutter/getting-started", "ui-kit/flutter/flutter-conversation", "ui-kit/flutter/flutter-one-to-one-chat", - "ui-kit/flutter/flutter-tab-based-chat", - "ui-kit/flutter/calling-integration" + "ui-kit/flutter/flutter-tab-based-chat" ] }, { @@ -2025,8 +2031,7 @@ "group": "Chat", "pages": [ "ui-kit/flutter/core-features", - "ui-kit/flutter/extensions", - "ui-kit/flutter/ai-features" + "ui-kit/flutter/extensions" ] }, "ui-kit/flutter/call-features" @@ -2054,15 +2059,12 @@ "ui-kit/flutter/message-header", "ui-kit/flutter/message-list", "ui-kit/flutter/message-composer", - "ui-kit/flutter/compact-message-composer", - "ui-kit/flutter/message-template", "ui-kit/flutter/threaded-messages-header", "ui-kit/flutter/incoming-call", "ui-kit/flutter/outgoing-call", "ui-kit/flutter/call-buttons", "ui-kit/flutter/call-logs", - "ui-kit/flutter/search", - "ui-kit/flutter/ai-assistant-chat-history" + "ui-kit/flutter/search" ] }, { @@ -2072,6 +2074,28 @@ "ui-kit/flutter/events" ] }, + { + "group": "Customization", + "pages": [ + "ui-kit/flutter/customization-overview", + "ui-kit/flutter/customization-view-slots", + "ui-kit/flutter/customization-bloc-data", + "ui-kit/flutter/customization-state-views", + "ui-kit/flutter/customization-text-formatters", + "ui-kit/flutter/customization-menu-options", + "ui-kit/flutter/customization-datasource" + ] + }, + { + "group": "Advanced", + "pages": [ + "ui-kit/flutter/message-template", + "ui-kit/flutter/mentions-formatter-guide", + "ui-kit/flutter/shortcut-formatter-guide", + "ui-kit/flutter/custom-text-formatter-guide", + "ui-kit/flutter/troubleshooting" + ] + }, { "group": "Guides", "pages": [ @@ -2080,45 +2104,39 @@ "ui-kit/flutter/guide-block-unblock-user", "ui-kit/flutter/guide-new-chat", "ui-kit/flutter/guide-message-privately", - "ui-kit/flutter/guide-search-messages", "ui-kit/flutter/guide-call-log-details", "ui-kit/flutter/guide-group-chat", "ui-kit/flutter/guide-message-agentic-flow", - "ui-kit/flutter/guide-image-caption", - "ui-kit/flutter/custom-text-formatter-guide", - "ui-kit/flutter/mentions-formatter-guide", - "ui-kit/flutter/custom-mentions-formatter-guide", - "ui-kit/flutter/url-formatter-guide", - "ui-kit/flutter/shortcut-formatter-guide" + "ui-kit/flutter/multi-tab-chat-ui-guide" ] }, { "group": "Migration Guide", "pages": [ - "ui-kit/flutter/upgrading-from-v4" + "ui-kit/flutter/upgrading-from-v5" ] }, "ui-kit/flutter/link/sample", - "ui-kit/flutter/link/changelog", - "ui-kit/flutter/troubleshooting" + "ui-kit/flutter/link/changelog" ] } ] }, { - "version": "v6\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "ui-kit/flutter/v6/overview", + "ui-kit/flutter/v5/overview", { "group": "Getting Started", "pages": [ - "ui-kit/flutter/v6/getting-started", - "ui-kit/flutter/v6/flutter-conversation", - "ui-kit/flutter/v6/flutter-one-to-one-chat", - "ui-kit/flutter/v6/flutter-tab-based-chat" + "ui-kit/flutter/v5/getting-started", + "ui-kit/flutter/v5/flutter-conversation", + "ui-kit/flutter/v5/flutter-one-to-one-chat", + "ui-kit/flutter/v5/flutter-tab-based-chat", + "ui-kit/flutter/v5/calling-integration" ] }, { @@ -2127,100 +2145,89 @@ { "group": "Chat", "pages": [ - "ui-kit/flutter/v6/core-features", - "ui-kit/flutter/v6/extensions" + "ui-kit/flutter/v5/core-features", + "ui-kit/flutter/v5/extensions", + "ui-kit/flutter/v5/ai-features" ] }, - "ui-kit/flutter/v6/call-features" + "ui-kit/flutter/v5/call-features" ] }, { "group": "Theming", "pages": [ - "ui-kit/flutter/v6/theme-introduction", - "ui-kit/flutter/v6/color-resources", - "ui-kit/flutter/v6/component-styling", - "ui-kit/flutter/v6/message-bubble-styling", - "ui-kit/flutter/v6/localize", - "ui-kit/flutter/v6/sound-manager" + "ui-kit/flutter/v5/theme-introduction", + "ui-kit/flutter/v5/color-resources", + "ui-kit/flutter/v5/component-styling", + "ui-kit/flutter/v5/message-bubble-styling", + "ui-kit/flutter/v5/localize", + "ui-kit/flutter/v5/sound-manager" ] }, { "group": "Components", "pages": [ - "ui-kit/flutter/v6/components-overview", - "ui-kit/flutter/v6/conversations", - "ui-kit/flutter/v6/users", - "ui-kit/flutter/v6/groups", - "ui-kit/flutter/v6/group-members", - "ui-kit/flutter/v6/message-header", - "ui-kit/flutter/v6/message-list", - "ui-kit/flutter/v6/message-composer", - "ui-kit/flutter/v6/threaded-messages-header", - "ui-kit/flutter/v6/incoming-call", - "ui-kit/flutter/v6/outgoing-call", - "ui-kit/flutter/v6/call-buttons", - "ui-kit/flutter/v6/call-logs", - "ui-kit/flutter/v6/search" + "ui-kit/flutter/v5/components-overview", + "ui-kit/flutter/v5/conversations", + "ui-kit/flutter/v5/users", + "ui-kit/flutter/v5/groups", + "ui-kit/flutter/v5/group-members", + "ui-kit/flutter/v5/message-header", + "ui-kit/flutter/v5/message-list", + "ui-kit/flutter/v5/message-composer", + "ui-kit/flutter/v5/compact-message-composer", + "ui-kit/flutter/v5/message-template", + "ui-kit/flutter/v5/threaded-messages-header", + "ui-kit/flutter/v5/incoming-call", + "ui-kit/flutter/v5/outgoing-call", + "ui-kit/flutter/v5/call-buttons", + "ui-kit/flutter/v5/call-logs", + "ui-kit/flutter/v5/search", + "ui-kit/flutter/v5/ai-assistant-chat-history" ] }, { "group": "Reference", "pages": [ - "ui-kit/flutter/v6/methods", - "ui-kit/flutter/v6/events" - ] - }, - { - "group": "Customization", - "pages": [ - "ui-kit/flutter/v6/customization-overview", - "ui-kit/flutter/v6/customization-view-slots", - "ui-kit/flutter/v6/customization-bloc-data", - "ui-kit/flutter/v6/customization-state-views", - "ui-kit/flutter/v6/customization-text-formatters", - "ui-kit/flutter/v6/customization-menu-options", - "ui-kit/flutter/v6/customization-datasource" - ] - }, - { - "group": "Advanced", - "pages": [ - "ui-kit/flutter/v6/message-template", - "ui-kit/flutter/v6/mentions-formatter-guide", - "ui-kit/flutter/v6/shortcut-formatter-guide", - "ui-kit/flutter/v6/custom-text-formatter-guide", - "ui-kit/flutter/v6/troubleshooting" + "ui-kit/flutter/v5/methods", + "ui-kit/flutter/v5/events" ] }, { "group": "Guides", "pages": [ - "ui-kit/flutter/v6/guide-overview", - "ui-kit/flutter/v6/guide-threaded-messages", - "ui-kit/flutter/v6/guide-block-unblock-user", - "ui-kit/flutter/v6/guide-new-chat", - "ui-kit/flutter/v6/guide-message-privately", - "ui-kit/flutter/v6/guide-call-log-details", - "ui-kit/flutter/v6/guide-group-chat", - "ui-kit/flutter/v6/guide-message-agentic-flow", - "ui-kit/flutter/v6/multi-tab-chat-ui-guide" + "ui-kit/flutter/v5/guide-overview", + "ui-kit/flutter/v5/guide-threaded-messages", + "ui-kit/flutter/v5/guide-block-unblock-user", + "ui-kit/flutter/v5/guide-new-chat", + "ui-kit/flutter/v5/guide-message-privately", + "ui-kit/flutter/v5/guide-search-messages", + "ui-kit/flutter/v5/guide-call-log-details", + "ui-kit/flutter/v5/guide-group-chat", + "ui-kit/flutter/v5/guide-message-agentic-flow", + "ui-kit/flutter/v5/guide-image-caption", + "ui-kit/flutter/v5/custom-text-formatter-guide", + "ui-kit/flutter/v5/mentions-formatter-guide", + "ui-kit/flutter/v5/custom-mentions-formatter-guide", + "ui-kit/flutter/v5/url-formatter-guide", + "ui-kit/flutter/v5/shortcut-formatter-guide" ] }, { "group": "Migration Guide", "pages": [ - "ui-kit/flutter/v6/upgrading-from-v5" + "ui-kit/flutter/v5/upgrading-from-v4" ] }, "ui-kit/flutter/link/sample", - "ui-kit/flutter/link/changelog" + "ui-kit/flutter/link/changelog", + "ui-kit/flutter/v5/troubleshooting" ] } ] }, { - "version": "v4\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎", "groups": [ { "group": " ", @@ -2396,14 +2403,24 @@ "icon": "/images/icons/angular.svg", "versions": [ { - "version": "v4", - "default": true, + "version": "v5‎‎‎‎‎", + + "groups": [ { "group": " ", "pages": [ "ui-kit/angular/overview", - "ui-kit/angular/getting-started", + { + "group": "Getting Started", + "pages": [ + "ui-kit/angular/quickstart", + "ui-kit/angular/integration", + "ui-kit/angular/angular-conversation", + "ui-kit/angular/angular-one-to-one-chat", + "ui-kit/angular/angular-tab-based-chat" + ] + }, { "group": "Features", "pages": [ @@ -2411,151 +2428,140 @@ "group": "Chat", "pages": [ "ui-kit/angular/core-features", - "ui-kit/angular/extensions" + "ui-kit/angular/extensions", + "ui-kit/angular/ai-features" ] }, - "ui-kit/angular/call-features", - "ui-kit/angular/ai-features" + "ui-kit/angular/call-features" ] }, { "group": "Theming", "pages": [ - "ui-kit/angular/theme", - "ui-kit/angular/localize", + "ui-kit/angular/customization/theming", + "ui-kit/angular/customization/localization", + "ui-kit/angular/customization/global-config", + "ui-kit/angular/customization/date-time-formatting", "ui-kit/angular/sound-manager" ] }, { "group": "Components", "pages": [ - "ui-kit/angular/components-overview", + "ui-kit/angular/components/components-overview", { "group": "Conversations", "pages": [ - "ui-kit/angular/conversations", - "ui-kit/angular/conversations-with-messages", - "ui-kit/angular/contacts" + "ui-kit/angular/components/cometchat-conversations", + "ui-kit/angular/components/cometchat-conversation-item" ] }, { "group": "Users", "pages": [ - "ui-kit/angular/users", - "ui-kit/angular/users-with-messages", - "ui-kit/angular/user-details" + "ui-kit/angular/components/cometchat-users", + "ui-kit/angular/components/cometchat-user-item" ] }, { "group": "Groups", "pages": [ - "ui-kit/angular/groups", - "ui-kit/angular/groups-with-messages", - "ui-kit/angular/create-group", - "ui-kit/angular/join-protected-group", - "ui-kit/angular/group-members", - "ui-kit/angular/group-add-members", - "ui-kit/angular/group-banned-members", - "ui-kit/angular/group-transfer-ownership", - "ui-kit/angular/group-details" + "ui-kit/angular/components/cometchat-groups", + "ui-kit/angular/components/cometchat-group-item" ] }, { - "group": "Messages", + "group": "Group Members", "pages": [ - "ui-kit/angular/messages", - "ui-kit/angular/message-header", - "ui-kit/angular/message-list", - "ui-kit/angular/message-template", - "ui-kit/angular/message-composer", - "ui-kit/angular/message-information", - "ui-kit/angular/threaded-messages" + "ui-kit/angular/components/cometchat-group-members", + "ui-kit/angular/components/cometchat-group-member-item" ] }, { - "group": "Interactive Messages", + "group": "Message Header", "pages": [ - "ui-kit/angular/interactive-form-message", - "ui-kit/angular/interactive-form-bubble", - "ui-kit/angular/interactive-card-message", - "ui-kit/angular/interactive-card-bubble", - "ui-kit/angular/interactive-element-type", - "ui-kit/angular/interactive-action-entity", - "ui-kit/angular/interactive-custom-interactive-message", - "ui-kit/angular/interactive-button-element", - "ui-kit/angular/interactive-text-input-element", - "ui-kit/angular/interactive-label-element", - "ui-kit/angular/interactive-single-select-element", - "ui-kit/angular/interactive-radio-button-element", - "ui-kit/angular/interactive-checkbox-element", - "ui-kit/angular/interactive-dropdown-element", - "ui-kit/angular/interactive-scheduler-message", - "ui-kit/angular/interactive-scheduler-bubble", - "ui-kit/angular/interactive-date-time-picker-element" + "ui-kit/angular/components/cometchat-message-header" ] }, { - "group": "Calls", + "group": "Search", "pages": [ - "ui-kit/angular/call-overview", - "ui-kit/angular/incoming-call", - "ui-kit/angular/ongoing-call", - "ui-kit/angular/outgoing-call", - "ui-kit/angular/call-buttons", - "ui-kit/angular/call-logs", - "ui-kit/angular/call-log-details", - "ui-kit/angular/call-log-history", - "ui-kit/angular/call-log-recording", - "ui-kit/angular/call-log-participants", - "ui-kit/angular/call-log-with-details" + "ui-kit/angular/components/cometchat-search" ] }, { - "group": "Extras", + "group": "Message List", "pages": [ - "ui-kit/angular/reaction", - "ui-kit/angular/reaction-list", - "ui-kit/angular/reaction-info", - "ui-kit/angular/user-member-wrapper" + "ui-kit/angular/components/cometchat-message-list" ] }, { - "group": "Base Components", + "group": "Message Composer", + "pages": [ + "ui-kit/angular/components/cometchat-message-composer" + ] + }, + { + "group": "Message Bubble", "pages": [ - "ui-kit/angular/avatar", - "ui-kit/angular/status-indicator", - "ui-kit/angular/badge", - "ui-kit/angular/receipt", - "ui-kit/angular/date", - "ui-kit/angular/text-bubble", - "ui-kit/angular/image-bubble", - "ui-kit/angular/file-bubble", - "ui-kit/angular/audio-bubble", - "ui-kit/angular/video-bubble", - "ui-kit/angular/message-bubble", - "ui-kit/angular/document-bubble", - "ui-kit/angular/message-input", - "ui-kit/angular/action-sheet", - "ui-kit/angular/media-recorder", - "ui-kit/angular/list-item", - "ui-kit/angular/confirm-dialog", - "ui-kit/angular/backdrop", - "ui-kit/angular/emoji-keyboard", - "ui-kit/angular/modal", - "ui-kit/angular/pop-over", - "ui-kit/angular/icon", - "ui-kit/angular/loader", - "ui-kit/angular/icon-button", - "ui-kit/angular/button-group", - "ui-kit/angular/label", - "ui-kit/angular/input", - "ui-kit/angular/search-input", - "ui-kit/angular/checkbox", - "ui-kit/angular/radio-button", - "ui-kit/angular/dropdown", - "ui-kit/angular/cometchat-quick-view", - "ui-kit/angular/singleselect", - "ui-kit/angular/list" + "ui-kit/angular/components/cometchat-message-bubble" + ] + }, + { + "group": "Message Information", + "pages": [ + "ui-kit/angular/components/cometchat-message-information" + ] + }, + { + "group": "Thread Header", + "pages": [ + "ui-kit/angular/components/cometchat-thread-header" + ] + }, + { + "group": "Message Bubbles", + "pages": [ + "ui-kit/angular/components/cometchat-text-bubble", + "ui-kit/angular/components/cometchat-image-bubble", + "ui-kit/angular/components/cometchat-video-bubble", + "ui-kit/angular/components/cometchat-audio-bubble", + "ui-kit/angular/components/cometchat-file-bubble", + "ui-kit/angular/components/cometchat-action-bubble", + "ui-kit/angular/components/cometchat-delete-bubble", + "ui-kit/angular/components/cometchat-call-bubble", + "ui-kit/angular/components/cometchat-poll-bubble", + "ui-kit/angular/components/cometchat-collaborative-document-bubble", + "ui-kit/angular/components/cometchat-collaborative-whiteboard-bubble", + "ui-kit/angular/components/cometchat-sticker-bubble", + "ui-kit/angular/components/cometchat-stickers-keyboard" + ] + }, + { + "group": "Reactions", + "pages": [ + "ui-kit/angular/components/cometchat-reactions", + "ui-kit/angular/components/cometchat-reaction-list", + "ui-kit/angular/components/cometchat-reaction-info" + ] + }, + { + "group": "Calls", + "pages": [ + "ui-kit/angular/components/cometchat-call-buttons", + "ui-kit/angular/components/cometchat-incoming-call", + "ui-kit/angular/components/cometchat-outgoing-call", + "ui-kit/angular/components/cometchat-call-logs" + ] + }, + { + "group": "AI", + "pages": [ + "ui-kit/angular/components/cometchat-smart-replies", + "ui-kit/angular/components/cometchat-conversation-starter", + "ui-kit/angular/components/cometchat-conversation-summary", + "ui-kit/angular/components/cometchat-ai-assistant-chat", + "ui-kit/angular/components/cometchat-markdown-renderer" ] } ] @@ -2563,178 +2569,212 @@ { "group": "Reference", "pages": [ + "ui-kit/angular/events", "ui-kit/angular/methods", - "ui-kit/angular/events" + "ui-kit/angular/accessibility", + "ui-kit/angular/troubleshooting" ] }, { "group": "Guides", "pages": [ - "ui-kit/angular/multi-tab-chat-ui-guide", - "ui-kit/angular/new-attachment-option-guide", - "ui-kit/angular/custom-text-formatter-guide", - "ui-kit/angular/mentions-formatter-guide", - "ui-kit/angular/url-formatter-guide", - "ui-kit/angular/shortcut-formatter-guide", - "ui-kit/angular/new-message-option-guide", - "ui-kit/angular/custom-message-guide" + "ui-kit/angular/guides/guides-overview", + "ui-kit/angular/guides/state-management", + "ui-kit/angular/guides/threaded-messages", + "ui-kit/angular/guides/group-chat", + "ui-kit/angular/guides/new-chat", + "ui-kit/angular/guides/block-unblock-user", + "ui-kit/angular/guides/message-privately", + "ui-kit/angular/guides/call-log-details", + "ui-kit/angular/guides/search-messages", + "ui-kit/angular/guides/rich-text-formatting", + "ui-kit/angular/guides/custom-message-types", + "ui-kit/angular/guides/custom-text-formatter", + "ui-kit/angular/guides/mentions-formatter", + "ui-kit/angular/guides/shortcut-formatter", + "ui-kit/angular/guides/hashtag-formatter", + "ui-kit/angular/guides/url-formatter", + "ui-kit/angular/guides/subscription-patterns" + ] + }, + { + "group": "Services", + "pages": [ + "ui-kit/angular/api-reference/introduction", + "ui-kit/angular/api-reference/chat-state-service", + "ui-kit/angular/api-reference/message-bubble-config-service", + "ui-kit/angular/api-reference/templates-service", + "ui-kit/angular/api-reference/search-conversations-service", + "ui-kit/angular/api-reference/search-messages-service", + "ui-kit/angular/api-reference/formatter-config-service", + "ui-kit/angular/api-reference/rich-text-editor-service" ] }, - "ui-kit/angular/link/sample", - "ui-kit/angular/link/changelog" + "ui-kit/angular/customization/migration-guide" ] } ] }, { - "version": "v5", + "version": "v4‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "ui-kit/angular/v5/overview", - { - "group": "Getting Started", - "pages": [ - "ui-kit/angular/v5/quickstart", - "ui-kit/angular/v5/integration", - "ui-kit/angular/v5/angular-conversation", - "ui-kit/angular/v5/angular-one-to-one-chat", - "ui-kit/angular/v5/angular-tab-based-chat" - ] - }, + "ui-kit/angular/v4/overview", + "ui-kit/angular/v4/getting-started", { "group": "Features", "pages": [ { "group": "Chat", "pages": [ - "ui-kit/angular/v5/core-features", - "ui-kit/angular/v5/extensions", - "ui-kit/angular/v5/ai-features" + "ui-kit/angular/v4/core-features", + "ui-kit/angular/v4/extensions" ] }, - "ui-kit/angular/v5/call-features" + "ui-kit/angular/v4/call-features", + "ui-kit/angular/v4/ai-features" ] }, { "group": "Theming", "pages": [ - "ui-kit/angular/v5/customization/theming", - "ui-kit/angular/v5/customization/localization", - "ui-kit/angular/v5/customization/global-config", - "ui-kit/angular/v5/sound-manager" + "ui-kit/angular/v4/theme", + "ui-kit/angular/v4/localize", + "ui-kit/angular/v4/sound-manager" ] }, { "group": "Components", "pages": [ - "ui-kit/angular/v5/components/overview", + "ui-kit/angular/v4/components-overview", { "group": "Conversations", "pages": [ - "ui-kit/angular/v5/components/cometchat-conversations", - "ui-kit/angular/v5/components/cometchat-conversation-item" + "ui-kit/angular/v4/conversations", + "ui-kit/angular/v4/conversations-with-messages", + "ui-kit/angular/v4/contacts" ] }, { "group": "Users", "pages": [ - "ui-kit/angular/v5/components/cometchat-users", - "ui-kit/angular/v5/components/cometchat-user-item" + "ui-kit/angular/v4/users", + "ui-kit/angular/v4/users-with-messages", + "ui-kit/angular/v4/user-details" ] }, { "group": "Groups", "pages": [ - "ui-kit/angular/v5/components/cometchat-groups", - "ui-kit/angular/v5/components/cometchat-group-item" - ] - }, - { - "group": "Group Members", - "pages": [ - "ui-kit/angular/v5/components/cometchat-group-members", - "ui-kit/angular/v5/components/cometchat-group-member-item" - ] - }, - { - "group": "Message Header", - "pages": [ - "ui-kit/angular/v5/components/cometchat-message-header" + "ui-kit/angular/v4/groups", + "ui-kit/angular/v4/groups-with-messages", + "ui-kit/angular/v4/create-group", + "ui-kit/angular/v4/join-protected-group", + "ui-kit/angular/v4/group-members", + "ui-kit/angular/v4/group-add-members", + "ui-kit/angular/v4/group-banned-members", + "ui-kit/angular/v4/group-transfer-ownership", + "ui-kit/angular/v4/group-details" ] }, { - "group": "Message List", - "pages": [ - "ui-kit/angular/v5/components/cometchat-message-list" - ] - }, - { - "group": "Message Composer", - "pages": [ - "ui-kit/angular/v5/components/cometchat-message-composer" - ] - }, - { - "group": "Message Bubble", - "pages": [ - "ui-kit/angular/v5/components/cometchat-message-bubble" - ] - }, - { - "group": "Message Information", - "pages": [ - "ui-kit/angular/v5/components/cometchat-message-information" - ] - }, - { - "group": "Thread Header", + "group": "Messages", "pages": [ - "ui-kit/angular/v5/components/cometchat-thread-header" + "ui-kit/angular/v4/messages", + "ui-kit/angular/v4/message-header", + "ui-kit/angular/v4/message-list", + "ui-kit/angular/v4/message-template", + "ui-kit/angular/v4/message-composer", + "ui-kit/angular/v4/message-information", + "ui-kit/angular/v4/threaded-messages" ] }, { - "group": "Message Bubbles", + "group": "Interactive Messages", "pages": [ - "ui-kit/angular/v5/components/cometchat-text-bubble", - "ui-kit/angular/v5/components/cometchat-image-bubble", - "ui-kit/angular/v5/components/cometchat-video-bubble", - "ui-kit/angular/v5/components/cometchat-audio-bubble", - "ui-kit/angular/v5/components/cometchat-file-bubble", - "ui-kit/angular/v5/components/cometchat-action-bubble", - "ui-kit/angular/v5/components/cometchat-delete-bubble", - "ui-kit/angular/v5/components/cometchat-call-bubble", - "ui-kit/angular/v5/components/cometchat-poll-bubble", - "ui-kit/angular/v5/components/cometchat-sticker-bubble", - "ui-kit/angular/v5/components/cometchat-stickers-keyboard", - "ui-kit/angular/v5/components/cometchat-collaborative-document-bubble", - "ui-kit/angular/v5/components/cometchat-collaborative-whiteboard-bubble" + "ui-kit/angular/v4/interactive-form-message", + "ui-kit/angular/v4/interactive-form-bubble", + "ui-kit/angular/v4/interactive-card-message", + "ui-kit/angular/v4/interactive-card-bubble", + "ui-kit/angular/v4/interactive-element-type", + "ui-kit/angular/v4/interactive-action-entity", + "ui-kit/angular/v4/interactive-custom-interactive-message", + "ui-kit/angular/v4/interactive-button-element", + "ui-kit/angular/v4/interactive-text-input-element", + "ui-kit/angular/v4/interactive-label-element", + "ui-kit/angular/v4/interactive-single-select-element", + "ui-kit/angular/v4/interactive-radio-button-element", + "ui-kit/angular/v4/interactive-checkbox-element", + "ui-kit/angular/v4/interactive-dropdown-element", + "ui-kit/angular/v4/interactive-scheduler-message", + "ui-kit/angular/v4/interactive-scheduler-bubble", + "ui-kit/angular/v4/interactive-date-time-picker-element" ] }, { - "group": "Reactions", + "group": "Calls", "pages": [ - "ui-kit/angular/v5/components/cometchat-reactions", - "ui-kit/angular/v5/components/cometchat-reaction-list", - "ui-kit/angular/v5/components/cometchat-reaction-info" + "ui-kit/angular/v4/call-overview", + "ui-kit/angular/v4/incoming-call", + "ui-kit/angular/v4/ongoing-call", + "ui-kit/angular/v4/outgoing-call", + "ui-kit/angular/v4/call-buttons", + "ui-kit/angular/v4/call-logs", + "ui-kit/angular/v4/call-log-details", + "ui-kit/angular/v4/call-log-history", + "ui-kit/angular/v4/call-log-recording", + "ui-kit/angular/v4/call-log-participants", + "ui-kit/angular/v4/call-log-with-details" ] }, { - "group": "Calls", + "group": "Extras", "pages": [ - "ui-kit/angular/v5/components/cometchat-call-buttons", - "ui-kit/angular/v5/components/cometchat-incoming-call", - "ui-kit/angular/v5/components/cometchat-outgoing-call", - "ui-kit/angular/v5/components/cometchat-call-logs" + "ui-kit/angular/v4/reaction", + "ui-kit/angular/v4/reaction-list", + "ui-kit/angular/v4/reaction-info", + "ui-kit/angular/v4/user-member-wrapper" ] }, { - "group": "AI", + "group": "Base Components", "pages": [ - "ui-kit/angular/v5/components/cometchat-conversation-starter", - "ui-kit/angular/v5/components/cometchat-smart-replies", - "ui-kit/angular/v5/components/cometchat-conversation-summary" + "ui-kit/angular/v4/avatar", + "ui-kit/angular/v4/status-indicator", + "ui-kit/angular/v4/badge", + "ui-kit/angular/v4/receipt", + "ui-kit/angular/v4/date", + "ui-kit/angular/v4/text-bubble", + "ui-kit/angular/v4/image-bubble", + "ui-kit/angular/v4/file-bubble", + "ui-kit/angular/v4/audio-bubble", + "ui-kit/angular/v4/video-bubble", + "ui-kit/angular/v4/message-bubble", + "ui-kit/angular/v4/document-bubble", + "ui-kit/angular/v4/message-input", + "ui-kit/angular/v4/action-sheet", + "ui-kit/angular/v4/media-recorder", + "ui-kit/angular/v4/list-item", + "ui-kit/angular/v4/confirm-dialog", + "ui-kit/angular/v4/backdrop", + "ui-kit/angular/v4/emoji-keyboard", + "ui-kit/angular/v4/modal", + "ui-kit/angular/v4/pop-over", + "ui-kit/angular/v4/icon", + "ui-kit/angular/v4/loader", + "ui-kit/angular/v4/icon-button", + "ui-kit/angular/v4/button-group", + "ui-kit/angular/v4/label", + "ui-kit/angular/v4/input", + "ui-kit/angular/v4/search-input", + "ui-kit/angular/v4/checkbox", + "ui-kit/angular/v4/radio-button", + "ui-kit/angular/v4/dropdown", + "ui-kit/angular/v4/cometchat-quick-view", + "ui-kit/angular/v4/singleselect", + "ui-kit/angular/v4/list" ] } ] @@ -2742,46 +2782,31 @@ { "group": "Reference", "pages": [ - "ui-kit/angular/v5/events", - "ui-kit/angular/v5/methods", - "ui-kit/angular/v5/accessibility", - "ui-kit/angular/v5/troubleshooting" + "ui-kit/angular/v4/methods", + "ui-kit/angular/v4/events" ] }, { "group": "Guides", "pages": [ - "ui-kit/angular/v5/guides/overview", - "ui-kit/angular/v5/guides/threaded-messages", - "ui-kit/angular/v5/guides/block-unblock-user", - "ui-kit/angular/v5/guides/new-chat", - "ui-kit/angular/v5/guides/message-privately", - "ui-kit/angular/v5/guides/call-log-details", - "ui-kit/angular/v5/guides/group-chat", - "ui-kit/angular/v5/guides/custom-text-formatter", - "ui-kit/angular/v5/guides/mentions-formatter", - "ui-kit/angular/v5/guides/hashtag-formatter", - "ui-kit/angular/v5/guides/shortcut-formatter", - "ui-kit/angular/v5/guides/state-management" + "ui-kit/angular/v4/multi-tab-chat-ui-guide", + "ui-kit/angular/v4/new-attachment-option-guide", + "ui-kit/angular/v4/custom-text-formatter-guide", + "ui-kit/angular/v4/mentions-formatter-guide", + "ui-kit/angular/v4/url-formatter-guide", + "ui-kit/angular/v4/shortcut-formatter-guide", + "ui-kit/angular/v4/new-message-option-guide", + "ui-kit/angular/v4/custom-message-guide" ] }, - { - "group": "Services", - "pages": [ - "ui-kit/angular/v5/api-reference/introduction", - "ui-kit/angular/v5/api-reference/chat-state-service", - "ui-kit/angular/v5/api-reference/templates-service", - "ui-kit/angular/v5/api-reference/formatter-config-service", - "ui-kit/angular/v5/api-reference/rich-text-editor-service", - "ui-kit/angular/v5/api-reference/message-bubble-config-service" - ] - } + "ui-kit/angular/v4/link/sample", + "ui-kit/angular/v4/link/changelog" ] } ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎", "groups": [ { "group": " ", @@ -2802,7 +2827,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e\u200e\u200e", + "version": "v2‎‎‎‎‎", "groups": [ { "group": " ", @@ -2829,7 +2854,7 @@ "icon": "/images/icons/vuejs.svg", "versions": [ { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -2922,7 +2947,7 @@ ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -2944,7 +2969,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v2‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -2976,7 +3001,7 @@ "icon": "/images/icons/js.svg", "versions": [ { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3034,6 +3059,7 @@ "sdk/javascript/ai-moderation", "sdk/javascript/ai-agents", "sdk/javascript/ai-copilot", + "sdk/javascript/webhooks", { "group": "Resources", "pages": [ @@ -3068,7 +3094,7 @@ ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3191,7 +3217,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v2‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3294,7 +3320,7 @@ "icon": "/images/icons/react.svg", "versions": [ { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3382,7 +3408,7 @@ ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3496,7 +3522,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v2‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3598,7 +3624,7 @@ "icon": "/images/icons/swift.svg", "versions": [ { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3656,6 +3682,7 @@ }, "sdk/ios/ai-moderation", "sdk/ios/ai-agents", + "sdk/ios/campaigns", { "group": "Resources", "pages": [ @@ -3687,7 +3714,7 @@ ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3805,7 +3832,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v2‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -3912,7 +3939,7 @@ "icon": "/images/icons/android.svg", "versions": [ { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -4013,7 +4040,7 @@ ] }, { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -4107,7 +4134,7 @@ ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -4227,7 +4254,7 @@ ] }, { - "version": "v2\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v2‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -4330,17 +4357,24 @@ "icon": "/images/icons/flutter.svg", "versions": [ { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ "sdk/flutter/overview", "sdk/flutter/setup", - "sdk/flutter/authentication-overview", + { + "group": "Authentication", + "pages": [ + "sdk/flutter/authentication-overview", + "sdk/flutter/login-listeners" + ] + }, { "group": "Messaging", "pages": [ + "sdk/flutter/messaging-overview", "sdk/flutter/send-message", "sdk/flutter/receive-messages", "sdk/flutter/additional-message-filtering", @@ -4358,7 +4392,6 @@ "sdk/flutter/reactions" ] }, - "sdk/flutter/calling-overview", { "group": "Users", "pages": [ @@ -4381,7 +4414,7 @@ "sdk/flutter/delete-group", "sdk/flutter/retrieve-group-members", "sdk/flutter/group-add-members", - "sdk/flutter/group-kick-ban-members", + "sdk/flutter/group-kick-member", "sdk/flutter/group-change-member-scope", "sdk/flutter/transfer-group-ownership" ] @@ -4391,129 +4424,123 @@ { "group": "Resources", "pages": [ - "sdk/flutter/key-concepts", - "sdk/flutter/message-structure-and-hierarchy", - "sdk/flutter/real-time-listeners", - "sdk/flutter/rate-limits", - "sdk/flutter/connection-status", - "sdk/flutter/connection-behaviour" + "sdk/flutter/resources-overview", + "sdk/flutter/real-time-listeners" ] }, { - "group": "Reference", + "group": "Advanced", "pages": [ - "sdk/reference/messages", - "sdk/reference/entities", - "sdk/reference/auxiliary", - "sdk/reference/calls" + "sdk/flutter/advanced-overview", + "sdk/flutter/connection-status", + "sdk/flutter/connection-behaviour" ] }, - "sdk/flutter/upgrading-from-v3-guide", - "sdk/flutter/best-practices", - "sdk/flutter/error-codes", - "sdk/flutter/troubleshooting", + "sdk/flutter/upgrading-from-v4-guide", "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" ] } ] }, { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "sdk/flutter/v5/overview", - "sdk/flutter/v5/setup", - { - "group": "Authentication", - "pages": [ - "sdk/flutter/v5/authentication-overview", - "sdk/flutter/v5/login-listeners" - ] - }, + "sdk/flutter/v4/overview", + "sdk/flutter/v4/setup", + "sdk/flutter/v4/authentication-overview", { "group": "Messaging", "pages": [ - "sdk/flutter/v5/messaging-overview", - "sdk/flutter/v5/send-message", - "sdk/flutter/v5/receive-messages", - "sdk/flutter/v5/additional-message-filtering", - "sdk/flutter/v5/retrieve-conversations", - "sdk/flutter/v5/edit-message", - "sdk/flutter/v5/flag-message", - "sdk/flutter/v5/delete-message", - "sdk/flutter/v5/delete-conversation", - "sdk/flutter/v5/typing-indicators", - "sdk/flutter/v5/interactive-messages", - "sdk/flutter/v5/transient-messages", - "sdk/flutter/v5/delivery-read-receipts", - "sdk/flutter/v5/threaded-messages", - "sdk/flutter/v5/mentions", - "sdk/flutter/v5/reactions" - ] - }, + "sdk/flutter/v4/send-message", + "sdk/flutter/v4/receive-messages", + "sdk/flutter/v4/additional-message-filtering", + "sdk/flutter/v4/retrieve-conversations", + "sdk/flutter/v4/edit-message", + "sdk/flutter/v4/flag-message", + "sdk/flutter/v4/delete-message", + "sdk/flutter/v4/delete-conversation", + "sdk/flutter/v4/typing-indicators", + "sdk/flutter/v4/interactive-messages", + "sdk/flutter/v4/transient-messages", + "sdk/flutter/v4/delivery-read-receipts", + "sdk/flutter/v4/threaded-messages", + "sdk/flutter/v4/mentions", + "sdk/flutter/v4/reactions" + ] + }, + "sdk/flutter/v4/calling-overview", { "group": "Users", "pages": [ - "sdk/flutter/v5/users-overview", - "sdk/flutter/v5/retrieve-users", - "sdk/flutter/v5/user-management", - "sdk/flutter/v5/block-users" + "sdk/flutter/v4/users-overview", + "sdk/flutter/v4/retrieve-users", + "sdk/flutter/v4/user-management", + "sdk/flutter/v4/block-users" ] }, - "sdk/flutter/v5/user-presence", + "sdk/flutter/v4/user-presence", { "group": "Groups", "pages": [ - "sdk/flutter/v5/groups-overview", - "sdk/flutter/v5/retrieve-groups", - "sdk/flutter/v5/create-group", - "sdk/flutter/v5/update-group", - "sdk/flutter/v5/join-group", - "sdk/flutter/v5/leave-group", - "sdk/flutter/v5/delete-group", - "sdk/flutter/v5/retrieve-group-members", - "sdk/flutter/v5/group-add-members", - "sdk/flutter/v5/group-kick-member", - "sdk/flutter/v5/group-change-member-scope", - "sdk/flutter/v5/transfer-group-ownership" + "sdk/flutter/v4/groups-overview", + "sdk/flutter/v4/retrieve-groups", + "sdk/flutter/v4/create-group", + "sdk/flutter/v4/update-group", + "sdk/flutter/v4/join-group", + "sdk/flutter/v4/leave-group", + "sdk/flutter/v4/delete-group", + "sdk/flutter/v4/retrieve-group-members", + "sdk/flutter/v4/group-add-members", + "sdk/flutter/v4/group-kick-ban-members", + "sdk/flutter/v4/group-change-member-scope", + "sdk/flutter/v4/transfer-group-ownership" ] }, - "sdk/flutter/v5/ai-moderation", - "sdk/flutter/v5/ai-agents", + "sdk/flutter/v4/ai-moderation", + "sdk/flutter/v4/ai-agents", { "group": "Resources", "pages": [ - "sdk/flutter/v5/resources-overview", - "sdk/flutter/v5/real-time-listeners" + "sdk/flutter/v4/key-concepts", + "sdk/flutter/v4/message-structure-and-hierarchy", + "sdk/flutter/v4/real-time-listeners", + "sdk/flutter/v4/rate-limits", + "sdk/flutter/v4/connection-status", + "sdk/flutter/v4/connection-behaviour" ] }, { - "group": "Advanced", + "group": "Reference", "pages": [ - "sdk/flutter/v5/advanced-overview", - "sdk/flutter/v5/connection-status", - "sdk/flutter/v5/connection-behaviour" + "sdk/reference/messages", + "sdk/reference/entities", + "sdk/reference/auxiliary", + "sdk/reference/calls" ] }, - "sdk/flutter/v5/upgrading-from-v4-guide", - "sdk/flutter/v5/extensions-overview", - "sdk/flutter/v5/ai-user-copilot-overview", - "sdk/flutter/v5/ai-chatbots-overview", - "sdk/flutter/v5/webhooks-overview", - "sdk/flutter/v5/flutter-overview", - "sdk/flutter/v5/changelog" + "sdk/flutter/v4/upgrading-from-v3-guide", + "sdk/flutter/v4/best-practices", + "sdk/flutter/v4/error-codes", + "sdk/flutter/v4/troubleshooting", + "sdk/flutter/v4/extensions-overview", + "sdk/flutter/v4/ai-user-copilot-overview", + "sdk/flutter/v4/ai-chatbots-overview", + "sdk/flutter/v4/webhooks-overview", + "sdk/flutter/v4/changelog" ] } ] }, { - "version": "v3\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v3‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", @@ -5118,49 +5145,7 @@ "icon": "/images/icons/js.svg", "versions": [ { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", - "groups": [ - { - "group": " ", - "pages": [ - "calls/v4/javascript/overview", - { - "group": "Getting Started", - "pages": [ - "calls/v4/javascript/setup" - ] - }, - { - "group": "Calling Flows", - "pages": [ - "calls/v4/javascript/ringing", - "calls/v4/javascript/call-session", - "calls/v4/javascript/standalone-calling" - ] - }, - { - "group": "Features", - "pages": [ - "calls/v4/javascript/recording", - "calls/v4/javascript/call-logs", - "calls/v4/javascript/session-timeout" - ] - }, - { - "group": "Customisation", - "pages": [ - "calls/v4/javascript/video-view-customisation", - "calls/v4/javascript/presenter-mode", - "calls/v4/javascript/virtual-background", - "calls/v4/javascript/custom-css" - ] - } - ] - } - ] - }, - { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": "Overview", @@ -5236,56 +5221,57 @@ ] } ] - } - ] - }, - { - "dropdown": "React Native", - "icon": "/images/icons/react.svg", - "versions": [ + }, { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "calls/v4/react-native/overview", + "calls/v4/javascript/overview", { "group": "Getting Started", "pages": [ - "calls/v4/react-native/setup", - "calls/v4/react-native/expo-integration-guide" + "calls/v4/javascript/setup" ] }, { "group": "Calling Flows", "pages": [ - "calls/v4/react-native/ringing", - "calls/v4/react-native/call-session", - "calls/v4/react-native/standalone-calling" + "calls/v4/javascript/ringing", + "calls/v4/javascript/call-session", + "calls/v4/javascript/standalone-calling" ] }, { "group": "Features", "pages": [ - "calls/v4/react-native/recording", - "calls/v4/react-native/call-logs", - "calls/v4/react-native/session-timeout" + "calls/v4/javascript/recording", + "calls/v4/javascript/call-logs", + "calls/v4/javascript/session-timeout" ] }, { "group": "Customisation", "pages": [ - "calls/v4/react-native/video-view-customisation", - "calls/v4/react-native/presenter-mode" + "calls/v4/javascript/video-view-customisation", + "calls/v4/javascript/presenter-mode", + "calls/v4/javascript/virtual-background", + "calls/v4/javascript/custom-css" ] } ] } ] - }, + } + ] + }, + { + "dropdown": "React Native", + "icon": "/images/icons/react.svg", + "versions": [ { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": "Overview", @@ -5351,56 +5337,56 @@ ] } ] - } - ] - }, - { - "dropdown": "iOS", - "icon": "/images/icons/swift.svg", - "versions": [ + }, { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "calls/v4/ios/overview", + "calls/v4/react-native/overview", { "group": "Getting Started", "pages": [ - "calls/v4/ios/setup" + "calls/v4/react-native/setup", + "calls/v4/react-native/expo-integration-guide" ] }, { "group": "Calling Flows", "pages": [ - "calls/v4/ios/ringing", - "calls/v4/ios/call-session", - "calls/v4/ios/standalone-calling" + "calls/v4/react-native/ringing", + "calls/v4/react-native/call-session", + "calls/v4/react-native/standalone-calling" ] }, { "group": "Features", "pages": [ - "calls/v4/ios/recording", - "calls/v4/ios/call-logs", - "calls/v4/ios/session-timeout", - "calls/v4/ios/launch-call-screen-on-tap-of-push-notification" + "calls/v4/react-native/recording", + "calls/v4/react-native/call-logs", + "calls/v4/react-native/session-timeout" ] }, { "group": "Customisation", "pages": [ - "calls/v4/ios/video-view-customisation", - "calls/v4/ios/presenter-mode" + "calls/v4/react-native/video-view-customisation", + "calls/v4/react-native/presenter-mode" ] } ] } ] - }, + } + ] + }, + { + "dropdown": "iOS", + "icon": "/images/icons/swift.svg", + "versions": [ { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": "Overview", @@ -5466,55 +5452,56 @@ ] } ] - } - ] - }, - { - "dropdown": "Android", - "icon": "/images/icons/android.svg", - "versions": [ + }, { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "calls/v4/android/overview", + "calls/v4/ios/overview", { "group": "Getting Started", "pages": [ - "calls/v4/android/setup" + "calls/v4/ios/setup" ] }, { "group": "Calling Flows", "pages": [ - "calls/v4/android/ringing", - "calls/v4/android/call-session", - "calls/v4/android/standalone-calling" + "calls/v4/ios/ringing", + "calls/v4/ios/call-session", + "calls/v4/ios/standalone-calling" ] }, { "group": "Features", "pages": [ - "calls/v4/android/recording", - "calls/v4/android/call-logs", - "calls/v4/android/session-timeout" + "calls/v4/ios/recording", + "calls/v4/ios/call-logs", + "calls/v4/ios/session-timeout", + "calls/v4/ios/launch-call-screen-on-tap-of-push-notification" ] }, { "group": "Customisation", "pages": [ - "calls/v4/android/video-view-customisation", - "calls/v4/android/presenter-mode" + "calls/v4/ios/video-view-customisation", + "calls/v4/ios/presenter-mode" ] } ] } ] - }, + } + ] + }, + { + "dropdown": "Android", + "icon": "/images/icons/android.svg", + "versions": [ { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": "Overview", @@ -5580,55 +5567,55 @@ ] } ] - } - ] - }, - { - "dropdown": "Flutter", - "icon": "/images/icons/flutter.svg", - "versions": [ + }, { - "version": "v4\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v4‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": " ", "pages": [ - "calls/v4/flutter/overview", + "calls/v4/android/overview", { "group": "Getting Started", "pages": [ - "calls/v4/flutter/setup" + "calls/v4/android/setup" ] }, { "group": "Calling Flows", "pages": [ - "calls/v4/flutter/ringing", - "calls/v4/flutter/call-session", - "calls/v4/flutter/standalone-calling" + "calls/v4/android/ringing", + "calls/v4/android/call-session", + "calls/v4/android/standalone-calling" ] }, { "group": "Features", "pages": [ - "calls/v4/flutter/recording", - "calls/v4/flutter/call-logs", - "calls/v4/flutter/session-timeout" + "calls/v4/android/recording", + "calls/v4/android/call-logs", + "calls/v4/android/session-timeout" ] }, { "group": "Customisation", "pages": [ - "calls/v4/flutter/video-view-customisation", - "calls/v4/flutter/presenter-mode" + "calls/v4/android/video-view-customisation", + "calls/v4/android/presenter-mode" ] } ] } ] - }, + } + ] + }, + { + "dropdown": "Flutter", + "icon": "/images/icons/flutter.svg", + "versions": [ { - "version": "v5\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e\u200e", + "version": "v5‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", "groups": [ { "group": "Overview", @@ -5694,6 +5681,46 @@ ] } ] + }, + { + "version": "v4‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎", + "groups": [ + { + "group": " ", + "pages": [ + "calls/v4/flutter/overview", + { + "group": "Getting Started", + "pages": [ + "calls/v4/flutter/setup" + ] + }, + { + "group": "Calling Flows", + "pages": [ + "calls/v4/flutter/ringing", + "calls/v4/flutter/call-session", + "calls/v4/flutter/standalone-calling" + ] + }, + { + "group": "Features", + "pages": [ + "calls/v4/flutter/recording", + "calls/v4/flutter/call-logs", + "calls/v4/flutter/session-timeout" + ] + }, + { + "group": "Customisation", + "pages": [ + "calls/v4/flutter/video-view-customisation", + "calls/v4/flutter/presenter-mode" + ] + } + ] + } + ] } ] } @@ -9645,17 +9672,12 @@ "destination": "/calls/flutter/events" } ], - "integrations": { - "gtm": { - "tagId": "GTM-59ZJRV2" - } - }, "seo": { "indexing": "all", "metatags": { "charset": "UTF-8", "viewport": "width=device-width, initial-scale=1.0", - "description": "Learn how to integrate, customize, and scale real-time chat using CometChat\u2019s UI Kits, SDKs, and widgets across popular frameworks. Get step-by-step guides, best practices, and implementation details to build production-ready chat experiences.", + "description": "Learn how to integrate, customize, and scale real-time chat using CometChat’s UI Kits, SDKs, and widgets across popular frameworks. Get step-by-step guides, best practices, and implementation details to build production-ready chat experiences.", "language": "en" } }, diff --git a/fundamentals/tenor.mdx b/fundamentals/tenor.mdx index bedad15ad..1c334129c 100644 --- a/fundamentals/tenor.mdx +++ b/fundamentals/tenor.mdx @@ -7,7 +7,7 @@ GIFs are a great way to change the tone or convey emotions in your conversations ## Before you begin -1. Sign up at [Tenor](https://tenor.com/developer/dashboard) and create a new app. +1. Sign up at [Tenor](https://tenor.com/) and create a new app. 2. Enter your App name, description and click create. 3. Make note of the API key that has been created. diff --git a/images/automatic-web-socket-handling.png b/images/automatic-web-socket-handling.png new file mode 100644 index 000000000..4ef8215fb Binary files /dev/null and b/images/automatic-web-socket-handling.png differ diff --git a/images/manual-web-socket-connection-handling.png b/images/manual-web-socket-connection-handling.png new file mode 100644 index 000000000..d87be94fa Binary files /dev/null and b/images/manual-web-socket-connection-handling.png differ diff --git a/mcp-server.mdx b/mcp-server.mdx index db99638df..901293132 100644 --- a/mcp-server.mdx +++ b/mcp-server.mdx @@ -1,89 +1,140 @@ --- -title: "MCP Server" -description: "Model Context Protocol (MCP) server for CometChat documentation" -canonical: "https://www.cometchat.com/docs/mcp" +title: "Use CometChat with AI Coding Agents (MCP)" +sidebarTitle: "MCP Integration" +description: "Connect CometChat to Claude, Cursor, Windsurf, VS Code, and any other Model Context Protocol–compatible agent. Search docs, fetch reference pages, and pull implementation bundles from inside the conversation." +canonical: "https://www.cometchat.com/docs/mcp-server" --- -## Using the CometChat MCP Server +The **CometChat MCP server** lets Claude, Cursor, Windsurf, VS Code, and any +other Model Context Protocol–compatible agent integrate CometChat into your +app from natural-language prompts. Ask the agent to *"add a chat tab where +users can DM each other"* and it uses the MCP to read CometChat's docs, +pick the right components for your stack, and write the integration code. -### Claude +The server is **read-only** and **needs no account or API key** — it surfaces +CometChat's public documentation and curated implementation recipes. -1. **Add MCP server to Claude** - 1. Navigate to the [Connectors](https://claude.ai) page in Claude’s settings. - 2. Select **Add custom connector**, name it e.g. `CometChat Docs`, and enter the URL: - ``` - https://www.cometchat.com/docs/mcp - ``` - 3. Click **Add**. -2. **Query with context** - 1. In Claude, click the attachments (➕) button. - 2. Select **CometChat Docs**. - 3. Ask your questions—Claude will use your CometChat docs as context. +## Connector URL + +``` +https://mcp.cometchat.com/mcp +``` + +Transport: HTTP with Server-Sent Events. No authentication required. + +## Connect from your agent + +### Claude (Desktop or claude.ai) + +1. Open **Settings → Connectors**. +2. Click **Add custom connector**. +3. Name it `CometChat`, paste the URL `https://mcp.cometchat.com/mcp`, and click **Add**. +4. In a new conversation, attach **CometChat** from the connectors picker and prompt away. ### Cursor -1. **Open MCP settings** - - Press `Cmd+Shift+P` (macOS) / `Ctrl+Shift+P` (Windows) → **Open MCP settings**. - - Select **Add custom MCP** to open your `mcp.json`. -2. **Configure** - ```json - { - "mcpServers": { - "cometchat-docs": { - "url": "https://www.cometchat.com/docs/mcp" - } - } - } - ``` -3. **Verify** - - In Cursor’s chat, ask: - > “How do I integrate CometChat in my React app?” - -{/* ### Lovable.dev - -1. **Open your Lovable project** - - Log in at [Lovable.dev](https://lovable.dev) and select your project. -2. **Add a custom MCP server** - - Go to **Settings** → **Developer Tools** → **MCP Servers**. - - Click **Add custom server**, then: - - **Name:** `CometChat Docs` - - **URL:** `https://www.cometchat.com/docs/mcp` - - Click **Save**. -3. **Use the tools** - - Invoke the CometChat tools in your conversations with Lovable’s AI assistant. */} +1. `Cmd+Shift+P` (macOS) / `Ctrl+Shift+P` (Windows) → **Open MCP settings**. +2. Click **Add custom MCP** and paste: + +```json +{ + "mcpServers": { + "cometchat": { + "url": "https://mcp.cometchat.com/mcp" + } + } +} +``` ### Windsurf -1. **Open Windsurf** - - Launch Windsurf and click the **Plugins** (hammer) icon. -2. **Add or configure** - - In **Manage plugins**, click **Add Custom Server +** or **View raw config**. - - Paste the following into your `mcp_config.json`: - ```json - { - "mcpServers": { - "cometchat-docs": { - "type": "sse", - "serverUrl": "https://www.cometchat.com/docs/mcp" - } - } - } - ``` - - Save and click **Refresh**. -3. **Invoke within Windsurf** - - In the Composer, ask prompts like: - > “Show me how to use CometChat in my app.” - -### Visual Studio Code - -1. **Prerequisites** - - Latest VS Code with Copilot (agent mode) enabled. -2. **Add the server** - - `Cmd+Shift+P` (macOS) / `Ctrl+Shift+P` (Windows) → **MCP: Add MCP Server**. - - Enter: - - **Server Name:** `CometChat Docs` - - **Server URL:** `https://www.cometchat.com/docs/mcp` - - **Transport:** `SSE` (or HTTP stream) - - Confirm. -3. **Use in Copilot agent** - - In a Copilot chat session, your CometChat tools will now be listed and available. +1. Click the **Plugins** (hammer) icon → **Manage plugins** → **View raw config**. +2. Paste: + +```json +{ + "mcpServers": { + "cometchat": { + "type": "sse", + "serverUrl": "https://mcp.cometchat.com/mcp" + } + } +} +``` + +3. Save and click **Refresh**. + +### Visual Studio Code (Copilot Agent) + +1. `Cmd+Shift+P` / `Ctrl+Shift+P` → **MCP: Add MCP Server**. +2. Enter: + - **Server Name:** `CometChat` + - **Server URL:** `https://mcp.cometchat.com/mcp` + - **Transport:** SSE +3. Confirm. + +## Example prompts + +Once connected, try these in a fresh agent conversation: + +- *"Add a chat tab where users can DM each other in my React app."* +- *"Let project members talk in a group chat with file sharing."* +- *"Add video calling between two users with a click-to-call button."* +- *"Set up content moderation so banned words are blocked before delivery."* +- *"Build a multi-tenant SaaS chat where each workspace's users are isolated."* +- *"Add presence indicators and typing dots to my conversation list."* + +The agent will search the docs, pull the matching implementation bundle, +and write the code into your project. + +## What the connector exposes + +### Three tools (all read-only) + + + + Search SDK guides, UI Kit references, REST API docs, and OpenAPI + specs. Returns ranked snippets with direct links. + + + Fetch the full content of any documentation page as markdown by URL + or relative path. + + + Return a curated implementation recipe — prerequisites, install, + configuration, working code — for a named scenario. + + + +### Ten curated implementation bundles + +| Bundle | What it covers | +| --- | --- | +| `react-uikit-quickstart` | React UI Kit install, init, login, conversations list, chat window | +| `react-native-uikit-quickstart` | React Native UI Kit install, navigation, basic chat screen | +| `flutter-uikit-quickstart` | Flutter UI Kit install, init, login, basic chat | +| `ios-uikit-quickstart` | iOS UI Kit (SwiftUI) install, init, login, chat view | +| `android-uikit-quickstart` | Android UI Kit (Compose) install, init, login, chat screen | +| `js-sdk-messaging-basics` | Vanilla JS SDK install, send/receive text and media messages | +| `widget-embed` | No-code widget embed for an existing site | +| `moderation-setup` | AI moderation, profanity filter, image moderation, webhooks | +| `multi-tenant-chat` | Multi-tenant SaaS chat — auth, isolation, tenant-scoped users | +| `presence-and-typing` | Online presence, typing indicators, read receipts | + +### Orientation skill resource + +The MCP also exposes a `cometchat://skills/overview` resource — a structured +markdown document the agent reads once to orient itself on CometChat's +products, decision tree, and common pitfalls. + +## Source + +The MCP server is open-source at +[`github.com/cometchat/cometchat-mcp`](https://github.com/cometchat/docs-mcp). +Built from this very documentation repository, so the content it surfaces +is always in sync with what you see on the docs site. + +## Support + +Questions, feedback, or feature requests: open an issue on the +[GitHub repository](https://github.com/cometchat/docs-mcp/issues) \ No newline at end of file diff --git a/moderation/getting-started.mdx b/moderation/getting-started.mdx index 00d46f47e..310696091 100644 --- a/moderation/getting-started.mdx +++ b/moderation/getting-started.mdx @@ -4,7 +4,7 @@ route: "/getting-started" description: "Getting Started — CometChat documentation." --- -# Moderation Integration +## Moderation Integration To maintain a safe, respectful, and engaging environment for your users, our platform offers a powerful **Moderation Integration** system. This system allows you to automatically review, filter, and take action on user-generated messages, images, and videos before they are delivered. diff --git a/moderation/lists-management.mdx b/moderation/lists-management.mdx index baba04722..20b7b6419 100644 --- a/moderation/lists-management.mdx +++ b/moderation/lists-management.mdx @@ -41,16 +41,27 @@ Create a custom keyword list in under 2 minutes: - Profanity and offensive terms - Brand names or competitors - Industry-specific blocked terms - - **Example:** `badword, offensive, blocked` + + **Entry format:** Comma-separated. Add multiple keywords on the same line, separated by commas. + + **Example:** + ``` + badword, offensive, blocked + ``` Regular expression matching for complex patterns. Use for: - Phone number formats - Email patterns - Custom data formats - - **Example:** `\b\d{3}[-.]?\d{3}[-.]?\d{4}\b` (US phone numbers) + + **Entry format:** Newline-separated — one regex pattern per line. Commas are treated as literal characters inside a pattern, so do **not** comma-separate multiple patterns on the same line. + + **Example:** + ``` + \b\d{3}[-.]?\d{3}[-.]?\d{4}\b + [A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,} + ``` **Greedy Regex Not Allowed:** For system performance and security, greedy regex patterns (using `*`, `+`, `{n,}` without proper boundaries) are not permitted. Greedy patterns can cause excessive backtracking and impact system performance. @@ -72,11 +83,30 @@ Create a custom keyword list in under 2 minutes: - Scam message variations - Platform circumvention attempts - Context-aware blocking - - **Example:** "Send me your credit card details" will match similar phishing attempts + + **Entry format:** Newline-separated — one sentence or phrase per line. + + **Example:** + ``` + Send me your credit card details + What is your bank account number + Share your OTP with me + ``` + +**Entry format at a glance** + +| List type | Format | Separator | +| --- | --- | --- | +| Keywords | Comma-separated | `,` | +| Patterns (Regex) | Newline-separated | New line | +| Sentence Similarity | Newline-separated | New line | + +If you paste comma-separated values into a Patterns or Sentence Similarity list, the entire string is stored as a single entry and will not match as expected. + + --- ## Default Lists Summary @@ -176,7 +206,9 @@ Pre-configured lists ready to use with your rules: - **ID**: Unique identifier - **Category**: Word, Pattern, or Sentence Similarity - **Description**: Purpose of the list - - **Source**: Enter terms manually (comma-separated) or upload CSV + - **Source**: Enter terms manually or upload CSV. Format depends on the category: + - **Word**: comma-separated entries. + - **Pattern** and **Sentence Similarity**: one entry per line (newline-separated). 3. Click **Save** ### List All Lists diff --git a/notifications/flutter-push-notifications-ios.mdx b/notifications/flutter-push-notifications-ios.mdx index 6c9f78679..2e020f564 100644 --- a/notifications/flutter-push-notifications-ios.mdx +++ b/notifications/flutter-push-notifications-ios.mdx @@ -78,7 +78,7 @@ Keep the provider IDs—you’ll set them in `CometChatConfig`. ## 3. Local configuration file -Update [`lib/cometchat_config.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app_push_notifications/lib/cometchat_config.dart) (or your own config file) so it exposes: +Update [`lib/app_credentials.dart`](https://github.com/cometchat/cometchat-uikit-flutter/blob/v5/sample_app_push_notifications/lib/app_credentials.dart) (or your own config file) so it exposes: ```dart lines class CometChatConfig { diff --git a/notifications/logs.mdx b/notifications/logs.mdx index b108d8299..79d90fef1 100644 --- a/notifications/logs.mdx +++ b/notifications/logs.mdx @@ -26,5 +26,15 @@ Logs are kept for up to 14 days: 7 days while logging is active, plus 7 days aft ### Access and filtering -- **Dashboard:** Browse recent logs and narrow by channel, event, user, or status. +- **Dashboard:** Browse recent logs and narrow them down using any of the following filters: + - **Channel** — push, email, or SMS. + - **Event** — message sent, edited, deleted, reaction, group membership change, etc. + - **Sender (User)** — filter by the UID that triggered the notification. + - **Receiver Type** — `user` (one-on-one) or `group`. + - **Receiver ID** — the UID or GUID that should receive the notification. + - **Status** — sent, failed, skipped, etc. - **API:** Use the Get logs API with query parameters (event, medium, receiver, status, time window, provider) for deeper filtering. See the [API explorer](/rest-api/chat-apis) for the full list. + + +**Receiver ID filter requires Receiver Type.** When filtering by Receiver ID in the dashboard, first select a **Receiver Type** (user or group), then enter the Receiver ID. Using Receiver ID without selecting Receiver Type first will not return results. We are tracking this requirement and plan to make Receiver ID work standalone in a future release. + diff --git a/notifications/react-native-push-notifications-ios.mdx b/notifications/react-native-push-notifications-ios.mdx index b6637ed42..f5489fc6e 100644 --- a/notifications/react-native-push-notifications-ios.mdx +++ b/notifications/react-native-push-notifications-ios.mdx @@ -67,7 +67,7 @@ For iOS we use Apple Push Notification service (APNs) for both standard and VoIP 1. Open **Keychain Access** → Certificate Assistant → *Request a Certificate From a Certificate Authority*.
- + Apple Developer portal screenshot 2. In **Certificate Information**, enter your Apple Developer email and a common name; choose **Saved to disk**, then **Continue**. 3. Save the CSR file locally—this contains your public/private key pair. @@ -76,31 +76,31 @@ For iOS we use Apple Push Notification service (APNs) for both standard and VoIP 1. Sign in to the [Apple Developer Member Center](https://developer.apple.com/membercenter) → **Certificates, Identifiers & Profiles**.
- + Apple Developer portal screenshot 2. Click **+** to add a certificate.
- + Apple Developer portal screenshot 3. Under **Services**, pick **Apple Push Notification service SSL (Sandbox & Production)**.
- + Apple Developer portal screenshot 4. Select your App ID, upload the CSR, continue, and download the generated `.cer` file.
- + Apple Developer portal screenshot & - + Apple Developer portal screenshot & - + Apple Developer portal screenshot
diff --git a/sdk/android/connection-behaviour.mdx b/sdk/android/connection-behaviour.mdx index 259c66f7e..4aa6c16ac 100644 --- a/sdk/android/connection-behaviour.mdx +++ b/sdk/android/connection-behaviour.mdx @@ -40,7 +40,7 @@ On login, the SDK logs the user in, saves their details locally, and creates a W The default mode. The SDK automatically establishes and maintains the WebSocket connection. Set `autoEstablishSocketConnection(true)` (or omit it — auto mode is the default). - + CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground | App State | Behaviour | @@ -59,7 +59,7 @@ Set `autoEstablishSocketConnection(false)` to take control of the WebSocket conn 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. - + CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow | App State | Behaviour | diff --git a/sdk/android/transient-messages.mdx b/sdk/android/transient-messages.mdx index 4d6e11059..44c4d1685 100644 --- a/sdk/android/transient-messages.mdx +++ b/sdk/android/transient-messages.mdx @@ -1,7 +1,7 @@ --- 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." +description: "Send and receive ephemeral real-time messages with the CometChat Android SDK 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. diff --git a/sdk/android/v5/connection-behaviour.mdx b/sdk/android/v5/connection-behaviour.mdx index 02a960181..36afd6ee8 100644 --- a/sdk/android/v5/connection-behaviour.mdx +++ b/sdk/android/v5/connection-behaviour.mdx @@ -25,7 +25,7 @@ CometChat SDK default connection behaviour is auto mode. Auto mode, the SDK auto 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. - + CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground | App State | Behaviour | @@ -48,7 +48,7 @@ To keep the WebSocket connection alive even if your app goes in the background, 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. - + CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow | App State | Behaviour | diff --git a/sdk/android/v5/overview.mdx b/sdk/android/v5/overview.mdx index 54348dbab..d8f286428 100644 --- a/sdk/android/v5/overview.mdx +++ b/sdk/android/v5/overview.mdx @@ -1,5 +1,6 @@ --- title: "Overview" +description: "Build Android chat apps with CometChat SDK v5, including real-time messaging, users, groups, and calling support." --- diff --git a/sdk/flutter/additional-message-filtering.mdx b/sdk/flutter/additional-message-filtering.mdx index 35f03b472..5ce56ff1b 100644 --- a/sdk/flutter/additional-message-filtering.mdx +++ b/sdk/flutter/additional-message-filtering.mdx @@ -1,95 +1,35 @@ --- 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 -``` -**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`) | +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: ## 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 `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`. +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`. The default limit is `30`. @@ -105,11 +45,32 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() +## Direct Page Navigation + +*In other words, how do I jump to a specific page of messages* + +You can use the `setPage()` method to directly navigate to a specific page of messages. This enables direct page navigation and improved data handling in paginated responses. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..limit = 30 + ..page = 2).build(); +``` + + + + + ## Messages for a user conversation *In other words, how do I fetch messages between me and any user* -Use the `uid` property to fetch messages between the logged-in user and a specific 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. @@ -128,7 +89,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I fetch messages for any group conversation* -Use the `guid` property to fetch messages from a group. The logged-in user must be a member of the group. +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. @@ -143,15 +104,11 @@ 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* -Use the `messageId` property. This provides messages only after/before the message-id based on if `fetchNext()` or `fetchPrevious()` is called. +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. @@ -168,13 +125,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -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. +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. ## Messages before/after a given time *In other words, how do I fetch messages before or after a particular date or time* -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. +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. @@ -191,13 +148,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -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. +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. ## Unread messages *In other words, how do I fetch unread messages* -Use the `unread` property set to `true` to return just the 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. @@ -214,13 +171,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -Combine with `guid` or `uid` to fetch unread messages for a specific conversation. +This method along with `GUID` or `UID` 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* -Use the `hideMessagesFromBlockedUsers` property. If set to `true`, messages from users blocked by the logged-in user will be excluded. Default is `false`. +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. @@ -237,13 +194,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -This also works in group conversations where both users are members. +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. ## Updated and received messages *In other words, how do I fetch messages that have been received or updated after a particular date or time* -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. +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. @@ -260,13 +217,13 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() -Useful for syncing messages with a local database — fetch only what's changed since your last sync. +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. ## Updated messages only *In other words, how do I fetch messages that have been updated after a particular date or time* -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`. +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. @@ -288,9 +245,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *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/flutter/message-structure-and-hierarchy) to get familiar with the various categories of messages. +We recommend before trying this, you refer to the [Message Structure and Hierarchy](/sdk/flutter/messaging-overview#message-structure-and-hierarchy) guide to get familiar with the various categories of messages. -Use the `categories` property with a list of category names to filter by message category. +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. @@ -310,15 +267,15 @@ 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 *In other words, how do I fetch messages belonging to multiple types* -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. +We recommend you refer to the [Message Structure and Hierarchy](/sdk/flutter/messaging-overview#message-structure-and-hierarchy) guide to get familiar with the various types of messages before trying this out. -Use the `types` property with a list of type names to filter by message type. +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. @@ -338,13 +295,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* -Use the `parentMessageId` property when you have implemented threaded conversations. This will return only messages belonging to the thread with the specified parent ID. +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. @@ -367,7 +324,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* -Use the `hideReplies` property set to `true` to exclude messages that belong to threads. Default is `false`. +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. @@ -388,7 +345,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I exclude deleted messages a user/group conversations* -Use the `hideDeleted` property set to `true` to exclude deleted messages. Default is `false`. +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. @@ -405,32 +362,11 @@ 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* -Use the `tags` property with a list of tag names to fetch only messages with those 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. @@ -454,7 +390,7 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() *In other words, how do I fetch messages with the tags information* -Use the `withTags` property set to `true` to include tag information in the response. Default is `false`. +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` . @@ -463,7 +399,7 @@ String UID = "cometchat-uid-1"; MessagesRequest messageRequest = (MessagesRequestBuilder() ..uid = UID - ..withTags = true + ...withTags = true ..limit = 50).build(); ``` @@ -471,17 +407,11 @@ 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 contain links?* +In other words, as a logged-in user, how do I fetch messages that contains links? -Use the `hasLinks` property set to `true` to fetch only messages containing links. Default is `false`. +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`. @@ -506,9 +436,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with attachments -*In other words, as a logged-in user, how do I fetch messages that contain attachments?* +In other words, as a logged-in user, how do I fetch messages that contains attachments? -Use the `hasAttachments` property set to `true` to fetch only messages with attachments (image, audio, video, or file). Default is `false`. +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`. @@ -533,9 +463,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with reactions -*In other words, as a logged-in user, how do I fetch messages that contain reactions?* +In other words, as a logged-in user, how do I fetch messages that contains reactions? -Use the `hasReactions` property set to `true` to fetch only messages with reactions. Default is `false`. +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`. @@ -560,9 +490,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with mentions -*In other words, as a logged-in user, how do I fetch messages that contain mentions?* +In other words, as a logged-in user, how do I fetch messages that contains mentions? -Use the `hasMentions` property set to `true` to fetch only messages with mentions. Default is `false`. +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`. @@ -587,9 +517,9 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ## Messages with particular user mentions -*In other words, as a logged-in user, how do I fetch messages that mention specific users?* +In other words, as a logged-in user, how do I fetch messages that mentions specific users? -Use the `mentionedUids` property with a list of UIDs to 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. @@ -602,7 +532,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve ```dart String UID = "cometchat-uid-1"; List mentionedUIDs = []; -mentionedUIDs.add("cometchat-uid-1"); +tags.add("cometchat-uid-1"); MessagesRequest messageRequest = (MessagesRequestBuilder() ..uid = UID ..mentionedUids = mentionedUIDs @@ -613,17 +543,42 @@ 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?* +## Messages by attachment types -Use the `attachmentTypes` property with a list of attachment type values to fetch messages with specific attachment types. +*In other words, how do I fetch messages with specific attachment types* - +In order to do this, you can use the `attachmentTypes` parameter. This parameter accepts a list of attachment types. This tells the SDK to fetch messages only with the specified 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"; +List attachmentTypes = []; +attachmentTypes.add("image"); +attachmentTypes.add("video"); - +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..attachmentTypes = attachmentTypes + ..limit = 50).build(); +``` + + + + + +The available attachment types are: +- `image` - Image attachments +- `video` - Video attachments +- `audio` - Audio attachments +- `file` - File/document attachments + +## Hide quoted messages + +*In other words, how do I exclude quoted messages from the response* + +In order to do this, you can use the `hideQuotedMessages` parameter. This parameter accepts boolean as input. When set to `true`, the SDK will not include the quoted message object in the response. The default value for this parameter is `false`. @@ -632,7 +587,7 @@ String UID = "cometchat-uid-1"; MessagesRequest messageRequest = (MessagesRequestBuilder() ..uid = UID - ..attachmentTypes = ["image", "video"] + ..hideQuotedMessages = true ..limit = 50).build(); ``` @@ -640,21 +595,4 @@ MessagesRequest messageRequest = (MessagesRequestBuilder() ---- - -## 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 - - +This can be useful when you want to reduce the payload size and don't need the full quoted message details in the response. diff --git a/sdk/flutter/v5/advanced-overview.mdx b/sdk/flutter/advanced-overview.mdx similarity index 100% rename from sdk/flutter/v5/advanced-overview.mdx rename to sdk/flutter/advanced-overview.mdx diff --git a/sdk/flutter/ai-agents.mdx b/sdk/flutter/ai-agents.mdx index 173304cf6..087b6bceb 100644 --- a/sdk/flutter/ai-agents.mdx +++ b/sdk/flutter/ai-agents.mdx @@ -1,98 +1,41 @@ --- 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." +description: "Learn how to integrate AI Agents in your Flutter app to process messages, trigger tools, and respond with context." --- - - -| 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. - +# 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**. ## Agent Run Lifecycle and Message Flow -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` +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`**. ### Real-time Events - -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 | +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. @@ -126,16 +69,12 @@ 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. @@ -143,31 +82,10 @@ Always remove AI Assistant listeners when they're no longer needed (e.g., on wid ### Agentic Messages -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 | +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. @@ -194,23 +112,4 @@ The `toolCalls` on `AIToolArgumentMessage` returns a list of `AIToolCall` object } ``` - - ---- - -## 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 - - + \ No newline at end of file diff --git a/sdk/flutter/ai-chatbots-overview.mdx b/sdk/flutter/ai-chatbots-overview.mdx index f3037d7e9..7a460169b 100644 --- a/sdk/flutter/ai-chatbots-overview.mdx +++ b/sdk/flutter/ai-chatbots-overview.mdx @@ -1,65 +1,4 @@ --- 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 4d8868826..e0414eb82 100644 --- a/sdk/flutter/ai-moderation.mdx +++ b/sdk/flutter/ai-moderation.mdx @@ -1,42 +1,11 @@ --- 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). @@ -84,8 +53,6 @@ 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 | @@ -131,99 +98,6 @@ 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: @@ -298,20 +172,4 @@ When a message is disapproved, handle it appropriately in your UI: ## Next Steps - -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 - - +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. diff --git a/sdk/flutter/ai-user-copilot-overview.mdx b/sdk/flutter/ai-user-copilot-overview.mdx index 12601d050..3e798a3fb 100644 --- a/sdk/flutter/ai-user-copilot-overview.mdx +++ b/sdk/flutter/ai-user-copilot-overview.mdx @@ -1,6 +1,4 @@ --- 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/authentication-overview.mdx b/sdk/flutter/authentication-overview.mdx index 07ff5d486..87b335748 100644 --- a/sdk/flutter/authentication-overview.mdx +++ b/sdk/flutter/authentication-overview.mdx @@ -1,69 +1,52 @@ --- title: "Authentication" -sidebarTitle: "Authentication" -description: "Create users, log in with Auth Key or Auth Token, check login status, and log out using the CometChat Flutter SDK." +sidebarTitle: "Overview" --- -{/* TL;DR for Agents and Quick Reference */} - +To allow a user to use CometChat, the user must log in to CometChat. -```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` - +**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. -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. +**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, you can associate them as friends in CometChat. -### How It Works +### Typical Workflow ```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) + participant App as Your App + participant Server as Your Server + participant CC as CometChat + + Note over App,CC: Registration + App->>Server: User registers + Server->>Server: Store user in DB + Server->>CC: Create user via REST API + + Note over App,CC: Login + App->>Server: User logs in + Server->>Server: Verify credentials + Server->>CC: Generate Auth Token + Server-->>App: Return Auth Token + App->>CC: CometChat.login(uid, authToken) + CC-->>App: Session established + + Note over App,CC: Messaging + App->>CC: Send and receive messages ``` -## Before You Log In +| Your App | Your Server | CometChat | +|----------|-------------|-----------| +| User registers | Store user info in your database | Create user via REST API (ID & name) | +| User logs in | Verify credentials, retrieve user ID | Log in user programmatically | +| User sends a friend request | Display the request to the potential friend | No action required | +| User accepts a friend request | Display the users as friends | Add both users as friends via REST API | -### Create a User +## Create User -A user must exist in CometChat before they can log in. +Before you login the user, you must add the user to CometChat. -- **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. +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. @@ -71,31 +54,19 @@ We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid -### Check for an Existing Session +Once initialization is successful, you will need to log the user into CometChat using 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. +We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once. -```dart -User? user = await CometChat.getLoggedInUser(); -if (user != null) { - // User is already logged in — proceed to your app -} -``` - -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 | + +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. -## 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 [Auth Token](#login-with-auth-token) instead of an Auth Key to ensure enhanced security. +## Login using Auth Key - -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. - +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. @@ -118,56 +89,20 @@ await CometChat.login(UID, authKey, -| 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: - - - -**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 | Description | +| --------- | -------------------------------------------------- | +| UID | The `UID` of the user that you would like to login | +| authKey | CometChat App Auth Key | - +After the user logs in, their information is returned in the `User` object. - +## Login using Auth Token -**CometChatException:** +This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. -| 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()`. +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. @@ -190,51 +125,15 @@ if (user == null) { -| 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: - - - -**User Object:** +| Parameter | Description | +| ---------------------------------------------- | ----------- | +| authToken | Auth Token of the user you would like to login | -| 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."` | - - +After the user logs in, their information is returned in the `User` object. ## Logout -Call `logout()` when your user logs out of your app. This clears the local session. +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. @@ -250,99 +149,3 @@ 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/block-users.mdx b/sdk/flutter/block-users.mdx index 6370279cd..8613e6df1 100644 --- a/sdk/flutter/block-users.mdx +++ b/sdk/flutter/block-users.mdx @@ -1,54 +1,14 @@ --- 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 `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 | +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. @@ -68,46 +28,13 @@ 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 `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 | +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. @@ -128,31 +55,6 @@ 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 @@ -163,15 +65,6 @@ 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. @@ -216,7 +109,7 @@ BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() ```dart BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() ..limit = 50 - ..direction = CometChatBlockedUsersDirection.directionBlockedByMe + .direction = CometChatBlockedUsersDirection.directionBlockedByMe ).build(); ``` @@ -245,63 +138,3 @@ 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/changelog.mdx b/sdk/flutter/changelog.mdx index d482ab3bb..eb92a1622 100644 --- a/sdk/flutter/changelog.mdx +++ b/sdk/flutter/changelog.mdx @@ -1,6 +1,4 @@ --- title: "Changelog" -sidebarTitle: "Changelog" url: "https://github.com/cometchat/chat-sdk-flutter/releases" -description: "Navigate to Changelog documentation." --- \ No newline at end of file diff --git a/sdk/flutter/connection-behaviour.mdx b/sdk/flutter/connection-behaviour.mdx index fb2e027ee..76557985f 100644 --- a/sdk/flutter/connection-behaviour.mdx +++ b/sdk/flutter/connection-behaviour.mdx @@ -1,36 +1,8 @@ --- 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 @@ -46,8 +18,6 @@ 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. @@ -55,7 +25,7 @@ CometChat SDK default connection behaviour is auto mode. Auto mode, the SDK auto 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. - + CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground | App State | Behaviour | @@ -81,7 +51,7 @@ To keep the WebSocket connection alive even if your app goes in the background, 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. - + CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow | App State | Behaviour | @@ -120,25 +90,6 @@ 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 @@ -162,25 +113,6 @@ 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. @@ -202,25 +134,6 @@ 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 @@ -248,44 +161,6 @@ 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 890d70074..a0877d610 100644 --- a/sdk/flutter/connection-status.mdx +++ b/sdk/flutter/connection-status.mdx @@ -1,89 +1,24 @@ --- 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: -1. `CometChatWSState.connected` (connected) -2. `CometChatWSState.connecting` (connecting) -3. `CometChatWSState.disconnected` (disconnected) -4. `CometChatWSState.featureThrottled` (featureThrottled) +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 -## Listen for Connection Changes +Connection Status provides you with the below 3 methods to get the status of the connection to CometChat web-socket servers: -Register a `ConnectionListener` to receive real-time connection state updates. We recommend adding this on app startup after `CometChat.init()` completes. +| 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. | -### 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 | +Once the connection is broken, the disconnected callback is triggered, the SDK automatically tries to establish the connection again, thus going into the connecting state and triggering the `connecting` method. Once the attempt to connect is successful, the `connected` method is triggered thus letting the developer know that the connection is established and is active. +In order to use the ConnectionListeners, you need to add the ConnectionListeners using the `addConnectionListener` method provided by the SDK. You can add multiple listeners as shown below. Just make sure you add listeners with unique IDs. @@ -125,37 +60,27 @@ void onConnectionError(CometChatException error) { - -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 +You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK + + ```dart -CometChat.removeConnectionListener("listenerId"); +String connectionStatus = CometChat.getConnectionStatus(); ``` + + + + +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 0c6157da2..feb4149fc 100644 --- a/sdk/flutter/create-group.mdx +++ b/sdk/flutter/create-group.mdx @@ -1,59 +1,22 @@ --- 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?* - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) - +You can create a group using `createGroup()` method. This method takes a `Group` object as input. -Use `createGroup()` to create a new group. Pass a `Group` object with the group details. +The `groupType` needs to be either of the below 3 values: -| 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 | +1.`CometChatGroupType.`*public* (public) -### Parameters +2.`CometChatGroupType.`*password* (password) -| 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 | +3.`CometChatGroupType.`*private* (private) @@ -77,45 +40,13 @@ String GUID = "GUID"; - -**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` | - - - - +The `createGroup()` method takes the following parameters: -| 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."` | +| Parameter | Description | +| --------- | ---------------------------- | +| `group` | An instance of `Group` class | - - -On success, returns a [`Group`](/sdk/reference/entities#group) object with the created group's details. +After the successful creation of the group, you will receive an instance of `Group` class which contains all the information about the particular group. @@ -123,45 +54,39 @@ 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. +## Create a Group with Members -### Parameters +*In other words, how do I create a group and add members in a single step?* -| 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)` +You can create a group and add members simultaneously using the `createGroupWithMembers()` method. This is more efficient than creating a group first and then adding members separately. ```dart -String GUID = "cometchat-guid-11"; +String GUID = "GUID"; 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( +// Create a list of group members to add +List members = []; +members.add(GroupMember(uid: "cometchat-uid-1", scope: CometChatMemberScope.participant)); +members.add(GroupMember(uid: "cometchat-uid-2", scope: CometChatMemberScope.moderator)); +members.add(GroupMember(uid: "cometchat-uid-3", scope: CometChatMemberScope.admin)); + +await CometChat.createGroupWithMembers( group: group, - groupMembers: members, - bannedUserIds: bannedUserIds, - onSuccess: (Group group) { - debugPrint("Group created with members: ${group.name}"); + members: members, + onSuccess: (Group group, Map failedMembers) { + debugPrint("Group Created Successfully : $group"); + if (failedMembers.isNotEmpty) { + debugPrint("Failed to add some members: $failedMembers"); + } }, onError: (CometChatException e) { - debugPrint("Error creating group with members: ${e.message}"); - }, + debugPrint("Group Creation failed with exception: ${e.message}"); + } ); ``` @@ -169,48 +94,26 @@ CometChat.createGroupWithMembers( - -**On Success** — A `Group` object containing all details of the newly created group: +The `createGroupWithMembers()` method takes the following parameters: - +| Parameter | Description | +| --------- | ---------------------------------------------------------- | +| `group` | An instance of `Group` class | +| `members` | A list of `GroupMember` objects to be added to the group | -**Group Object:** +The `onSuccess` callback returns: +- `group`: The created `Group` object +- `failedMembers`: A map containing UIDs of members that failed to be added along with the error reason -| 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` | +The `GroupMember` class takes the following parameters: - - - - -| 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."` | - - +| Parameter | Description | +| --------- | ------------------------------------------------------------------------------------------------ | +| `uid` | The UID of the user to be added as a member | +| `scope` | The scope of the member: `CometChatMemberScope.participant`, `moderator`, or `admin` | ## 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 | @@ -228,22 +131,4 @@ The [`Group`](/sdk/reference/entities#group) object has the following fields. Fi | 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 - - +| isBannedFromGroup | No | A boolean indicating whether the logged-in user is banned from the group. | diff --git a/sdk/flutter/delete-conversation.mdx b/sdk/flutter/delete-conversation.mdx index 7eed0b031..57473b8ca 100644 --- a/sdk/flutter/delete-conversation.mdx +++ b/sdk/flutter/delete-conversation.mdx @@ -1,44 +1,12 @@ --- -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." +title: "Delete A Conversation" --- -{/* 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}"), -); -``` -**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. 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. +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. @@ -75,51 +43,11 @@ 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 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."` | - - - ---- +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). -## Next Steps +The `deleteConversation()` method takes the following parameters: - - - Fetch and filter conversation lists - - - Delete individual messages from conversations - - - Listen for incoming messages in real-time - - - Show when users are typing in conversations - - +| 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 | diff --git a/sdk/flutter/delete-group.mdx b/sdk/flutter/delete-group.mdx index 4f48f7e14..2bc36f2e0 100644 --- a/sdk/flutter/delete-group.mdx +++ b/sdk/flutter/delete-group.mdx @@ -1,49 +1,12 @@ --- 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. - -This operation is irreversible. Deleted groups and their messages cannot be recovered. - +## Delete Group -## 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 | +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. @@ -61,44 +24,8 @@ debugPrint("Delete Group failed with exception: ${e.message}"); - -**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 +The `deleteGroup()` method takes the following parameters: - - - 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 - - +| Parameter | Description | +| --------- | ---------------------------------------------- | +| `GUID` | The GUID of the group you would like to delete | diff --git a/sdk/flutter/delete-message.mdx b/sdk/flutter/delete-message.mdx index 0240e6336..ebf63f117 100644 --- a/sdk/flutter/delete-message.mdx +++ b/sdk/flutter/delete-message.mdx @@ -1,70 +1,19 @@ --- 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) when your app was not running. - - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) - +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. ## Delete a Message *In other words, as a sender, how do I delete a message?* -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. | +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. @@ -84,103 +33,13 @@ await CometChat.deleteMessage(messageId, - -**On Success** — A `BaseMessage` object with `deletedAt` and `deletedBy` fields set: - - - -**BaseMessage Object:** - -| 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` | +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. - - - - -| 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: +By default, CometChat allows certain roles to delete a 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 | +## Real-time Message Delete Events -By default, CometChat allows certain roles to delete a message. +*In other words, as a recipient, how do I know when someone deletes a message when my app is running?* | User Role | Conversation Type | Deletion Capabilities | | --------------- | ----------------------- | ------------------------- | @@ -189,11 +48,7 @@ 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 | -## 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. +In order to receive real-time events for a message being deleted, you need to override the `onMessageDeleted()` method of the `MessageListener` class. @@ -214,27 +69,6 @@ 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?* @@ -249,24 +83,7 @@ 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. - ---- - -## Next Steps +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. - - - 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 ca2605290..19be057f3 100644 --- a/sdk/flutter/delivery-read-receipts.mdx +++ b/sdk/flutter/delivery-read-receipts.mdx @@ -1,81 +1,29 @@ --- 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 delivered using the `markAsDelivered()` method. This method takes a `BaseMessage` object as input. +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 | +| ------------ | ---------------------------------------------------------------------------------------------------------- | +| 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). | -| 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. +Messages for both user & group conversations can be marked as read 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 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. +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. -This method will mark all the messages before the message specified, for the conversation with `receiverId` and `receiverType` (user/group) as delivered. +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 `markAsDelivered()` method with the callbacks as shown below: @@ -83,9 +31,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} "); }); ``` @@ -93,40 +41,21 @@ CometChat.markAsDelivered(message, onSuccess: (String unused) { - -**On Success** — A `String` message confirming the message has been marked as delivered: - - - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | `String` | Success confirmation message | `"markAsDelivered 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 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. +You can mark the messages for a particular conversation as read using the `markAsRead()` method. This method takes the below parameters as input: + +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 | 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. | +| 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). | Messages for both user and group conversations can be marked as read using this method. @@ -166,29 +95,6 @@ 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. @@ -199,72 +105,86 @@ This feature is valuable for users who want to revisit and respond to important You can mark the messages for a particular conversation as unread using the `markMessageAsUnread()` method. -| 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. +| 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. | ```dart CometChat.markMessageAsUnread( - message, - onSuccess: (Conversation conversation) { - debugPrint("markMessageAsUnread : $conversation"); - }, - onError: (CometChatException error) { - debugPrint("markMessageAsUnread unsuccessful : $error"); - }, -); + message, + onSuccess: (success) { + debugPrint("markMessageAsUnread : $success"); + }, + onError: (error) { + debugPrint("markMessageAsUnread unsuccessful : $error"); + }, + ); ``` - -**On Success** — A `Conversation` object with the updated unread message count: +## Mark Conversation as Delivered - +*In other words, how do I mark an entire conversation as delivered?* -| 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 | +You can mark an entire conversation as delivered using the `markConversationAsDelivered()` method. This is useful when you want to signal that all messages in a conversation have been delivered to the recipient. - + + +```dart +CometChat.markConversationAsDelivered( + conversation, + onSuccess: (success) { + debugPrint("markConversationAsDelivered : $success"); + }, + onError: (error) { + debugPrint("markConversationAsDelivered unsuccessful : $error"); + }, + ); +``` + + + + + +## Mark Conversation as Read + +*In other words, how do I mark an entire conversation as read?* - +You can mark an entire conversation as read using the `markConversationAsRead()` method. This updates the status of all messages in the conversation to "read". - + + +```dart +CometChat.markConversationAsRead( + conversation, + onSuccess: (success) { + debugPrint("markConversationAsRead : $success"); + }, + onError: (error) { + debugPrint("markConversationAsRead unsuccessful : $error"); + }, + ); +``` -| 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 - -Register a `MessageListener` to receive delivery and read receipt events. +### 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. +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. @@ -299,29 +219,17 @@ void onMessagesReadByAll(MessageReceipt messageReceipt) { - -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. +You will receive events in the form of `MessageReceipt` objects. The message receipt contains the following parameters: -```dart -@override -void dispose() { - CometChat.removeMessageListener("listenerId"); - super.dispose(); -} -``` - - -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. | +| 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. | ### Missed Receipts @@ -329,25 +237,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. - -| 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. | +In order to fetch the message receipts, you can use the `getMessageReceipts()` method. ```dart -int messageId = 10101; +private int messageId = 10101; -CometChat.getMessageReceipts(messageId, onSuccess: (List messageReceipts) { - debugPrint("Message receipts fetched: $messageReceipts"); -}, onError: (CometChatException e) { - debugPrint("Error fetching receipts: ${e.message}"); +CometChat.getMessageReceipts(messageId, new CometChat.CallbackListener>() { +@Override + public void onSuccess(List messageReceipts) { + // Handle message receipts +} + +@Override + public void onError(CometChatException e) { + // Handle error +} }); ``` @@ -355,36 +263,7 @@ CometChat.getMessageReceipts(messageId, onSuccess: (List message - -**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. +You will receive a list of `MessageReceipt` objects in the `onSuccess()` method. @@ -395,24 +274,7 @@ The following features will be available only if the **Enhanced Messaging Status * `deliveredAt` field in a group message, * `readAt` field in a group message. * `markMessageAsUnread` method. +* `markConversationAsDelivered` method. +* `markConversationAsRead` 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/edit-message.mdx b/sdk/flutter/edit-message.mdx index f9f54efde..76ae225c6 100644 --- a/sdk/flutter/edit-message.mdx +++ b/sdk/flutter/edit-message.mdx @@ -1,72 +1,26 @@ --- -title: "Edit Message" -sidebarTitle: "Edit Message" -description: "Edit text and custom messages using the CometChat Flutter SDK." +title: "Edit A Message" --- -{/* 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 | -```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: +While editing a message is straightforward, receiving events for edited messages with CometChat has two parts: -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 +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 ## 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 other words, as a sender, how do I edit a 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. | +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 -Use `tags` to update tags when editing. New tags replace existing ones. +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. - + ```dart List tags = []; tags.add("pinned"); @@ -75,18 +29,9 @@ textMessage.tags = tags; - -```dart -List tags = []; -tags.add("pinned"); -customMessage.tags = tags; -``` - - - -Once the message object is ready, call `editMessage()`. +Once the message object is ready, you can use the `editMessage()` method and pass the message object to it. @@ -112,103 +57,7 @@ await CometChat.editMessage(updatedMessage, - -**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 | +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 roles to edit a message. @@ -221,7 +70,9 @@ By default, CometChat allows certain roles to edit a message. ## Real-time Message Edit Events -Use `onMessageEdited` in `MessageListener` to receive real-time 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. @@ -241,56 +92,21 @@ void onMessageEdited(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 `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. - -Relevant fields to access on the returned message: +## Missed Message Edit Events -| 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 | +*In other words, as a recipient, how do I know when someone edited their message when my app was not running?* -## Missed Message Edit Events +When you retrieve the list of previous messages, for the message that was edited, the `editedAt` and the `editedBy` fields will be set. Also, for example, if the total number of messages for a conversation is 100, and the message with message ID 50 was edited. 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- -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 +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. -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 - - - - 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/extensions-overview.mdx b/sdk/flutter/extensions-overview.mdx index 5dcf22fb9..29c1774bd 100644 --- a/sdk/flutter/extensions-overview.mdx +++ b/sdk/flutter/extensions-overview.mdx @@ -1,144 +1,4 @@ --- title: "Extensions" -sidebarTitle: "Extensions" -description: "Explore CometChat extensions that add enhanced functionality to your Flutter chat application" url: "/fundamentals/extensions-overview" ---- - - -**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 - - +--- \ No newline at end of file diff --git a/sdk/flutter/flag-message.mdx b/sdk/flutter/flag-message.mdx index a2f8d6530..02b71550c 100644 --- a/sdk/flutter/flag-message.mdx +++ b/sdk/flutter/flag-message.mdx @@ -1,48 +1,11 @@ --- 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. @@ -88,7 +51,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}, Name: ${reason.name}"); + print("Reason ID: ${reason.id}, Title: ${reason.title}"); } }, onError: (CometChatException e) { @@ -105,21 +68,8 @@ The response is a list of `FlagReason` objects containing: | Property | Type | Description | |----------|------|-------------| -| `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."` | - - +| id | String | Unique identifier for the reason | +| title | String | Display text for the reason | ## Flag a Message @@ -130,10 +80,9 @@ 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, @@ -153,29 +102,18 @@ 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 | - - -**On Success** — A `String` message confirming the message has been flagged: - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | `String` | Success confirmation message | `"Message 123 has been flagged successfully."` | +| 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 | - - - - -| 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."` | +### Response - +```json +{ + "message": "Message {id} has been flagged successfully." +} +``` ## Complete Example @@ -216,10 +154,12 @@ Here's a complete implementation showing how to build a report message flow: }) async { final completer = Completer(); - FlagDetail flagDetail = FlagDetail( - reasonId: reasonId, - remark: remark, - ); + FlagDetail flagDetail = FlagDetail() + ..reasonId = reasonId; + + if (remark != null) { + flagDetail.remark = remark; + } CometChat.flagMessage( messageId, @@ -257,22 +197,3 @@ 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/v5/flutter-overview.mdx b/sdk/flutter/flutter-overview.mdx similarity index 100% rename from sdk/flutter/v5/flutter-overview.mdx rename to sdk/flutter/flutter-overview.mdx diff --git a/sdk/flutter/group-add-members.mdx b/sdk/flutter/group-add-members.mdx index 36b38943c..e125be98b 100644 --- a/sdk/flutter/group-add-members.mdx +++ b/sdk/flutter/group-add-members.mdx @@ -1,57 +1,16 @@ --- 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 - -**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). +You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: -| 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. +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. @@ -79,39 +38,21 @@ CometChat.addMembersToGroup( guid: conversationWith, - -**On Success** — A `Map` where each key is the UID of the user and the value is either `"success"` or an error message: - - - -| 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"` | - - - - - - - -| 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."` | - - - -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. +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. ## 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. + -Implement `onMemberAddedToGroup()` in `GroupListener` to receive real-time notifications when members are added. +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. @@ -130,49 +71,15 @@ void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group add -| 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 | +## Member Added to Group event in Message History - -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. +*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?* -```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. +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: - -| 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- -## 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 - - +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 diff --git a/sdk/flutter/group-change-member-scope.mdx b/sdk/flutter/group-change-member-scope.mdx index 0420f4fdb..412b54b93 100644 --- a/sdk/flutter/group-change-member-scope.mdx +++ b/sdk/flutter/group-change-member-scope.mdx @@ -1,37 +1,12 @@ --- 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 -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) - +In order to change the scope of a group member, you can use the `changeGroupMemberScope()`. @@ -40,12 +15,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}"); }); ``` @@ -55,42 +30,19 @@ CometChat.updateGroupMemberScope(guid: GUID, uid: UID, scope: scope, This method takes the below parameters: -| 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 | +| 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) | The default scope of any member is `participant`. Only the **Admin** of the group can change the scope of any participant in the group. - -**On Success** — A `String` message confirming the scope change: - - - -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | string | Success confirmation message | `"cometchat-guid-1 scope changed 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 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. +*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 @@ -110,42 +62,17 @@ 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 -When fetching previous messages, scope changes appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). +*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?* -| 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 | +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- -## 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 - - +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 diff --git a/sdk/flutter/v5/group-kick-member.mdx b/sdk/flutter/group-kick-member.mdx similarity index 100% rename from sdk/flutter/v5/group-kick-member.mdx rename to sdk/flutter/group-kick-member.mdx diff --git a/sdk/flutter/groups-overview.mdx b/sdk/flutter/groups-overview.mdx index 3e27ebc8c..f219e6c57 100644 --- a/sdk/flutter/groups-overview.mdx +++ b/sdk/flutter/groups-overview.mdx @@ -1,75 +1,61 @@ --- title: "Groups" sidebarTitle: "Overview" -description: "Overview of group management in the CometChat Flutter SDK including group types, member roles, and available operations." --- - +A group can be used for multiple users to communicate with each other on a particular topic or interest. -| 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) | +## GUID - +- 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. -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) - + +GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. + ## 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 - - +CometChat supports three different types of groups: + +```mermaid +flowchart LR + G["Group"] --> Public + G --> Password + G --> Private + + Public -.- P1["Visible to all, anyone can join"] + Password -.- P2["Visible to all, requires password"] + Private -.- P3["Hidden, invite only"] +``` + +| Type | Visibility | Participation | +|------|-----------|---------------| +| Public | All users | Any user can choose to join | +| Password | All users | Any user with a valid password can join | +| Private | Only members | Invited users are auto-joined | + +## Member Scopes + +Once a participant joins a group, they become a member. Members remain part of the group indefinitely — to stop receiving messages, calls, and notifications, a member must be kicked, banned, or leave the group. + +```mermaid +flowchart TD + Admin["Admin (Group creator)"] + Moderator["Moderator"] + Participant["Participant (Default scope)"] + + Admin -->|Can promote or demote| Moderator + Admin -->|Can promote or demote| Participant + Moderator -->|Can promote or demote| Participant + + Admin -.- A1["Full control: manage members, update/delete group, message & call"] + Moderator -.- M1["Moderate: kick/ban participants, update group, message & call"] + Participant -.- P1["Basic: send & receive messages & calls"] +``` + +| Scope | Default | Privileges | +|-------|---------|-----------| +| Admin | Group creator | Manage all members, add members, kick & ban anyone, send & receive messages & calls, update & delete group | +| Moderator | — | Change scope of participants, kick & ban participants, update group, send & receive messages & calls | +| Participant | All other members | Send & receive messages & calls | diff --git a/sdk/flutter/interactive-messages.mdx b/sdk/flutter/interactive-messages.mdx index e13d96a3e..ce85974c3 100644 --- a/sdk/flutter/interactive-messages.mdx +++ b/sdk/flutter/interactive-messages.mdx @@ -1,77 +1,81 @@ --- 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 -// 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) { } +await CometChat.markAsInteracted(messageId, interactedElementId, + onSuccess: (String message ){ + //write code here for after success + + }, onError: + (CometChatException excep){ + //write code here for after err + + }); ``` - + + + + +### 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: -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. +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. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) - +### InteractionGoal -## InteractiveMessage +The `InteractionGoal` represents the desired outcome of an interaction with an InteractiveMessage. It includes: -The `InteractiveMessage` class extends `BaseMessage` and represents a message with embedded interactive content. +* `elementIds`: A list of identifiers for the interactive elements. +* `type`: The type of interaction goal from the `CometChatConstants`. -| 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 | +### 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. -Use `CometChat.sendInteractiveMessage()` to send an interactive message. +Here is an example of how to use it: - + ```dart final Map interactiveData = { "title": "Survey", @@ -169,297 +173,19 @@ 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}"); - }, -); -``` - - -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. - -## Interactions - -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 | - -## 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 - }, - ); -} -``` - - - +### Event Listeners -| Parameter | Type | Description | Required | -| --- | --- | --- | --- | -| `messageId` | `int` | The ID of the interactive message | Yes | -| `interactedElementId` | `String` | The element ID that was interacted with | Yes | +CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. - -**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 +### On InteractiveMessage Received The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. +Here is an example: + ```dart @@ -482,21 +208,14 @@ void onInteractiveMessageReceived(InteractiveMessage message){ ``` + -### Interaction Goal Completed +### On Interaction Goal Completed The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. -`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 | +Here is an exampl @@ -519,61 +238,11 @@ 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. - -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}"); - }, -); -``` - - - - ---- +### Usage -## 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 - - +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. diff --git a/sdk/flutter/join-group.mdx b/sdk/flutter/join-group.mdx index bc2595378..41e6b00da 100644 --- a/sdk/flutter/join-group.mdx +++ b/sdk/flutter/join-group.mdx @@ -1,48 +1,12 @@ --- 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 -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 | +In order to start participating in group conversations, you will have to join a group. You can do so using the `joinGroup()` method. @@ -63,45 +27,19 @@ CometChat.joinGroup(GUID, groupType, password: password, - -**On Success** — A `Group` object containing all details of the joined group: - - - -**Group Object:** +The `joinGroup()` method takes the below parameters -| 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` | +| 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. | - +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. -| 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. +You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. ## Real-time Group Member Joined Events @@ -112,13 +50,12 @@ If a user joins any group, the members of the group receive a real-time event in ```dart -class ClassName with GroupListener { - // CometChat.addGroupListener("group_Listener_id", this); +class Class_Name with GroupListener { - @override - void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { - debugPrint("onGroupMemberJoined"); - } +//CometChat.addGroupListener("group_Listener_id", this); +@override +void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { + debugPrint("onGroupMemberJoined"); } ``` @@ -126,14 +63,6 @@ class ClassName with GroupListener { - -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?* @@ -145,22 +74,3 @@ 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/leave-group.mdx b/sdk/flutter/leave-group.mdx index 3d57928d7..f73638b8d 100644 --- a/sdk/flutter/leave-group.mdx +++ b/sdk/flutter/leave-group.mdx @@ -1,48 +1,12 @@ --- 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 -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 | +In order to stop receiving updates and messages for any particular joined group, you will have to leave the group using the `leaveGroup()` method. @@ -60,28 +24,9 @@ CometChat.leaveGroup(GUID, onSuccess: ( String message) { - -**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."` | - - +| Parameter | Description | +| --------- | --------------------------------------------- | +| `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. @@ -109,41 +54,14 @@ 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`](/sdk/reference/messages#action) message. An `Action` message is a sub-class of [`BaseMessage`](/sdk/reference/messages#basemessage) class. +When you retrieve the list of previous messages if a member has left any group that the logged-in user is a member of, the list of messages will contain an `Action` message. An `Action` message is a sub-class of `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/v5/login-listeners.mdx b/sdk/flutter/login-listeners.mdx similarity index 100% rename from sdk/flutter/v5/login-listeners.mdx rename to sdk/flutter/login-listeners.mdx diff --git a/sdk/flutter/mentions.mdx b/sdk/flutter/mentions.mdx index d837732e7..2a0ad288e 100644 --- a/sdk/flutter/mentions.mdx +++ b/sdk/flutter/mentions.mdx @@ -1,55 +1,12 @@ --- 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. - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) - +Mentions in messages enable users to refer to specific individuals within a conversation. ## Send Mentioned Messages @@ -110,120 +67,6 @@ 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 @@ -243,13 +86,6 @@ By default, the SDK will fetch all the messages irrespective of the fact that th To get a list of messages in a conversation where users are mentioned along with the 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 @@ -303,106 +139,10 @@ 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 @@ -458,100 +198,12 @@ 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 ``` @@ -560,8 +212,6 @@ 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`. @@ -575,22 +225,3 @@ 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/v5/messaging-overview.mdx b/sdk/flutter/messaging-overview.mdx similarity index 92% rename from sdk/flutter/v5/messaging-overview.mdx rename to sdk/flutter/messaging-overview.mdx index 71c3a8d4b..4d3acd3e9 100644 --- a/sdk/flutter/v5/messaging-overview.mdx +++ b/sdk/flutter/messaging-overview.mdx @@ -5,9 +5,9 @@ sidebarTitle: "Overview" 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/v5/send-message) and [receiving messages](/sdk/flutter/v5/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/v5/typing-indicators) and [delivery & read receipts](/sdk/flutter/v5/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 Structure and Hierarchy @@ -70,7 +70,7 @@ An `InteractiveMessage` encapsulates an interactive unit within a chat message, 3. **scheduler** — scheduler message 4. **customInteractive** — custom interaction messages -See [Interactive Messages](/sdk/flutter/v5/interactive-messages) for more details. +See [Interactive Messages](/sdk/flutter/interactive-messages) for more details. ### Action diff --git a/sdk/flutter/overview.mdx b/sdk/flutter/overview.mdx index 6789301ed..5dcc533ec 100644 --- a/sdk/flutter/overview.mdx +++ b/sdk/flutter/overview.mdx @@ -1,149 +1,94 @@ --- -title: "Flutter SDK" +title: "Chat SDK" sidebarTitle: "Overview" -description: "Add real-time chat, voice, and video to your Flutter application with the CometChat SDK." --- -{/* TL;DR for Agents and Quick Reference */} - +The CometChat Chat SDK for Flutter enables real-time messaging, user management, group conversations, and more in your Flutter application. Built as a pure Dart implementation in v5, it removes the dependency on platform channels and works seamlessly across Android, iOS, Web, and desktop. -```yaml -# Install (pubspec.yaml) -cometchat_sdk: ^4.0.33 -``` - -```dart -import 'package:cometchat_sdk/cometchat_sdk.dart'; - -// 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("APP_ID", appSettings, - onSuccess: (msg) => debugPrint("Init success"), - onError: (e) => debugPrint("Init failed: ${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}"), -); -``` + +**Faster Integration with UI Kits** -**Credentials:** App ID, Region, Auth Key from [CometChat Dashboard](https://app.cometchat.com) -**Test UIDs:** `cometchat-uid-1` through `cometchat-uid-5` - +If you're using CometChat UI Kits, messaging features can be quickly integrated with pre-built components: +- Conversation lists, message composers, and thread views +- Typing indicators, read receipts, and reactions +- Group management and user profiles -The CometChat Flutter SDK lets you add real-time messaging, voice, and video calling to any Flutter application — iOS, Android, Web, or Desktop. +👉 [Flutter UI Kit Overview](/ui-kit/flutter/overview) -## Requirements +Use this Chat SDK directly only if you need custom UI or advanced control. +
-| Requirement | Minimum Version | -|-------------|-----------------| -| Flutter SDK | 1.2 | -| Android API Level | 21 | -| iOS | 11 | + +**Upgrading from v4?** -Requires AndroidX compatibility. For iOS platform setup, see [Setup](/sdk/flutter/setup#ios-setup). +If you're migrating an existing app from CometChat SDK v4, check out the [Upgrading from v4](/sdk/flutter/upgrading-from-v4-guide) guide for breaking changes, deprecated methods, and migration instructions. + -## Getting Started +Before integrating the Chat SDK, ensure you have a [CometChat Account](https://app.cometchat.com/signup) with your App ID, Region, and Auth Key. Flutter SDK `>=1.2` is required, with Android API Level 21+ and iOS 11+. Users must exist in CometChat to send or receive messages — see [Authentication](/sdk/flutter/authentication-overview) for details. - - - [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. - - +```mermaid +sequenceDiagram + participant App + participant CometChat -## Features + App->>CometChat: init(appId, appSettings) + App->>CometChat: login(uid, authKey) + CometChat-->>App: User + App->>CometChat: sendMessage() / addMessageListener() + CometChat-->>App: Real-time events (messages, typing, presence) + App->>CometChat: logout() +``` - - 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 + + Send text, media, and custom messages in 1-on-1 or group conversations + -Explore working examples with full source code: + + Create, join, and manage group conversations with member roles and scopes + - - - Flutter sample app - - + + Listen for messages, typing indicators, read receipts, and presence changes in real time + -## UI Kits + + Show real-time typing status for users and groups + -Skip the UI work — use pre-built, customizable components: + + Track online/offline status of users with configurable subscription modes + - - - Flutter UI Kit - - + + Add and manage emoji reactions on messages + -## Resources + + Organize conversations with message threads + - - - 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 - - + + Track message delivery and read status + -## Next Steps + + Integrate AI-powered agents into your chat experience + + + + Voice and video calling with built-in UI components + - - - 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 - + +| Component | Description | +|-----------|-------------| +| `CometChat` | Main entry point for initialization, authentication, messaging, and real-time events | +| `AppSettings` | Configuration for SDK initialization (App ID, Region, presence subscription) | +| `User` | Represents a CometChat user with UID, name, avatar, and metadata | +| `Group` | Represents a group conversation with GUID, type, and member management | +| `BaseMessage` | Base class for all message types (text, media, custom, action) | +| `MessageListener` | Event interface for real-time message, typing, and receipt events | +| `ConnectionListener` | Event interface for WebSocket connection status changes | diff --git a/sdk/flutter/reactions.mdx b/sdk/flutter/reactions.mdx index 7f0c3e057..86824cf6c 100644 --- a/sdk/flutter/reactions.mdx +++ b/sdk/flutter/reactions.mdx @@ -1,333 +1,79 @@ --- 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 | -```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) - +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. ## Add a Reaction - -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"`). | +Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. ```dart int messageId = 1; -CometChat.addReaction(messageId, "\U0001f634", onSuccess: (message) { +CometChat.addReaction(messageId, "😴", onSuccess: (message) { debugPrint("Success : ${message.getReactions().last}"); }, onError: (e) { debugPrint("Error: ${e.message}"); }); ``` + - -**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."` | - - + +You can react on Text, Media and Custom messages. + ## Remove a Reaction - -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"`). | +Removing a reaction from a message can be done using the `removeReaction` method. ```dart + int messageId = 1; -CometChat.removeReaction(messageId, "\U0001f634", onSuccess: (message) { +CometChat.removeReaction(messageId, "😴", 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 -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. +## 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. - - -```dart -for (ReactionCount reactionCount in message.reactions) { - debugPrint("isReactedByMe ${reactionCount.reactedByMe}"); //Return true is logged-in user reacted on that message, otherwise false -} -``` - - -## Fetch Reactions for a Message +| 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. | -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). -| 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. -### Fetch Next -The `fetchNext()` method fetches the next set of reactions for the message. ```dart int messageId = 1; -ReactionsRequest reactionsRequest = (ReactionsRequestBuilder() - ..limit = 30 - ..messageId = messageId -).build(); +ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messageId = messageId).build(); -reactionsRequest.fetchNext( - onSuccess: (reactions) { - for (Reaction reaction in reactions) { - debugPrint("Success: $reaction"); +reactionRequest.fetchNext( + onSuccess: (messageReactions) { + for (MessageReaction messageReaction in messageReactions) { + debugPrint("Success: ${messageReaction.getReactions()}"); } }, onError: (e) { @@ -335,62 +81,11 @@ reactionsRequest.fetchNext( }, ); ``` + -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 - +## Fetch Previous The `fetchPrevious()` method fetches the previous set of reactions for the message. @@ -398,15 +93,12 @@ The `fetchPrevious()` method fetches the previous set of reactions for the messa ```dart int messageId = 1; -ReactionsRequest reactionsRequest = (ReactionsRequestBuilder() - ..limit = 30 - ..messageId = messageId -).build(); +ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messageId = messageId).build(); -reactionsRequest.fetchPrevious( - onSuccess: (reactions) { - for (Reaction reaction in reactions) { - debugPrint("Success: $reaction"); +reactionRequest.fetchPrevious( + onSuccess: (messageReactions) { + for (MessageReaction messageReaction in messageReactions) { + debugPrint("Success: ${messageReaction.getReactions()}"); } }, onError: (e) { @@ -414,61 +106,13 @@ reactionsRequest.fetchPrevious( }, ); ``` + - -**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` | - - - - +## 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. -| 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. @@ -492,85 +136,78 @@ 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). | -### Remove the Listener +## Removing a Reaction Listener +To stop listening for reaction events, remove the listener as follows: ```dart String listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeMessageListener(listenerID); +CometChat.removeMessageReactionListener(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. - +## 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 +``` -## 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. -| 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` | +## 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`. ```dart -// 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 +for (ReactionCount reactionCount in message.reactions) { + debugPrint("isReactedByMe ${reactionCount.reactedByMe}"); //Return true is logged-in user reacted on that message, otherwise false } ``` + -After calling this method, use `modifiedBaseMessage?.reactions` to get the latest reactions and 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 = ...; -## 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 - - +// 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 +); +``` + + + diff --git a/sdk/flutter/real-time-listeners.mdx b/sdk/flutter/real-time-listeners.mdx index 0ba1a4508..e1685bb8e 100644 --- a/sdk/flutter/real-time-listeners.mdx +++ b/sdk/flutter/real-time-listeners.mdx @@ -1,235 +1,26 @@ --- 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) { - - } -} -``` - - - - - -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. +CometChat provides 4 listeners viz. -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) -``` - - +1. [UserListener](#user-listener) +2. [GroupListener](#group-listener) +3. [MessageListener](#message-listener) ## User Listener The `UserListener` class provides you with live events related to users. Below are the callback methods provided by the `UserListener` class. -### 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. | +| 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. | 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 @@ -270,25 +61,18 @@ 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. -### 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. | +| 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. | 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 @@ -351,244 +135,105 @@ CometChat.removeGroupListener(UNIQUE_LISTENER_ID) -## Call Listener - -The `CallListener` class provides you with real-time events related to calls. Below are the callback methods provided by the `CallListener` class. - -### CallListener Events +## Message Listener -| 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 | +The `MessageListener` class provides you with live events related to messages. Below are the callback methods provided by the `MessageListener` class. -To add the `CallListener`, you need to use the `addCallListener()` method provided by the `CometChat` 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. | -| 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 | +To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. ```dart -class Class_Name with CallListener { - //CometChat.addCallListener("UNIQUE_LISTENER_ID", this); +class Class_Name with MessageListener { - @override - void onIncomingCallReceived(Call call) { + //CometChat.addMessageListener("listenerId", this); + @override + void onTextMessageReceived(TextMessage textMessage) { } @override - void onOutgoingCallAccepted(Call call) { + void onMediaMessageReceived(MediaMessage mediaMessage) { } @override - void onOutgoingCallRejected(Call call) { + void onCustomMessageReceived(CustomMessage customMessage) { } - @override - void onIncomingCallCancelled(Call call) { + @override + void onTypingStarted(TypingIndicator typingIndicator) { } @override - void onCallEndedMessageReceived(Call call) { + void onTypingEnded(TypingIndicator typingIndicator) { } -} -``` - - - - - -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 onConnected() { + void onMessagesDelivered(MessageReceipt messageReceipt) { } @override - void onConnecting() { + void onMessagesRead(MessageReceipt messageReceipt) { } @override - void onDisconnected() { + void onMessageEdited(BaseMessage message) { } @override - void onFeatureThrottled() { + void onMessageDeleted(BaseMessage message) { } @override - 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); + void onInteractionGoalCompleted(InteractionReceipt receipt) { - @override - void loginSuccess(User user) { } @override - void loginFailure(CometChatException e) { + void onInteractiveMessageReceived(InteractiveMessage message) { } - @override - void logoutSuccess() { - - } - @override - void logoutFailure(CometChatException e) { + @Override + public void onTransientMessageReceived(TransientMessage transientMessage) { } -} -``` - - - - - -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 | + @Override + public void onMessageReactionAdded(ReactionEvent reactionEvent) { - - -```dart -class Class_Name with AIAssistantListener { - //CometChat.addAIAssistantListener("UNIQUE_LISTENER_ID", this); + } - @override - void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { + @Override + public void onMessageReactionRemoved(ReactionEvent reactionEvent) { } @@ -601,39 +246,4 @@ class Class_Name with AIAssistantListener { 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 `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 - - +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. diff --git a/sdk/flutter/receive-messages.mdx b/sdk/flutter/receive-messages.mdx index f4f376439..92246df7f 100644 --- a/sdk/flutter/receive-messages.mdx +++ b/sdk/flutter/receive-messages.mdx @@ -1,29 +1,14 @@ --- 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?* @@ -70,39 +55,8 @@ 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 @@ -165,94 +119,6 @@ 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 @@ -285,94 +151,6 @@ 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?* @@ -412,94 +190,6 @@ 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 @@ -533,98 +223,10 @@ 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`](/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. +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. @@ -665,94 +267,6 @@ 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 @@ -787,94 +301,6 @@ 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 @@ -930,94 +356,6 @@ 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 @@ -1050,94 +388,6 @@ 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?* @@ -1389,22 +639,3 @@ 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/v5/resources-overview.mdx b/sdk/flutter/resources-overview.mdx similarity index 100% rename from sdk/flutter/v5/resources-overview.mdx rename to sdk/flutter/resources-overview.mdx diff --git a/sdk/flutter/retrieve-conversations.mdx b/sdk/flutter/retrieve-conversations.mdx index cb43d8cc9..690d1d42b 100644 --- a/sdk/flutter/retrieve-conversations.mdx +++ b/sdk/flutter/retrieve-conversations.mdx @@ -1,82 +1,20 @@ --- 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. -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`. | +The `ConversationsRequestBuilder` class allows you to set the below parameters: ### Set Limit -Set the number of conversations to fetch per request. +This method sets the limit i.e. the number of conversations that should be fetched in a single iteration. @@ -85,16 +23,19 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..limit = 50 ).build(); ``` + - - -The default value for `limit` is 30 and the max value is 50. - + ### Set Conversation Type -Filter by conversation type: `user` for one-on-one or `group` for group conversations. If not set, both types are returned. +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. @@ -104,14 +45,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 -Use `withUserAndGroupTags = true` to include user/group tags in the `Conversation` object. Default is `false`. +This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is false. @@ -121,48 +62,14 @@ 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 -Use `withTags = true` to include conversation tags in the response. Default is `false`. +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` @@ -172,12 +79,14 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..withTags = true ).build(); ``` + + ### Set Tags -Fetch conversations that have specific tags. +This method helps you fetch the conversations based on the specified tags. @@ -189,12 +98,14 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..tags = tags ).build(); ``` + + ### Include Blocked Users -Use `includeBlockedUsers = true` to include conversations with users you've blocked. +This method helps you fetch the conversations of users whom the logged-in user has blocked. @@ -204,14 +115,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 -Use `withBlockedInfo = true` to include blocked user information in the response. +This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. @@ -221,12 +132,14 @@ ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..withBlockedInfo = true ).build(); ``` + + ### Search Conversations -Use `searchKeyword` to search conversations by user or group name. +This method helps you search a conversation based on User or Group name. @@ -242,14 +155,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 -Use `unread = true` to fetch only conversations with unread messages. +This method helps you fetch unread conversations. @@ -265,228 +178,108 @@ 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 +### Filter by User Tags -Use `hideAgentic = true` to exclude AI agent conversations from the list. +This method helps you filter conversations based on specific user tags. ```dart +List userTags = ["premium", "verified"]; ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..limit = 50 - ..hideAgentic = true + ..userTags = userTags ).build(); ``` + + -### Only Agentic Conversations +### Filter by Group Tags -Use `onlyAgentic = true` to fetch only AI agent conversations. +This method helps you filter conversations based on specific group tags. ```dart +List groupTags = ["support", "sales"]; ConversationsRequest conversationRequest = (ConversationsRequestBuilder() ..limit = 50 - ..onlyAgentic = true + ..groupTags = groupTags ).build(); ``` - - - -`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. + -### Fetch Conversations +### Hide Agentic 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. +This method helps you hide AI-driven (agentic) conversations from the list. Agentic conversations are those involving AI agents. ```dart ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ).build(); - -conversationRequest.fetchNext( - onSuccess: (List conversations){ - - - }, onError: (CometChatException e){ - - }); + ..limit = 50 + ..hideAgentic = true +).build(); ``` - - - - -**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` | +### Only Agentic Conversations ---- +This method helps you fetch only AI-driven (agentic) conversations. This is useful when you want to display a separate list of AI agent conversations. - - -**`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` | + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..onlyAgentic = true +).build(); +``` ---- + - - -**`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` | + ---- +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. - - -**`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` | +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. ---- +A Maximum of only 50 Conversations can be fetched at once. - + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ).build(); -**`lastMessage.receiver` Object:** +conversationRequest.fetchNext( + onSuccess: (List conversations){ -| 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` | - + }, onError: (CometChatException e){ - + } +``` -| 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: +The `Conversation`object consists of the below fields: | Field | Information | | --------------------- | -------------------------------------------------------------------- | @@ -496,19 +289,22 @@ The `Conversation` object consists of the below fields: | `conversationWith` | `User` or `Group` object containing the details of the user or group | | `unreadMessageCount` | Unread message count for the conversation | | `unreadMentionsCount` | the count of unread mentions in the conversation. | -| `lastReadMessageId` | the ID of the last read message in the conversation. | +| `lastReadMessageId` | the ID of the last read message in the conversation (int type). | ## Tag Conversation *In other words, as a logged-in user, how do I tag a conversation?* -Use `tagConversation()` to add tags to 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. -| Parameter | Description | -| --- | --- | -| `conversationWith` | UID or GUID of the user/group | -| `conversationType` | `user` or `group` | -| `tags` | Array of tags to add | +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. @@ -526,141 +322,10 @@ 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."` | + - + @@ -672,12 +337,13 @@ 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?* -Use `getConversation()` to fetch a specific conversation. +In order to fetch a specific conversation, you can use the `getConversation` method. The `getConversation` method accepts two parameters. -| Parameter | Description | -| --- | --- | -| `conversationWith` | UID or GUID of the user/group | -| `conversationType` | `user` or `group` | +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. @@ -692,141 +358,10 @@ 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 @@ -837,28 +372,13 @@ 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 1eaa8a1ba..517799414 100644 --- a/sdk/flutter/retrieve-group-members.mdx +++ b/sdk/flutter/retrieve-group-members.mdx @@ -1,65 +1,17 @@ --- 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. - - -**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) - +In order to fetch the list of groups members for a group, you can use the `GroupMembersRequest` class. To use this class i.e to create an object of the `GroupMembersRequest` class, you need to use the `GroupMembersRequestBuilder` class. The `GroupMembersRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. -To 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. -### 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. @@ -116,22 +68,9 @@ 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. +This method allows you to filter group members based on their online/offline status. @@ -139,14 +78,20 @@ If not set, returns all members regardless of status. String GUID = "GUID"; GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) ..limit = 20 - ..status = "online" -).build(); + ..status = CometChatUserStatus.online // or CometChatUserStatus.offline + ).build(); ``` +The `status` parameter can contain one of the below two values: +* `CometChatUserStatus.online` - will return only online group members. +* `CometChatUserStatus.offline` - will return only offline group members. + +If this parameter is not set, all group members will be returned regardless of their status. + 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. @@ -169,54 +114,3 @@ 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 d5182cea2..23417e0b0 100644 --- a/sdk/flutter/retrieve-groups.mdx +++ b/sdk/flutter/retrieve-groups.mdx @@ -1,53 +1,8 @@ --- 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 @@ -55,22 +10,9 @@ Retrieve groups allows you to fetch the list of groups you've joined and 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 -Sets the number of groups to fetch per request. +This method sets the limit i.e. the number of groups that should be fetched in a single iteration. @@ -86,7 +28,7 @@ GroupsRequest groupsRequest = (GroupsRequestBuilder() ### Set Search Keyword -Filters groups by a search string. +This method allows you to set the search string based on which the groups are to be fetched. @@ -103,7 +45,7 @@ GroupsRequest groupsRequest = (GroupsRequestBuilder() ### Joined Only -When `true`, returns only groups the logged-in user has joined or is a part of. +This method when used, will ask CometChat to only return the groups that the user has joined or is a part of. @@ -120,7 +62,7 @@ GroupsRequest groupsRequest = (GroupsRequestBuilder() ### Set Tags -Filters groups by specified tags. The list fetched will only contain the groups that have been tagged with the specified 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. @@ -139,7 +81,7 @@ GroupsRequest groupsRequest = (GroupsRequestBuilder() ### With Tags -When `true`, includes tag data in the returned group objects. +This property when set to true will fetch tags data along with the list of groups. @@ -156,7 +98,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`](/sdk/reference/entities#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` 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. @@ -178,44 +120,6 @@ 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?* @@ -242,45 +146,7 @@ CometChat.getGroup(GUID, onSuccess: (Group group) { | --------- | ------------------------------------------------------------ | | `GUID` | The GUID of the group for whom the details are to be fetched | -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."` | - - +On success, the `Group` object containing the details of the group is returned. ## Get online group member count @@ -306,41 +172,3 @@ 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 1331d8932..9284b158f 100644 --- a/sdk/flutter/retrieve-users.mdx +++ b/sdk/flutter/retrieve-users.mdx @@ -1,96 +1,34 @@ --- 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 -Use `getLoggedInUser()` to get the current user's details. Returns `null` if no user is logged in. +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. ```dart -User? user = await CometChat.getLoggedInUser(); +User user = await CometChat.getLoggedInUser() ``` + + -This method returns a [`User`](/sdk/reference/entities#user) object with the logged-in user's information. +This method will return a `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. - -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. | +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: ### Set Limit -Sets the number of users to fetch per request. +This method sets the limit i.e. the number of users that should be fetched in a single iteration. @@ -99,12 +37,14 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..limit = 50 ).build(); ``` + + ### Set Search Keyword -Filters users by a search string. +This method allows you to set the search string based on which the users are to be fetched. @@ -114,33 +54,19 @@ 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 -Filters users by online status: +The status based on which the users are to be fetched. The status parameter can contain one of the below two values: -- `CometChatUserStatus.online` — Only online users -- `CometChatUserStatus.offline` — Only offline users +* CometChatUserStatus.online - will return the list of only online users. +* CometChatUserStatus.offline - will return the list of only offline users. -If not set, returns all users. +If this parameter is not set, will return all the available users. @@ -150,12 +76,16 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..userStatus = CometChatUserStatus.online ).build(); ``` + + +If this parameter is not set, will return all users. + ### Hide Blocked Users -When `true`, excludes users blocked by the logged-in user from the results. +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. @@ -165,12 +95,14 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..hideBlockedUsers = true ).build(); ``` + + ### Set Roles -Filters users by specified roles. +This method allows you to fetch the users based on multiple roles. @@ -183,12 +115,14 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..roles = roles ).build(); ``` + + ### Friends Only -When `true`, returns only friends of the logged-in user. +This property when set to true will return only the friends of the logged-in user. @@ -198,12 +132,14 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..friendsOnly = true ).build(); ``` + + ### Set Tags -Filters users by specified 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. @@ -216,27 +152,34 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..tags = tags ).build(); ``` + + ### With Tags -When `true`, includes tag data in the returned user objects. +This property when set to true will fetch tags data along with the list of users. ```dart +List tags = []; +tags.add("tag1"); +tags.add("tag2"); UsersRequest usersRequest = (UsersRequestBuilder() ..limit = 50 ..withTags = true ).build(); ``` + + ### Set UIDs -Fetches specific users by their UIDs. Maximum 25 users per request. +This method accepts a list of UIDs based on which the list of users is fetched. A maximum of 25 users can be fetched. @@ -249,40 +192,85 @@ UsersRequest usersRequest = (UsersRequestBuilder() ..uids = uids ).build(); ``` + + + + + +### Search In + +This method allows you to specify which user fields to search in when using the search keyword. You can search in `name`, `uid`, or both. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..searchKeyword = "john" + ..searchIn = ["name", "uid"] + ).build(); +``` + + ### Sort By -Sorts the user list by a specific property. Default sort order: `status → name → UID`. Pass `"name"` to sort by `name → UID`. +This method allows you to specify the field by which the users should be sorted. You can sort by `name`, `status`, or `createdAt`. ```dart UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 30 + ..limit = 50 ..sortBy = "name" ).build(); ``` + + ### Sort By Order -Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. +This method allows you to specify the order in which the users should be sorted. You can use `asc` for ascending or `desc` for descending order. ```dart UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 30 - ..sortByOrder = "desc" + ..limit = 50 + ..sortBy = "name" + ..sortByOrder = "asc" ).build(); ``` + + -After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. +You can combine these parameters for more precise user filtering and ordering: + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..searchKeyword = "john" + ..searchIn = ["name"] + ..sortBy = "name" + ..sortByOrder = "asc" + ).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 depending on the limit set. @@ -297,48 +285,14 @@ 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 -Use `getUser()` to fetch a specific user's details by UID. +To get the information of a user, you can use the `getUser()` method. @@ -351,7 +305,9 @@ CometChat.getUser(UID, onSuccess: (User user){ debugPrint("User Fetch Failed: ${e.message}"); }); ``` + + The `getUser()` method takes the following parameters: @@ -362,43 +318,9 @@ The `getUser()` method takes the following parameters: On success, the `User` object containing the details of the user is returned. - -**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` | - - - - - -| 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 - - -## Get Online User Count - -Use `getOnlineUserCount()` to get the total number of online users in your app. +To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. @@ -409,45 +331,7 @@ 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 57cc58dfa..fd2c833d9 100644 --- a/sdk/flutter/send-message.mdx +++ b/sdk/flutter/send-message.mdx @@ -1,72 +1,15 @@ --- -title: "Send Messages" -sidebarTitle: "Send Messages" -description: "Send text, media, and custom messages to users and groups using the CometChat Flutter SDK." +title: "Send A Message" --- - -| 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 | -```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) {}); +Using CometChat, you can send three types of messages: -// 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 | - -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) - +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 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. @@ -74,7 +17,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`](/sdk/reference/messages#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` object to it. ### Add Metadata @@ -167,99 +110,6 @@ 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. @@ -281,52 +131,42 @@ 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; -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}"); - }, -); + 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}"); + }, + ); ``` ```dart String receiverID = "GUID"; -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}"); - }, -); + 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}"); + }, + ); ``` @@ -339,108 +179,15 @@ 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- `CometChatReceiverType.user` (user) or `CometChatReceiverType.group` (group) | Required | +| `receiverType` | The type of the receiver- `CometChatConstants.RECEIVER_TYPE_USER` (user) or `CometChatConstants.RECEIVER_TYPE_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`](/sdk/reference/messages#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` object to it. ### Add Metadata @@ -487,65 +234,26 @@ 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 = "cometchat-uid-1"; -String messageType = CometChatMessageType.image; -String receiverType = CometChatConversationType.user; -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}"); - } -); -``` - - - - + ```dart -String receiverID = "cometchat-guid-1"; +String receiverID; String messageType = CometChatMessageType.image; -String receiverType = CometChatConversationType.group; +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}"); } @@ -565,126 +273,11 @@ 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 | - -**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: +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: - + ```dart -String receiverID = "cometchat-uid-1"; -String messageType = CometChatMessageType.image; -String receiverType = CometChatConversationType.user; - MediaMessage mediaMessage = MediaMessage( receiverType: receiverType, type: messageType, @@ -696,12 +289,12 @@ 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}"); } @@ -710,153 +303,90 @@ 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. + +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`. + +### Send Multiple Media Files + +You can send multiple media files (images, videos, audio, or documents) in a single message. This enables richer and more efficient conversations. + + + ```dart -String receiverID = "cometchat-guid-1"; +String receiverID = "cometchat-uid-1"; +String receiverType = CometChatConversationType.user; 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"; +// Create a list of file paths +List filePaths = [ + "storage/emulated/0/Download/image1.jpg", + "storage/emulated/0/Download/image2.jpg", + "storage/emulated/0/Download/image3.jpg", +]; -Attachment attach = Attachment(fileUrl, fileName, fileExtension, fileMimeType, null); -mediaMessage.attachment = attach; +MediaMessage mediaMessage = MediaMessage( + receiverType: receiverType, + type: messageType, + receiverUid: receiverID, + files: filePaths, // Use 'files' for multiple files +); -await CometChat.sendMediaMessage(mediaMessage, +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}"); + debugPrint("Multiple media files sent successfully"); + // Access the list of attachments + List? attachments = message.attachments; + for (var attachment in attachments ?? []) { + debugPrint("Attachment URL: ${attachment.fileUrl}"); + } + }, + onError: (CometChatException e) { + debugPrint("Media message sending failed: ${e.message}"); } -); +); ``` -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` | - ---- - - +### File Size and Count Validation -**`attachment` Object:** +The SDK automatically validates file size and count when sending media messages. You can configure these limits through Settings in the CometChat Dashboard. -| 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` | +| Validation | Description | +|------------|-------------| +| File Size | Maximum size per file (configurable in Dashboard) | +| File Count | Maximum number of files per message (configurable in Dashboard) | - +If validation fails, the `onError` callback will be triggered with details about the validation error. - - -| 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."` | + + +```dart +await CometChat.sendMediaMessage(mediaMessage, + onSuccess: (MediaMessage message) { + debugPrint("Media message sent successfully"); + }, + onError: (CometChatException e) { + // Handle validation errors + if (e.code == "ERR_FILE_SIZE_EXCEEDED") { + debugPrint("File size exceeds the allowed limit"); + } else if (e.code == "ERR_FILE_COUNT_EXCEEDED") { + debugPrint("Too many files in a single message"); + } else { + debugPrint("Error: ${e.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 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 @@ -866,7 +396,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`](/sdk/reference/messages#custommessage) which can be obtained using the below constructor. +The `sendCustomMessage()` methods takes an object of the `CustomMessage` which can be obtained using the below constructor. @@ -885,35 +415,15 @@ 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 `CustomMessage` class constructor takes the following parameters: +The parameters involved are: -| 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 | +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`. 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. @@ -930,20 +440,6 @@ 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. @@ -1009,101 +505,6 @@ 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?* @@ -1243,22 +644,3 @@ 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/setup.mdx b/sdk/flutter/setup.mdx index 877c9e0e6..14e1fa426 100644 --- a/sdk/flutter/setup.mdx +++ b/sdk/flutter/setup.mdx @@ -1,75 +1,50 @@ --- title: "Setup" -sidebarTitle: "Setup" -description: "Install, configure, and initialize the CometChat Flutter SDK in your application." --- -{/* 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) - +### Add the CometChat Dependency -## Prerequisites +### Cloudsmith -| Requirement | Version | -|-------------|---------| -| Flutter SDK | 1.2 or higher | -| Android API Level | 21 or higher | -| AndroidX | Required | -| iOS | 11 or higher | +Add the Cloudsmith hosted repository and dependency to your `pubspec.yaml`: -Get your credentials from the [CometChat Dashboard](https://app.cometchat.com): +```yaml +dependencies: + cometchat_sdk: + hosted: + url: https://dart.cloudsmith.io/cometchat/cometchat/ + version: 5.0.0 +``` -1. Create a new app -2. Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** +Then run: +```bash +flutter pub get +``` -**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. - - -## Installation +**Upgrading from v4?** -Add the following dependency to your `pubspec.yaml` file and run `pub get`: - - - -```yaml -cometchat_sdk: ^4.0.33 -``` - - - -### iOS Setup +If you're migrating an existing app from CometChat SDK v4, check out the [Upgrading from v4](/sdk/flutter/upgrading-from-v4-guide) guide for breaking changes, deprecated methods, and migration instructions. + -1. Add the following to your Podfile inside the iOS section of your app: +2. Add following code to podfile inside iOS section of your app @@ -94,40 +69,54 @@ end end ``` + + **Apple Silicon (M1/M2/M3) users:** Excluding `arm64` from the simulator build prevents the app from running natively on Apple Silicon Macs. If you are developing on an Apple Silicon Mac, consider excluding only `i386` instead of `arm64 i386` to enable native simulator builds. -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. +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 -### Import the SDK - +Import CometChat SDK using following code in dart ```dart import 'package:cometchat_sdk/cometchat_sdk.dart'; ``` + + -## Initialization +## Initialise 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. +The `init()` method initialises the settings required for CometChat. The `init()` method takes the below parameters: + +1. appID - You CometChat App ID +2. appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the `setRegion()` method. + +The `AppSettings` class allows you to configure 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. ```dart -String region = "APP_REGION"; +String region = "REGION"; String appId = "APP_ID"; AppSettings appSettings= (AppSettingsBuilder() @@ -146,101 +135,35 @@ CometChat.init(appId, appSettings, } ); ``` - - - -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: +We suggest you call the `init()` method on app startup. -| Parameter | Type | Description | Sample Value | -|-----------|------|-------------|--------------| -| `message` | `String` | Success confirmation message | `"Initialization completed successfully"` | - +## Auto Mode Connection - + -| 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."` | - +Know more about auto mode connection [click here](/sdk/flutter/connection-behaviour) -### WebSocket Connection +
-By default, the SDK manages WebSocket connections automatically. To manage them manually: +| App State | Behaviour | +| ----------------- | --------------------------------------- | +| App in foreground | Connected with WebSocket | +| App in background | Immediately disconnected with WebSocket | -```dart -AppSettings appSettings = (AppSettingsBuilder() - ..region = region - ..autoEstablishSocketConnection = false -).build(); -``` +## Manual Mode Connection -See [Connection Behaviour](/sdk/flutter/connection-behaviour) for manual control. + ---- +Know more about manual mode connection [click here](/sdk/flutter/connection-behaviour) -## Next Steps + - - - Log in users with Auth Key or Auth Token - - - Send your first message - - +| 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. | diff --git a/sdk/flutter/threaded-messages.mdx b/sdk/flutter/threaded-messages.mdx index d2b1e40f9..330506158 100644 --- a/sdk/flutter/threaded-messages.mdx +++ b/sdk/flutter/threaded-messages.mdx @@ -1,51 +1,11 @@ --- 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 | -```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) - +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 @@ -55,14 +15,17 @@ A message can be categorized as: 1. Text Message 2. Media Message -3. Custom Message +3. Custom Message. 4. Interactive Message -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. +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. +**Example to Send a Text Message in a thread in a user conversation.** - + ```dart String receiverID = "UID"; String messagesText = "Hello"; @@ -74,159 +37,27 @@ TextMessage textMessage = TextMessage( receiverUid: receiverID, receiverType: receiverType, type: type); -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; +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) 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"); -``` - +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. @@ -263,17 +94,14 @@ void onCustomMessageReceived(CustomMessage customMessage) { ### Fetch all the messages for any particular thread. -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. +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: -`MessagesRequestBuilder` Parameters: +1. parentMessageId: Takes the parentId of the message as argument whose thread needs to be requested. +2. build(): returns the MessageRequest 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 | +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. @@ -295,100 +123,12 @@ 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. Use `hideReplies = true` on the `MessagesRequestBuilder` to exclude threaded messages from the list. +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. - + ```dart String UID = "cometchat-uid-1"; @@ -404,133 +144,7 @@ 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}"); - }); -``` - - - -**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 - - +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 diff --git a/sdk/flutter/transfer-group-ownership.mdx b/sdk/flutter/transfer-group-ownership.mdx index d5c67b622..5c2b8b668 100644 --- a/sdk/flutter/transfer-group-ownership.mdx +++ b/sdk/flutter/transfer-group-ownership.mdx @@ -1,33 +1,14 @@ --- 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. - -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 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 +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. -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) - +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. @@ -46,50 +27,3 @@ 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 9b7654664..4d2676079 100644 --- a/sdk/flutter/transient-messages.mdx +++ b/sdk/flutter/transient-messages.mdx @@ -1,90 +1,30 @@ --- 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." +description: "Send and receive ephemeral real-time messages with the CometChat Flutter SDK 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`](/sdk/reference/auxiliary#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` 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}"); -}); -``` - - - - -```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}"); +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}"); }); ``` @@ -92,37 +32,10 @@ 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. @@ -144,24 +57,11 @@ void onTransientMessageReceived(TransientMessage message) { -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 +The `TransientMessage` class consists of the below parameters: - - - Learn how to send persistent text and media messages - - - Show real-time typing status to users - - +| 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. | diff --git a/sdk/flutter/typing-indicators.mdx b/sdk/flutter/typing-indicators.mdx index 19640d53d..c3787c105 100644 --- a/sdk/flutter/typing-indicators.mdx +++ b/sdk/flutter/typing-indicators.mdx @@ -1,43 +1,8 @@ --- 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 @@ -45,93 +10,68 @@ Typing indicators let users know when someone is actively typing a message, crea ### Start Typing -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. +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. - + ```dart CometChat.startTyping( - receiverUid: "UID", - receiverType: CometChatReceiverType.user, -); + receiverUid: "UID", + receiverType: CometChatReceiverType.user, + ); ``` - + ```dart CometChat.startTyping( - receiverUid: "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 -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. +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. - + ```dart CometChat.endTyping( - receiverUid: "UID", - receiverType: CometChatReceiverType.user, -); + receiverUid: "UID", + receiverType: CometChatReceiverType.user); ``` - + ```dart CometChat.endTyping( - receiverUid: "GUID", - receiverType: CometChatReceiverType.group, -); + receiverUid: "GUID", + receiverType: CometChatReceiverType.group); ``` -`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 | + +Custom Data -`endTyping()` returns `void` — the typing indicator is sent as a fire-and-forget operation. +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. - -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?* -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"); -``` - +You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the registered `MessageListener` class. @@ -157,25 +97,11 @@ void onTypingEnded(TypingIndicator typingIndicator) { -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 +The `TypingIndicator` class consists of the below parameters: - - - Track message delivery and read status - - - Send ephemeral real-time messages like live reactions - - +| 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 | diff --git a/sdk/flutter/update-group.mdx b/sdk/flutter/update-group.mdx index 8371e41af..c9353f983 100644 --- a/sdk/flutter/update-group.mdx +++ b/sdk/flutter/update-group.mdx @@ -1,44 +1,14 @@ --- 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. 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 | +You can update the existing details of the group using the `updateGroup()` method. @@ -62,67 +32,12 @@ String GUID = "GUID"; - -**On Success** — A `Group` object containing all details of the updated group: - - - -**Group Object:** +This method takes an instance of the `Group` class as a parameter which should contain the data that you wish to update. -| 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."` | - - +| Parameter | Description | +| --------- | ---------------------------- | +| `group` | an instance of class `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). - - -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 - - +For more information on the `Group` class, please check [here](/sdk/flutter/create-group#group-class) diff --git a/sdk/flutter/v5/upgrading-from-v4-guide.mdx b/sdk/flutter/upgrading-from-v4-guide.mdx similarity index 94% rename from sdk/flutter/v5/upgrading-from-v4-guide.mdx rename to sdk/flutter/upgrading-from-v4-guide.mdx index 5347d2bd4..04728b860 100644 --- a/sdk/flutter/v5/upgrading-from-v4-guide.mdx +++ b/sdk/flutter/upgrading-from-v4-guide.mdx @@ -6,16 +6,16 @@ This guide helps you migrate your Flutter application from CometChat SDK v4 to v ## Installation -### Cloudsmith (Current Beta) +### Cloudsmith -For the current beta release, add the Cloudsmith hosted repository and dependency to your `pubspec.yaml`: +Add the Cloudsmith hosted repository and dependency to your `pubspec.yaml`: ```yaml dependencies: cometchat_sdk: hosted: url: https://dart.cloudsmith.io/cometchat/cometchat/ - version: 5.0.0-beta.1 + version: 5.0.0 ``` Then run: diff --git a/sdk/flutter/user-management.mdx b/sdk/flutter/user-management.mdx index 95622f92c..b58d3da36 100644 --- a/sdk/flutter/user-management.mdx +++ b/sdk/flutter/user-management.mdx @@ -1,251 +1,88 @@ --- 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}"); -}); -``` -**Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). - +When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. -Users must exist in CometChat before they can log in. This page covers creating, updating, and deleting users. All methods that return user data return a [`User`](/sdk/reference/entities#user) object. +Summing up- -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) +**When a user registers in 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 add the user details in your database +2. You create a user in CometChat -## Creating a User +**When a user logs into your app** -User creation should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). +1. You log in the user to your app +2. You [log in the user to CometChat](https://app.cometchat.com/login) - -**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. - +## 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. -For client-side creation (development only), use `createUser()`: +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/flutter/user-management#user-class) ```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 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."` | - +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 - - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - +CometChat.createUser(user, authKey, onSuccess: (User user){ + debugPrint("Create User succesful ${user}"); -## Updating a User + }, onError: (CometChatException e){ + debugPrint("Create User Failed with exception ${e.message}"); -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. +UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - -**On Success** — A `User` object containing all details of the updated user: + -| 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 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. -| 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."` | - +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 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. +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. ```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 -User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-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 Class @@ -263,20 +100,3 @@ User deletion is only available via the [REST API](https://api-explorer.cometcha | 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 c1f0fecea..a9721a3d9 100644 --- a/sdk/flutter/user-presence.mdx +++ b/sdk/flutter/user-presence.mdx @@ -1,62 +1,30 @@ --- 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"); -``` - -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) - +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?* -Configure presence subscription in `AppSettings` during SDK initialization. The `AppSettingsBuilder` provides three subscription options: +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. -| 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 | +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(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. - -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. - +If none of the above methods are set, no presence will be sent to the logged-in user. -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. +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. @@ -85,23 +53,9 @@ void onUserOffline(User user) { | ------------ | ----------------------------------------------------------------------------------------------- | | `listenerID` | An ID that uniquely identifies that listener. We recommend using the activity or fragment name. | -### 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. +You will receive an object of the `User` class in the listener methods. -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: +We recommend you remove the listener once the listener is not in use. @@ -115,15 +69,11 @@ 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) object, you will receive 2 keys: +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: 1. `status` - This will hold either of the two values : @@ -131,22 +81,3 @@ 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 32e83bbb2..868ac1bf1 100644 --- a/sdk/flutter/users-overview.mdx +++ b/sdk/flutter/users-overview.mdx @@ -1,37 +1,35 @@ --- title: "Users" sidebarTitle: "Overview" -description: "Overview of CometChat user functionality including user management, retrieval, and presence tracking in the Flutter SDK." --- - +A user is anyone who uses CometChat. The primary aim for the users functionality is to allow you to quickly retrieve and add users to CometChat. -- [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 - +## UID -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. +- Each user is uniquely identified using a UID. +- The UID is typically the primary ID of the user from your database. -- [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 + +UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. + + +## Auth Token + +- A single user can have multiple auth tokens. Auth tokens should be per user per device. +- It should 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. + +## 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. ## 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. - - +- [User Management](/sdk/flutter/user-management) — sync your users to CometChat +- [Retrieve Users](/sdk/flutter/retrieve-users) — fetch and display users in your app diff --git a/sdk/flutter/v4/additional-message-filtering.mdx b/sdk/flutter/v4/additional-message-filtering.mdx new file mode 100644 index 000000000..35f03b472 --- /dev/null +++ b/sdk/flutter/v4/additional-message-filtering.mdx @@ -0,0 +1,660 @@ +--- +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 +``` + +**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 `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`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..limit = 30).build(); +``` + + + + + +## Messages for a user conversation + +*In other words, how do I fetch messages between me and any user* + +Use the `uid` property to fetch messages between the logged-in user and a specific user. + + + +```dart +String UID = "cometchat-uid-1"; +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..limit = 50).build(); +``` + + + + + +## Messages for a group conversation + +*In other words, how do I fetch messages for any group conversation* + +Use the `guid` property to fetch messages from a group. The logged-in user must be a member of the group. + + + +```dart +String GUID = "cometchat-uid-1"; +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..limit = 50).build(); +``` + + + + + + +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* + +Use the `messageId` property. This provides messages only after/before the message-id based on if `fetchNext()` or `fetchPrevious()` is called. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..messageId = 50 + ..limit = 50).build(); +``` + + + + + +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* + +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. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..timestamp = DateTime.now() + ..limit = 50).build(); +``` + + + + + +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* + +Use the `unread` property set to `true` to return just the unread messages. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..unread = true + ..limit = 50).build(); +``` + + + + + +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* + +Use the `hideMessagesFromBlockedUsers` property. If set to `true`, messages from users blocked by the logged-in user will be excluded. Default is `false`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hideMessagesFromBlockedUsers = true + ..limit = 50).build(); +``` + + + + + +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* + +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. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..updatedAfter = DateTime.now() + ..limit = 50).build(); +``` + + + + + +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* + +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`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..updatedAfter = DateTime.now() + ..updatesOnly = true + ..limit = 50).build(); +``` + + + + + +## 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/flutter/message-structure-and-hierarchy) to get familiar with the various categories of messages. + +Use the `categories` property with a list of category names to filter by message category. + + + +```dart +String UID = "cometchat-uid-1"; +List categories = []; +categories.add("message"); +categories.add("custom"); + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..categories = categories + ..limit = 50).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 `uid` and `guid` 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 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. + +Use the `types` property with a list of type names to filter by message type. + + + +```dart +String UID = "cometchat-uid-1"; +List types = []; +types.add("image"); +types.add("video"); + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..types = types + ..limit = 50).build(); +``` + + + + + +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* + +Use the `parentMessageId` property when you have implemented threaded conversations. This will return only messages belonging to the thread with the specified parent ID. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..parentMessageId = 103 + ..limit = 50).build(); +``` + + + + + +The above code snippet returns the messages that belong to the thread with parent id 103. + +## Hide threaded messages in user/group conversations + +*In other words, how do I exclude threaded messages from the normal user/group conversations* + +Use the `hideReplies` property set to `true` to exclude messages that belong to threads. Default is `false`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hideReplies = true + ..limit = 50).build(); +``` + + + + + +## Hide deleted messages in user/group conversations + +*In other words, how do I exclude deleted messages a user/group conversations* + +Use the `hideDeleted` property set to `true` to exclude deleted messages. Default is `false`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hideDeleted = true + ..limit = 50).build(); +``` + + + + + +## 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* + +Use the `tags` property with a list of tag names to fetch only messages with those tags. + + + +```dart +String UID = "cometchat-uid-1"; +List tags = []; +tags.add("tag1"); +tags.add("tag2"); + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..tags = tags + ..limit = 50).build(); +``` + + + + + +## Messages with tags + +*In other words, how do I fetch messages with the tags information* + +Use the `withTags` property set to `true` to include tag information in the response. Default is `false`. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..withTags = true + ..limit = 50).build(); +``` + + + + + +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 contain links?* + +Use the `hasLinks` property set to `true` to fetch only messages containing links. 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) + + + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hasLinks = true + ..limit = 50).build(); +``` + + + + + +## Messages with attachments + +*In other words, as a logged-in user, how do I fetch messages that contain attachments?* + +Use the `hasAttachments` property set to `true` to fetch only messages with attachments (image, audio, video, or file). 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) + + + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hasAttachments = true + ..limit = 50).build(); +``` + + + + + +## Messages with reactions + +*In other words, as a logged-in user, how do I fetch messages that contain reactions?* + +Use the `hasReactions` property set to `true` to fetch only messages with 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) + + + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hasReactions = true + ..limit = 50).build(); +``` + + + + + +## Messages with mentions + +*In other words, as a logged-in user, how do I fetch messages that contain mentions?* + +Use the `hasMentions` property set to `true` to fetch only messages with mentions. 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) + + + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..hasMentions = true + ..limit = 50).build(); +``` + + + + + +## Messages with particular user mentions + +*In other words, as a logged-in user, how do I fetch messages that mention specific users?* + +Use the `mentionedUids` property with a list 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) + + + + + +```dart +String UID = "cometchat-uid-1"; +List mentionedUIDs = []; +mentionedUIDs.add("cometchat-uid-1"); +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..mentionedUids = mentionedUIDs + ..limit = 50).build(); +``` + + + + + +## 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/v4/ai-agents.mdx b/sdk/flutter/v4/ai-agents.mdx new file mode 100644 index 000000000..173304cf6 --- /dev/null +++ b/sdk/flutter/v4/ai-agents.mdx @@ -0,0 +1,216 @@ +--- +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." +--- + + + +| 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 + +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 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 | + + + + ```dart +import 'package:flutter/foundation.dart'; +import 'package:cometchat_sdk/cometchat_sdk.dart'; + +class AIAssistantEventHandler with AIAssistantListener { + final String _sdkStreamListenerId = "unique_listener_id"; + + /// Call this to start listening to AI Assistant events + void addListener() { + CometChat.addAIAssistantListener(_sdkStreamListenerId, this); + debugPrint("AIAssistantListener added successfully."); + } + + /// Call this to remove the AI Assistant listener + void removeListener() { + CometChat.removeAIAssistantListener(_sdkStreamListenerId); + debugPrint("AIAssistantListener removed successfully."); + } + + @override + void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { + debugPrint( + "Received AI Event: ${aiAssistantBaseEvent.type} for Run ID: ${aiAssistantBaseEvent.id}", + ); + } +} + ``` + + + + +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. +- 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 + +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 | + + + + ```dart + const listenerId = "unique_listener_id"; + + class Class_Name with MessageListener { + // Adding the MessageListener + // CometChat.addMessageListener(listenerId, this); + @override + void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { + debugPrint("AI Assistant Message Received: ${aiAssistantMessage.toString()}"); + } + + @override + void onAIToolResultReceived(AIToolResultMessage aiToolArgumentMessage) { + debugPrint("AI Assistant Message Received: ${aiToolArgumentMessage.toString()}"); + } + + @override + void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { + debugPrint("AI Assistant Message Received: ${aiToolArgumentMessage.toString()}"); + } + } + ``` + + + +--- + +## 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/v4/ai-chatbots-overview.mdx b/sdk/flutter/v4/ai-chatbots-overview.mdx new file mode 100644 index 000000000..f3037d7e9 --- /dev/null +++ b/sdk/flutter/v4/ai-chatbots-overview.mdx @@ -0,0 +1,65 @@ +--- +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/v4/ai-moderation.mdx b/sdk/flutter/v4/ai-moderation.mdx new file mode 100644 index 000000000..4d8868826 --- /dev/null +++ b/sdk/flutter/v4/ai-moderation.mdx @@ -0,0 +1,317 @@ +--- +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). + + +## 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 + +## How It Works + +```mermaid +sequenceDiagram + participant App + participant SDK + participant CometChat + participant Moderation + + App->>SDK: sendMessage() + SDK->>CometChat: Send Message + CometChat->>Moderation: Process Message + CometChat-->>SDK: Message (status: PENDING) + SDK-->>App: onSuccess (PENDING) + Moderation-->>CometChat: Moderation Result + CometChat-->>SDK: onMessageModerated + SDK-->>App: APPROVED or DISAPPROVED +``` + +| Step | Description | +|------|-------------| +| 1. Send Message | App sends a text, image, or video message | +| 2. Pending Status | Message is sent with `PENDING` moderation status | +| 3. AI Processing | Moderation service analyzes the content | +| 4. Result Event | `onMessageModerated` event fires with final status | + +## 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 | + +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 | + +## Moderation Status + +The `moderationStatus` property returns one of the following enum values: + +| Status | Enum Value | Description | +|--------|------------|-------------| +| Pending | `ModerationStatusEnum.PENDING` | Message is being processed by moderation | +| Approved | `ModerationStatusEnum.APPROVED` | Message passed moderation and is visible | +| Disapproved | `ModerationStatusEnum.DISAPPROVED` | Message violated rules and was blocked | + +## Implementation + +### Step 1: Send a Message and Check Initial Status + +When you send a text, image, or video message, check the initial moderation status: + + + + ```dart + TextMessage textMessage = TextMessage( + text: "Hello, how are you?", + receiverUid: receiverUID, + receiverType: ReceiverTypeConstants.user, + ); + + CometChat.sendMessage( + textMessage, + onSuccess: (TextMessage message) { + // Check moderation status + if (message.moderationStatus?.value == ModerationStatusEnum.PENDING.value) { + print("Message is under moderation review"); + // Show pending indicator in UI + } + }, + onError: (CometChatException e) { + print("Message sending failed: ${e.message}"); + }, + ); + ``` + + + + +**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: + + + + ```dart + class ModerationListener with MessageListener { + + @override + void onMessageModerated(BaseMessage message) { + if (message is TextMessage) { + switch (message.moderationStatus?.value) { + case ModerationStatusEnum.APPROVED: + print("Message ${message.id} approved"); + // Update UI to show message normally + break; + + case ModerationStatusEnum.DISAPPROVED: + print("Message ${message.id} blocked"); + // Handle blocked message (hide or show warning) + handleDisapprovedMessage(message); + break; + } + } else if (message is MediaMessage) { + switch (message.moderationStatus?.value) { + case ModerationStatusEnum.APPROVED: + print("Media message ${message.id} approved"); + break; + + case ModerationStatusEnum.DISAPPROVED: + print("Media message ${message.id} blocked"); + handleDisapprovedMessage(message); + break; + } + } + } + } + + // Register the listener + CometChat.addMessageListener("MODERATION_LISTENER", ModerationListener()); + + // Don't forget to remove the listener when done + // CometChat.removeMessageListener("MODERATION_LISTENER"); + ``` + + + +### Step 3: Handle Disapproved Messages + +When a message is disapproved, handle it appropriately in your UI: + + + + ```dart + void handleDisapprovedMessage(BaseMessage message) { + int messageId = message.id; + + // Option 1: Hide the message completely + hideMessageFromUI(messageId); + + // Option 2: Show a placeholder message + showBlockedPlaceholder(messageId, "This message was blocked by moderation"); + + // Option 3: Notify the sender (if it's their message) + if (message.sender?.uid == currentUserUID) { + showNotification("Your message was blocked due to policy violation"); + } + } + ``` + + + +## Next Steps + +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/v4/ai-user-copilot-overview.mdx b/sdk/flutter/v4/ai-user-copilot-overview.mdx new file mode 100644 index 000000000..12601d050 --- /dev/null +++ b/sdk/flutter/v4/ai-user-copilot-overview.mdx @@ -0,0 +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" +--- diff --git a/sdk/flutter/v4/authentication-overview.mdx b/sdk/flutter/v4/authentication-overview.mdx new file mode 100644 index 000000000..07ff5d486 --- /dev/null +++ b/sdk/flutter/v4/authentication-overview.mdx @@ -0,0 +1,348 @@ +--- +title: "Authentication" +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 a User + +A user must exist in CometChat before they can log in. + +- **During development:** Create users from the [CometChat Dashboard](https://app.cometchat.com). Five test users are already available with UIDs `cometchat-uid-1` through `cometchat-uid-5`. +- **In production:** Call the [Create User REST API](https://api-explorer.cometchat.com/reference/creates-user) when a user signs up in your app. + + + +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`. + + + +### 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. + +```dart +User? user = await CometChat.getLoggedInUser(); +if (user != null) { + // User is already logged in — proceed to your app +} +``` + +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 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 [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. + + + + +```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}"); + }); +} +``` + + + + + +| 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: + + + +**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."` | + + + +## 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()`. + + + +```dart +String authToken = "AUTH_TOKEN"; +var user = await CometChat.getLoggedInUser(onSuccess: (_){}, onError: (_){}); +if (user == null) { + if(authToken!=null){ + await CometChat.loginWithAuthToken(authToken, + onSuccess: (User loggedInUser){ + debugPrint("Login Successful : $user" ); + }, onError: ( CometChatException e){ + debugPrint("Login failed with exception: ${e.message}"); + }); + } +} +``` + + + + + +| 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: + + + +**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 + +Call `logout()` when your user logs out of your app. This clears the local session. + + + +```dart +CometChat.logout( onSuccess: ( successMessage) { + debugPrint("Logout successful with message $successMessage"); + }, onError: (CometChatException e ){ + debugPrint("Logout failed with exception: ${e.message}"); + } + ); +``` + + + + + + +**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/v4/best-practices.mdx similarity index 100% rename from sdk/flutter/best-practices.mdx rename to sdk/flutter/v4/best-practices.mdx diff --git a/sdk/flutter/v4/block-users.mdx b/sdk/flutter/v4/block-users.mdx new file mode 100644 index 000000000..6370279cd --- /dev/null +++ b/sdk/flutter/v4/block-users.mdx @@ -0,0 +1,307 @@ +--- +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 `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 | + + + +```dart +List uids = []; +uids.add("UID1"); +uids.add("UID2"); +uids.add("UID3"); +CometChat.blockUser(uids, onSuccess: (Map map) { +debugPrint("Blocked User Successfully $map "); +}, onError: (CometChatException e) { +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 `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 | + + + +```dart +List uids = []; +uids.add("UID1"); +uids.add("UID2"); +uids.add("UID3"); + +CometChat.unblockUser(uids, onSuccess: (Map map) { + debugPrint("Blocked User Successfully $map "); + }, onError: (CometChatException e) { + 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 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 + +*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: + +### 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. + + + +```dart +BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() + ..limit = 50 + ).build(); +``` + + + + + +### Set Search Keyword + +This method allows you to set the search string based on which the blocked users are to be fetched. + + + +```dart +BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() + ..limit = 50 + ..searchKeyword = "abc" + ).build(); +``` + + + + + +### Set Direction + +* `CometChatBlockedUsersDirection.`*directionBlockedByMe* - This will ensure that the list of blocked users only contains the users blocked by the logged in user. +* `CometChatBlockedUsersDirection.`*directionHasBlockedMe* - This will ensure that the list of blocked users only contains the users that have blocked the logged in user. +* `CometChatBlockedUsersDirection.`*directionBoth* - 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. + + + +```dart +BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() + ..limit = 50 + ..direction = CometChatBlockedUsersDirection.directionBlockedByMe + ).build(); +``` + + + + + +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. + +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. + + + +```dart +BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() + ..limit = 30 + ).build(); + +blockedUsersRequest.fetchNext(onSuccess: (List userList){ + debugPrint("Custom Message Sent Successfully : $userList "); + }, onError: (CometChatException e){ + debugPrint("Blocked User Request failed with exception: ${e.message}"); +}); +``` + + + + + + +**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/calling-overview.mdx b/sdk/flutter/v4/calling-overview.mdx similarity index 100% rename from sdk/flutter/calling-overview.mdx rename to sdk/flutter/v4/calling-overview.mdx diff --git a/sdk/flutter/v5/changelog.mdx b/sdk/flutter/v4/changelog.mdx similarity index 53% rename from sdk/flutter/v5/changelog.mdx rename to sdk/flutter/v4/changelog.mdx index eb92a1622..d482ab3bb 100644 --- a/sdk/flutter/v5/changelog.mdx +++ b/sdk/flutter/v4/changelog.mdx @@ -1,4 +1,6 @@ --- title: "Changelog" +sidebarTitle: "Changelog" url: "https://github.com/cometchat/chat-sdk-flutter/releases" +description: "Navigate to Changelog documentation." --- \ No newline at end of file diff --git a/sdk/flutter/v5/connection-behaviour.mdx b/sdk/flutter/v4/connection-behaviour.mdx similarity index 57% rename from sdk/flutter/v5/connection-behaviour.mdx rename to sdk/flutter/v4/connection-behaviour.mdx index ba5b683a9..568b22c4d 100644 --- a/sdk/flutter/v5/connection-behaviour.mdx +++ b/sdk/flutter/v4/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. @@ -25,7 +55,7 @@ CometChat SDK default connection behaviour is auto mode. Auto mode, the SDK auto 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. - + CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground | App State | Behaviour | @@ -51,7 +81,7 @@ To keep the WebSocket connection alive even if your app goes in the background, 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. - + CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow | App State | Behaviour | @@ -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/v4/connection-status.mdx b/sdk/flutter/v4/connection-status.mdx new file mode 100644 index 000000000..890d70074 --- /dev/null +++ b/sdk/flutter/v4/connection-status.mdx @@ -0,0 +1,161 @@ +--- +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: + +1. `CometChatWSState.connected` (connected) +2. `CometChatWSState.connecting` (connecting) +3. `CometChatWSState.disconnected` (disconnected) +4. `CometChatWSState.featureThrottled` (featureThrottled) + +## Listen for Connection Changes + +Register a `ConnectionListener` to receive real-time connection state updates. We recommend adding this on app startup after `CometChat.init()` completes. + +### 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 | + + + + +```dart +class Class_Name with ConnectionListener { +//1. Register Connection listener +//CometChat.addConnctionListener("listenerId", this); + +//2. Ovveride the ConnectionListener methods +@override +void onConnected() { + // TODO: implement onConnected +} + +@override +void onConnecting() { + // TODO: implement onConnecting +} + +@override +void onDisconnected() { + // TODO: implement onDisconnected +} + +@override +void onFeatureThrottled() { + // TODO: implement onFeatureThrottled +} + +@override +void onConnectionError(CometChatException error) { + // TODO: implement onFeatureThrottled +} + +} +``` + + + + + + +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 +CometChat.removeConnectionListener("listenerId"); +``` + + + +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/v4/create-group.mdx b/sdk/flutter/v4/create-group.mdx new file mode 100644 index 000000000..0c6157da2 --- /dev/null +++ b/sdk/flutter/v4/create-group.mdx @@ -0,0 +1,249 @@ +--- +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?* + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +Use `createGroup()` to create a new group. Pass a `Group` object with the group details. + +| 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 | + +### Parameters + +| 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 | + + + +```dart +String GUID = "GUID"; + String groupName = "Hello Group!"; + String groupType = CometChatGroupType.public; + String password = ""; + + Group _group = Group(guid: GUID, name: groupName, type: groupType); + + + await CometChat.createGroup(group: _group, onSuccess: (Group group ){ + debugPrint("Group Created Successfully : $group "); + }, onError:(CometChatException e) { + debugPrint("Group Creation failed with exception: ${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-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 | 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."` | + + + +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 + +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 | +| name | Yes | Name of the group | +| type | No | Type of the group: Can be 1. Public 2. Password 3. Private | +| password | No | Password for the group in case the group is of type password. | +| icon | Yes | An URL to group icon | +| description | Yes | Description about the group | +| owner | Yes | UID of the owner of the group. | +| metadata | Yes | Additional data for the group as JSON | +| 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/flutter/v4/delete-conversation.mdx b/sdk/flutter/v4/delete-conversation.mdx new file mode 100644 index 000000000..7eed0b031 --- /dev/null +++ b/sdk/flutter/v4/delete-conversation.mdx @@ -0,0 +1,125 @@ +--- +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}"), +); +``` + +**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 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. + + + +```dart +String conversationWith = "UID"; +String conversationType = CometChatConversationType.user; +await CometChat.deleteConversation(conversationWith, conversationType, + onSuccess: (String str){ + debugPrint("Conversation deleted successfully at : $str"); + }, + onError: (CometChatException e){ + debugPrint("Conversation deletion failed : ${e.message}"); + } +); +``` + + + + +```dart +String conversationWith = "GUID"; +String conversationType = CometChatConversationType.group; +await CometChat.deleteConversation(conversationWith, conversationType, + onSuccess: (String str){ + debugPrint("Conversation deleted successfully at : $str"); + }, + onError: (CometChatException e){ + debugPrint("Conversation deletion failed : ${e.message}"); + } +); +``` + + + + + +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."` | + + + +--- + +## Next Steps + + + + 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/v4/delete-group.mdx b/sdk/flutter/v4/delete-group.mdx new file mode 100644 index 000000000..4f48f7e14 --- /dev/null +++ b/sdk/flutter/v4/delete-group.mdx @@ -0,0 +1,104 @@ +--- +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. + + +This operation is irreversible. Deleted groups and their messages cannot be recovered. + + +## 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 | + + + +```dart +String GUID = "GUID"; + +CometChat.deleteGroup(GUID, onSuccess: (String message) { +debugPrint("Deleted Group Successfully : $message "); +}, onError: (CometChatException e) { +debugPrint("Delete Group failed with exception: ${e.message}"); +}); +``` + + + + + + +**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 + + + + 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/v4/delete-message.mdx b/sdk/flutter/v4/delete-message.mdx new file mode 100644 index 000000000..0240e6336 --- /dev/null +++ b/sdk/flutter/v4/delete-message.mdx @@ -0,0 +1,272 @@ +--- +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) 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?* + +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. | + + + +```dart +int messageId=1234; + +await CometChat.deleteMessage(messageId, + onSuccess: (BaseMessage message){ + debugPrint("Message deleted successfully at : $message"); + }, onError: (CometChatException e){ + debugPrint("Message deletion failed : ${e.message}"); + } +); +``` + + + + + + +**On Success** — A `BaseMessage` object with `deletedAt` and `deletedBy` fields set: + + + +**BaseMessage Object:** + +| 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 | +| --------------- | ----------------------- | ------------------------- | +| 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 | + +## 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. + + + +```dart +class Class_Name with MessageListener { + +//CometChat.addMessageListener("listenerId", this); +@override +void onMessageDeleted(BaseMessage message) { + // TODO implement onMessageDeleted +} + + +} +``` + + + + + + +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?* + +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. + +For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- + +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. + + +You must be the message sender or a group admin/moderator to delete a message. + + +--- + +## 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/v4/delivery-read-receipts.mdx b/sdk/flutter/v4/delivery-read-receipts.mdx new file mode 100644 index 000000000..ca2605290 --- /dev/null +++ b/sdk/flutter/v4/delivery-read-receipts.mdx @@ -0,0 +1,418 @@ +--- +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 delivered using the `markAsDelivered()` method. This method takes a `BaseMessage` object as input. + + +| 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 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 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: + + + +```dart +CometChat.markAsDelivered(message, onSuccess: (String unused) { + debugPrint("markAsDelivered : $unused "); +}, onError: (CometChatException e) { + debugPrint("markAsDelivered unsuccessful : ${e.message} "); +}); +``` + + + + + + +**On Success** — A `String` message confirming the message has been marked as delivered: + + + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | `String` | Success confirmation message | `"markAsDelivered 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 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. + +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: + +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 `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 and pass it to the `markAsRead()` method + +This method will mark all the messages before the message specified, for the conversation with `receiverId` and `receiverType` (user/group) as read. + +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. + + + +```dart +CometChat.markAsRead(message) +``` + + + + + +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: + + + +```dart +CometChat.markAsRead(message, onSuccess: (String unused) { + debugPrint("markAsRead : $unused "); + reinitiateList(); + }, onError: (CometChatException e) { + debugPrint("markAsRead unsuccessfull : ${e.message} "); + }); +``` + + + + + + +**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. + +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 message as unread?* + +You can mark the messages for a particular conversation as unread using the `markMessageAsUnread()` method. + +| 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.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 + +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 | + + + +```dart +class Class_Name with MessageListener { + +//CometChat.addMessageListener("listenerId", this); +@override +void onMessagesDelivered(MessageReceipt messageReceipt) { + // TODO: implement onMessagesDelivered +} + +@override +void onMessagesRead(MessageReceipt messageReceipt) { + // TODO: implement onMessagesRead +} + +@override +void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { + // TODO: implement onMessagesDeliveredToAll +} + +@override +void onMessagesReadByAll(MessageReceipt messageReceipt) { + // TODO: implement onMessagesReadByAll +} + +} +``` + + + + + + +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(); +} +``` + + +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 + +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. + +## 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. + +| 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 +int messageId = 10101; + +CometChat.getMessageReceipts(messageId, onSuccess: (List messageReceipts) { + debugPrint("Message receipts fetched: $messageReceipts"); +}, onError: (CometChatException e) { + debugPrint("Error fetching receipts: ${e.message}"); +}); +``` + + + + + + +**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. + + + +The following features will be available only if the **Enhanced Messaging Status** feature is enabled for your app. + +* `onMessagesDeliveredToAll` event, +* `onMessagesReadByAll` event, +* `deliveredAt` field in a group message, +* `readAt` field in a group message. +* `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/v4/edit-message.mdx b/sdk/flutter/v4/edit-message.mdx new file mode 100644 index 000000000..f9f54efde --- /dev/null +++ b/sdk/flutter/v4/edit-message.mdx @@ -0,0 +1,296 @@ +--- +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 | + +```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 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 + +Use `editMessage()` with a [`TextMessage`](/sdk/reference/messages#textmessage) or [`CustomMessage`](/sdk/reference/messages#custommessage) object. Set the message ID using the `id` property. + +| 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 + +Use `tags` to update tags when editing. New tags replace existing ones. + + + +```dart +List tags = []; +tags.add("pinned"); +textMessage.tags = tags; +``` + + + + +```dart +List tags = []; +tags.add("pinned"); +customMessage.tags = tags; +``` + + + + + +Once the message object is ready, call `editMessage()`. + + + +```dart +TextMessage updatedMessage = TextMessage( + text: updatedText, + receiverUid: receiverID, + receiverType: receiverType, + type: type); + +updatedMessage.id = message.id; + +await CometChat.editMessage(updatedMessage, + onSuccess: (BaseMessage message){ + debugPrint("Message Edited successfully: $message"); + }, onError: (CometChatException e){ + debugPrint("Message Edited failed with exception: ${e.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. + +| 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 | + +## Real-time Message Edit Events + +Use `onMessageEdited` in `MessageListener` to receive real-time edit events. + + + +```dart +class Class_Name with MessageListener { + +//CometChat.addMessageListener("listenerId", this); +@override +void onMessageEdited(BaseMessage message) { + // TODO: implement onMessageEdited +} + + +} +``` + + + + + +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 `onMessageEdited` callback receives a [`BaseMessage`](/sdk/reference/messages#basemessage) object with the `editedAt` and `editedBy` fields set. + +Relevant fields to access on the returned message: + +| Field | 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 + +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/v4/error-codes.mdx similarity index 100% rename from sdk/flutter/error-codes.mdx rename to sdk/flutter/v4/error-codes.mdx diff --git a/sdk/flutter/v4/extensions-overview.mdx b/sdk/flutter/v4/extensions-overview.mdx new file mode 100644 index 000000000..5dcf22fb9 --- /dev/null +++ b/sdk/flutter/v4/extensions-overview.mdx @@ -0,0 +1,144 @@ +--- +title: "Extensions" +sidebarTitle: "Extensions" +description: "Explore CometChat extensions that add enhanced functionality to your Flutter chat application" +url: "/fundamentals/extensions-overview" +--- + + +**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/v5/flag-message.mdx b/sdk/flutter/v4/flag-message.mdx similarity index 54% rename from sdk/flutter/v5/flag-message.mdx rename to sdk/flutter/v4/flag-message.mdx index 02b71550c..a2f8d6530 100644 --- a/sdk/flutter/v5/flag-message.mdx +++ b/sdk/flutter/v4/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/v4/group-add-members.mdx b/sdk/flutter/v4/group-add-members.mdx new file mode 100644 index 000000000..36b38943c --- /dev/null +++ b/sdk/flutter/v4/group-add-members.mdx @@ -0,0 +1,178 @@ +--- +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 + + +**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). + +| 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. + + + +```dart +List groupMembers = []; +GroupMember firstMember = GroupMember.fromUid( +scope: CometChatMemberScope.participant, +uid: "cometchat-uid-3",name: "name"); +GroupMember secondMember = GroupMember.fromUid(scope: CometChatMemberScope.admin, +uid: "cometchat-uid-4",name: "name"); + +groupMembers = [firstMember, secondMember]; + +CometChat.addMembersToGroup( guid: conversationWith, + groupMembers: groupMembers, + onSuccess: (Map result) { + debugPrint("Group Member added Successfully : $result"); + }, + onError: (CometChatException e) { + debugPrint("Group Member addition failed with exception: ${e.message}"); + }); +``` + + + + + + +**On Success** — A `Map` where each key is the UID of the user and the value is either `"success"` or an error message: + + + +| 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"` | + + + + + + + +| 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."` | + + + +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. + + + +```dart +class Class_Name with GroupListener { + +//CometChat.addGroupListener("group_Listener_id", this); +@override +void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo) { + print("onMemberAddedToGroup"); +} +} +``` + + + + + +| 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 | + + +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 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: + +| 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 + + + + 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/v4/group-change-member-scope.mdx b/sdk/flutter/v4/group-change-member-scope.mdx new file mode 100644 index 000000000..0420f4fdb --- /dev/null +++ b/sdk/flutter/v4/group-change-member-scope.mdx @@ -0,0 +1,151 @@ +--- +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 + +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) + + + + +```dart +String UID = "UID"; +String GUID = "GUID"; +String scope = CometChatMemberScope.admin; + +CometChat.updateGroupMemberScope(guid: GUID, uid: UID, scope: scope, + onSuccess: (String message) { + debugPrint("Group Member Scope Changed Successfully : $message"); + }, + onError: (CometChatException e) { + debugPrint("Group Member Scope Change failed : ${e.message}"); + }); +``` + + + + + +This method takes the below parameters: + +| 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. + + +**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"` | + + + + + + + +| 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. + + + +```dart +class Class_Name with GroupListener { + +//CometChat.addGroupListener("group_Listener_id", this); +@override +void onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { + print("onGroupMemberScopeChanged "); + +} +} +``` + + + + + + +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 + +When fetching previous messages, scope changes appear as [Action](/sdk/reference/messages#action) messages (a subclass of `BaseMessage`). + +| 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 | + +--- + +## 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/v4/group-kick-ban-members.mdx similarity index 100% rename from sdk/flutter/group-kick-ban-members.mdx rename to sdk/flutter/v4/group-kick-ban-members.mdx diff --git a/sdk/flutter/v4/groups-overview.mdx b/sdk/flutter/v4/groups-overview.mdx new file mode 100644 index 000000000..3e27ebc8c --- /dev/null +++ b/sdk/flutter/v4/groups-overview.mdx @@ -0,0 +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 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/v4/interactive-messages.mdx b/sdk/flutter/v4/interactive-messages.mdx new file mode 100644 index 000000000..e13d96a3e --- /dev/null +++ b/sdk/flutter/v4/interactive-messages.mdx @@ -0,0 +1,579 @@ +--- +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 | + +```dart +// 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) { } +``` + + + +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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +## InteractiveMessage + +The `InteractiveMessage` class extends `BaseMessage` and represents a message with embedded interactive content. + +| 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 | + +## Send an Interactive Message + +Use `CometChat.sendInteractiveMessage()` to send an interactive message. + + + +```dart +final Map interactiveData = { + "title": "Survey", + "formFields": [ + { + "elementType": "textInput" , + "elementId": "name", + "optional": false, + "label": "Name", + "placeholder": { + "text": "Enter text here" + } + }, + { + "elementType": "textInput", + "elementId": "age", + "optional": true, + "label": "Age", + "maxLines": 1, + "placeholder": { + "text": "Enter text here" + } + }, + { + "elementType": "Select", + "elementId": "checkBox1", + "optional": true, + "label": "Check box element", + "defaultValue":["chk_option_2"], + "options" : [ + { + "label": "Option 1", + "value": "chk_option_1", + }, + { + "label": "Option 2", + "value": "chk_option_2", + } + + ] + }, + { + "elementType": "dropdown", + "elementId": "gender", + "optional": false, + "label": "Gender", + "defaultValue":"male", + "options" : [ + { + "label": "Male", + "value": "male", + }, + { + "label": "Female", + "value": "female", + } + + ] + }, + ], + "submitElement": { + "elementType": "button", + "elementId": "submitButton", + "buttonText": "Submit", + "disableAfterInteracted": false, + "action": { + "actionType": "urlNavigation", + "url": "https://www.cometchat.com/", + } + }, +}; + + + +InteractiveMessage interactiveMessage = +InteractiveMessage(interactiveData: interactiveData, + receiverUid: "cometchat-uid-3", //Replace this with receiver id + type: "form", + receiverType: "user",//replace this with receiver type + allowSenderInteraction: true, + muid: DateTime.now().millisecondsSinceEpoch.toString(), + interactionGoal: InteractionGoal( + type: InteractionGoalType.none + ) + ); + + +CometChat.sendInteractiveMessage(interactiveMessage, onSuccess: (InteractiveMessage message){ + +print(interactiveMessage); + +}, onError: (CometChatException excep){ +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}"); + }, +); +``` + + + + +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. + +## Interactions + +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 | + +## 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. + + + +```dart +class DemoClass with MessageListener{ + +String listenerId = "UNIQUE_LISTENER_ID"; //Replace with unique listener id + + +CometChat.addMessageListener(_listenerId, this); + + + + @override +void onInteractiveMessageReceived(InteractiveMessage message){ + + //TODO implement onInteractiveMessageReceived event +} + +} +``` + + + + +### Interaction Goal Completed + +The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. + +`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 | + + + +```dart +class DemoClass with MessageListener{ + +String listenerId = "UNIQUE_LISTENER_ID"; //Replace with unique listener id + + +CometChat.addMessageListener(_listenerId, this); + + + +@override +void onInteractionGoalCompleted(InteractionReceipt receipt) { + //TODO implement onInteractionGoalCompleted +} + +} +``` + + + + +These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience. + + +Always remove 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}"); + }, +); +``` + + + + +--- + +## 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/v4/join-group.mdx b/sdk/flutter/v4/join-group.mdx new file mode 100644 index 000000000..bc2595378 --- /dev/null +++ b/sdk/flutter/v4/join-group.mdx @@ -0,0 +1,166 @@ +--- +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 + +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 | + + + +```dart +String GUID = "GUID"; +String groupType = CometChatGroupType.public; +String password = ""; + +CometChat.joinGroup(GUID, groupType, password: password, + onSuccess: (Group group) { + debugPrint("Group Joined Successfully : $group "); + }, onError: (CometChatException e) { + debugPrint("Group Joining failed with exception: ${e.message}"); + }); +``` + + + + + + +**On Success** — A `Group` object containing all details of the joined 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 | `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` | + + + + + +| 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 + +*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. + + + +```dart +class ClassName with GroupListener { + // CometChat.addGroupListener("group_Listener_id", this); + + @override + void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { + debugPrint("onGroupMemberJoined"); + } +} +``` + + + + + + +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?* + +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 + +--- + +## 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/v4/key-concepts.mdx similarity index 100% rename from sdk/flutter/key-concepts.mdx rename to sdk/flutter/v4/key-concepts.mdx diff --git a/sdk/flutter/v4/leave-group.mdx b/sdk/flutter/v4/leave-group.mdx new file mode 100644 index 000000000..3d57928d7 --- /dev/null +++ b/sdk/flutter/v4/leave-group.mdx @@ -0,0 +1,149 @@ +--- +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 + +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 | + + + +```dart +String GUID = "GUID"; + +CometChat.leaveGroup(GUID, onSuccess: ( String message) { + debugPrint("Group Left Successfully : $message"); + },onError: (CometChatException e) { + debugPrint("Group Left failed : ${e.message}"); + }); +``` + + + + + + +**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. + +## 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. + + + +```dart +class Class_Name with GroupListener { + +//CometChat.addGroupListener("group_Listener_id", this); +@override +void onGroupMemberLeft(Action action, User leftUser, Group leftGroup) { + print("onGroupMemberLeft "); + +} +} +``` + + + + + + +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`](/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/v4/mentions.mdx b/sdk/flutter/v4/mentions.mdx new file mode 100644 index 000000000..d837732e7 --- /dev/null +++ b/sdk/flutter/v4/mentions.mdx @@ -0,0 +1,596 @@ +--- +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. + + +**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/flutter/overview) + + +## 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>`" + + + +```dart +String receiverID = "UID"; +User sender = User(name: "Sender", uid: "senderUID"); +String messageText = "Hello, <@uid:cometchat-uid-1>"; +String receiverType = CometChatReceiverType.user; + +TextMessage textMessage = TextMessage( + text: messageText, + sender: sender, + receiverUid: receiverID, + receiverType: receiverType, + category: CometChatMessageCategory.message, + type: CometChatMessageType.text); + +CometChat.sendMessage(textMessage, onSuccess:(TextMessage textMessage) { + print("Message sent successfully: ${textMessage.text}, mentioned users: ${textMessage.mentionedUsers}"); + }, + onError:(CometChatException e) { + print("Message sending failed with exception: $e"); + } +); +``` + + + + +```dart +String receiverID = "GUID"; +User sender = User(name: "Sender", uid: "senderUID"); +String messageText = "Hello, <@uid:cometchat-uid-1>"; +String receiverType = CometChatReceiverType.group; + +TextMessage textMessage = TextMessage( + text: messageText, + sender: sender, + receiverUid: receiverID, + receiverType: receiverType, + category: CometChatMessageCategory.message, + type: CometChatMessageType.text); + +CometChat.sendMessage(textMessage, onSuccess:(TextMessage textMessage) { + print("Message sent successfully: ${textMessage.text}, mentioned users: ${textMessage.mentionedUsers}"); + }, + onError:(CometChatException e) { + print("Message sending failed with exception: $e"); + } +); +``` + + + + + + +**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 + + + +## 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. + +| Setting | Description | Default Value | +| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | +| `mentionsWithTagInfo(bool 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. | false | +| `mentionsWithBlockedInfo(bool 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. | false | + +## 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. + +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 +String UID = "cometchat-uid-1"; + +MessagesRequest messagesRequest = (MessagesRequestBuilder() +..limit=50 +..uid=UID +..mentionsWithTagInfo(true)) +.build(); + +messagesRequest.fetchPrevious(onSuccess:(List messages) { + for (BaseMessage message in messages){ + for (User user in message.mentionedUsers){ + print("mentioned user tags: ${user.tags}"); + } + } + }, + onError: (CometChatException e) { + print("error: $e"); + } +); +``` + + + + +```dart +String GUID = "cometchat-guid-1"; + +MessagesRequest messagesRequest = (MessagesRequestBuilder() +..limit=50 +..guid=GUID +..mentionsWithTagInfo(true)) +.build(); + +messagesRequest.fetchPrevious(onSuccess:(List messages) { + for (BaseMessage message in messages){ + for (User user in message.mentionedUsers){ + print("mentioned user tags: ${user.tags}"); + } + } + }, + onError: (CometChatException e) { + print("error: $e"); + } +); +``` + + + + + + +**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 +String UID = "cometchat-uid-1"; + +MessagesRequest messagesRequest = (MessagesRequestBuilder() +..limit=50 +..uid=UID +..mentionsWithBlockedInfo(true)) +.build(); + +messagesRequest.fetchPrevious(onSuccess:(List messages) { + for (BaseMessage message in messages){ + for (User user in message.mentionedUsers){ + print("mentioned user has blocked me? ${user.hasBlockedMe}"); + print("mentioned user is blocked by me? ${user.blockedByMe}"); + } + } + }, + onError: (CometChatException e) { + print("error: $e"); + } +); +``` + + + + +```dart +String GUID = "cometchat-guid-1"; + +MessagesRequest messagesRequest = (MessagesRequestBuilder() +..limit=50 +..guid=GUID +..mentionsWithBlockedInfo(true)) +.build(); + +messagesRequest.fetchPrevious(onSuccess:(List messages) { + for (BaseMessage message in messages){ + for (User user in message.mentionedUsers){ + print("mentioned user has blocked me? ${user.hasBlockedMe}"); + print("mentioned user is blocked by me? ${user.blockedByMe}"); + } + } + }, + onError: (CometChatException e) { + print("error: $e"); + } +); +``` + + + + + + +**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 +``` + + + + + +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`. + + + +```dart +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/v4/message-structure-and-hierarchy.mdx similarity index 98% rename from sdk/flutter/message-structure-and-hierarchy.mdx rename to sdk/flutter/v4/message-structure-and-hierarchy.mdx index 7f6284d3e..fe4c22aeb 100644 --- a/sdk/flutter/message-structure-and-hierarchy.mdx +++ b/sdk/flutter/v4/message-structure-and-hierarchy.mdx @@ -1,7 +1,7 @@ --- 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." +description: "Understand CometChat Flutter SDK message categories, types, class hierarchy, and text, media, custom, interactive, and action messages." --- diff --git a/sdk/flutter/v4/overview.mdx b/sdk/flutter/v4/overview.mdx new file mode 100644 index 000000000..6789301ed --- /dev/null +++ b/sdk/flutter/v4/overview.mdx @@ -0,0 +1,149 @@ +--- +title: "Flutter SDK" +sidebarTitle: "Overview" +description: "Add real-time chat, voice, and video to your Flutter application with the CometChat SDK." +--- + +{/* TL;DR for Agents and Quick Reference */} + + +```yaml +# Install (pubspec.yaml) +cometchat_sdk: ^4.0.33 +``` + +```dart +import 'package:cometchat_sdk/cometchat_sdk.dart'; + +// 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("APP_ID", appSettings, + onSuccess: (msg) => debugPrint("Init success"), + onError: (e) => debugPrint("Init failed: ${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}"), +); +``` + +**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/rate-limits.mdx b/sdk/flutter/v4/rate-limits.mdx similarity index 100% rename from sdk/flutter/rate-limits.mdx rename to sdk/flutter/v4/rate-limits.mdx diff --git a/sdk/flutter/v4/reactions.mdx b/sdk/flutter/v4/reactions.mdx new file mode 100644 index 000000000..7f0c3e057 --- /dev/null +++ b/sdk/flutter/v4/reactions.mdx @@ -0,0 +1,576 @@ +--- +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 | + +```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 + +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, "\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 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 + +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, "\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 + +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 +} +``` + + + +## 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). + +| 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; + +ReactionsRequest reactionsRequest = (ReactionsRequestBuilder() + ..limit = 30 + ..messageId = messageId +).build(); + +reactionsRequest.fetchNext( + onSuccess: (reactions) { + for (Reaction reaction in reactions) { + debugPrint("Success: $reaction"); + } + }, + onError: (e) { + debugPrint("Error: ${e.message}"); + }, +); +``` + + + +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. + + + +```dart +int messageId = 1; + +ReactionsRequest reactionsRequest = (ReactionsRequestBuilder() + ..limit = 30 + ..messageId = messageId +).build(); + +reactionsRequest.fetchPrevious( + onSuccess: (reactions) { + for (Reaction reaction in reactions) { + debugPrint("Success: $reaction"); + } + }, + onError: (e) { + debugPrint("Error: ${e.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-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. + + + +```dart +class MyClass with MessageListener { + + String listenerID = "UNIQUE_LISTENER_ID"; + + MyClass() { + CometChat.addMessageListener(listenerID, this); + } + + @override + void onMessageReactionAdded(ReactionEvent reactionEvent) { + debugPrint("Reaction added ${reactionEvent.reaction}"); + } + + @override + void onMessageReactionRemoved(ReactionEvent reactionEvent) { + debugPrint("Reaction removed ${reactionEvent.reaction}"); + } +} +``` + + + +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). | + +### Remove the Listener + + + +```dart +String listenerID = "UNIQUE_LISTENER_ID"; + +CometChat.removeMessageListener(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. + + +## 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. + +| 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 +// 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 +} +``` + + + +After calling this method, use `modifiedBaseMessage?.reactions` to get the latest reactions and refresh your UI. + +--- + +## 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/v4/real-time-listeners.mdx b/sdk/flutter/v4/real-time-listeners.mdx new file mode 100644 index 000000000..0ba1a4508 --- /dev/null +++ b/sdk/flutter/v4/real-time-listeners.mdx @@ -0,0 +1,639 @@ +--- +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) { + + } + +} +``` + + + + + +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. + + + +```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. + +### 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 +class Class_Name with UserListener { + //CometChat.addUserListener("user_Listener_id", this); + @override + void onUserOnline(User user) { + + } + + @override + void onUserOffline(User user) { + + } + +} +``` + + + + + +where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. + +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. + + + +```dart +CometChat.removeUserListener(UNIQUE_LISTENER_ID) +``` + + + + + +## Group Listener + +The `GroupListener` class provides you with all the real-time events related to groups. Below are the callback methods provided by the `GroupListener` class. + +### 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 +class Class_Name with GroupListener { + //CometChat.addGroupListener("UNIQUE_LISTENER_ID", this); + + @override + void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { + + } + + @override + void onGroupMemberLeft(Action action, User leftUser, Group leftGroup) { + + } + + @override + void onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom) { + + } + + @override + void onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom) { + + } + + @override + void onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom) { + + } + + @override + void onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { + + } + + @override + void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo) { + + } + +} +``` + + + + + +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. + + + +```dart +CometChat.removeGroupListener(UNIQUE_LISTENER_ID) +``` + + + + + +## Call Listener + +The `CallListener` class provides you with real-time events related to calls. Below are the callback methods provided by the `CallListener` class. + +### CallListener Events + +| 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 CallListener { + //CometChat.addCallListener("UNIQUE_LISTENER_ID", this); + + @override + void onIncomingCallReceived(Call call) { + + } + + @override + void onOutgoingCallAccepted(Call call) { + + } + + @override + void onOutgoingCallRejected(Call call) { + + } + + @override + void onIncomingCallCancelled(Call call) { + + } + + @override + 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 onConnected() { + + } + + @override + void onConnecting() { + + } + + @override + void onDisconnected() { + + } + + @override + void onFeatureThrottled() { + + } + + @override + 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 loginSuccess(User user) { + + } + + @override + void loginFailure(CometChatException e) { + + } + + @override + void logoutSuccess() { + + } + + @override + void logoutFailure(CometChatException e) { + + } + +} +``` + + + + + +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) { + + } + +} +``` + + + + + +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 `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/v4/receive-messages.mdx b/sdk/flutter/v4/receive-messages.mdx new file mode 100644 index 000000000..f4f376439 --- /dev/null +++ b/sdk/flutter/v4/receive-messages.mdx @@ -0,0 +1,1410 @@ +--- +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?* + +For every activity or fragment you wish to receive messages in, you need to register the `MessageListener` using the `addMessageListener()` method. + +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 MessageListener { + +//CometChat.addMessageListener("listenerId", this); + @override +void onTextMessageReceived(TextMessage textMessage) { + debugPrint("Text message received successfully: $textMessage"); +} + +@override +void onMediaMessageReceived(MediaMessage mediaMessage) { + debugPrint("Media message received successfully: $mediaMessage"); +} + +@override +void onCustomMessageReceived(CustomMessage customMessage) { + debugPrint("Custom message received successfully: $customMessage"); +} + +@override +onInteractiveMessageReceived(InteractiveMessage message) { + +} + + +} +``` + + + + + +| Parameter | Description | +| ---------- | ---------------------------------------------------------------------------------------------- | +| 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 +private String listenerID = "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 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 + +### For a Particular One-on-one Conversation + + + +```dart +int limit = 30; +int lastMessageId = -1; +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..limit = limit + ..messageId = lastMessageId + ).build(); + +messageRequest.fetchNext(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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 + + + +```dart +int limit = 30; +int lastMessageId = -1; +String GUID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..limit = limit + ..messageId = lastMessageId + ).build(); + +messageRequest.fetchNext(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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?* + +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` so that only the unread messages are fetched. + +### For a Particular One-on-one Conversation + + + +```dart +int limit = 30; +int lastMessageId = -1; +String GUID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..limit = limit + ..messageId = lastMessageId + ..unread = true + ).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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 + + + +```dart +int limit = 30; +int lastMessageId = -1; +String GUID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..limit = limit + ..messageId = lastMessageId + ..unread = true + ).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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`](/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. + + + +## Message History + +*In other words, as a logged-in user, how do I fetch the message history for a user or a group conversation?* + +### 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 of the builder. This UID is the unique id of the user for which the conversation needs to be fetched. + + + +```dart +int limit = 30; +int lastMessageId = -1; +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..limit = limit + ).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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 + +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 of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched. + + + +```dart +int limit = 30; +String GUID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..limit = limit + ).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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 + +In other words, as a logged-in user, how do I search a message? + +In order to do this, you can use the `searchKeyword` 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 | ❌ | ✅ | + +### For a Particular One-on-one Conversation + + + +```dart +int limit = 30; +int searchKeyword = "search keyboard"; +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..limit = limit + .searchKeyword=searchKeyword + ).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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 + + + +```dart +int limit = 30; +int searchKeyword = "search keyboard"; +String GUID = "cometchat-guid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..guid = GUID + ..limit = limit + .searchKeyword=searchKeyword + ).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + for (BaseMessage message in list) { + if(message is TextMessage){ + debugPrint("Text message received successfully: "+(message as TextMessage).toString()); + }else if(message is MediaMessage){ + debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); + } + } + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + + +**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?* + +### For 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: + + + +```dart +CometChat.getUnreadMessageCountForUser(String UID, Callbacks); +``` + + + + + +If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: + + + +```dart +CometChat.getUnreadMessageCountForUser(String UID, boolean hideMessagesFromBlockedUsers, Callbacks); +``` + + + + + + + +```dart +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 +} +}); +``` + + + + + +In the `onSuccess()` callback, you will receive a `Map` which will contain the `UID` of the user as the key and the unread message count as the value. + +### For 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: + + + +```dart +Map? ab = await CometChat.getUnreadMessageCountForGroup(guid: guid); +``` + + + + + +If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: + + + +```dart +Map? ab = await CometChat.getUnreadMessageCountForGroup(guid: guid,hideMessagesFromBlockedUsers: hideBlockedUser); +``` + + + + + + + +```dart +private String GUID = "cometchat-guid-1" + +CometChat.getUnreadMessageCountForGroup(guid: GUID,hideMessagesFromBlockedUsers: hideBlockedUser, + onSuccess: (Map map) { + + }, + onError: (CometChatException e) { + + }); +``` + + + + + +In the `onSuccess()` callback, you will receive a `Map` which will contain the `GUID` of the group as the key and the unread message count as the value. + +### For 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: + + + +```dart +await CometChat.getUnreadMessageCount(); +``` + + + + + +If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: + + + +```dart +await CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: true); +``` + + + + + + + +```dart +CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: hideBlockedUser, + onSuccess: (Map> map) { + + },onError: (CometChatException e) { + + }); +``` + + + + + +In the `onSuccess()` callback, you will receive a `Map` having two keys: + +1. `user` - The value for this key holds another `Map` that holds the `UIDs` of users and their corresponding unread message counts. +2. `group` - The value for this key holds another `Map` that holds the `GUIDs` of groups and their corresponding unread message counts. + +### For Unread Count for 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: + + + +```dart +await CometChat.getUnreadMessageCountForAllUsers(); +``` + + + + + +If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: + + + +```dart +await CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: true); +``` + + + + + + + +```dart +CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers, + onSuccess: (Map map) { + + }, + onError: (CometChatException e) { + + }); +``` + + + + + +In the `onSuccess()` callback, you will receive a `Map` that will contain the `UIDs` of users as the key and the unread message counts as the values. + +### Fetch Unread Count for all Group Conversations + +*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: + + + +```dart +await CometChat.getUnreadMessageCountForAllGroups(); +``` + + + + + +If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: + + + +```dart +await CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: true); +``` + + + + + + + +```dart +CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers, + onSuccess: (Map map) { + + }, + onError: (CometChatException e) { + + }); +``` + + + + + +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/v4/retrieve-conversations.mdx b/sdk/flutter/v4/retrieve-conversations.mdx new file mode 100644 index 000000000..cb43d8cc9 --- /dev/null +++ b/sdk/flutter/v4/retrieve-conversations.mdx @@ -0,0 +1,864 @@ +--- +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. + +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 + +Set the number of conversations to fetch per request. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 +).build(); +``` + + + + +The default value for `limit` is 30 and the max value is 50. + + +### Set Conversation Type + +Filter by conversation type: `user` for one-on-one or `group` for group conversations. If not set, both types are returned. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..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 + +Use `withUserAndGroupTags = true` to include user/group tags in the `Conversation` object. Default is `false`. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..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 + +Use `withTags = true` to include conversation tags in the response. Default is `false`. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..withTags = true +).build(); +``` + + + +### Set Tags + +Fetch conversations that have specific tags. + + + +```dart +List tags = []; +tags.add("archived"); +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..tags = tags +).build(); +``` + + + +### Include Blocked Users + +Use `includeBlockedUsers = true` to include conversations with users you've blocked. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..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 + +Use `withBlockedInfo = true` to include blocked user information in the response. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..withBlockedInfo = true +).build(); +``` + + + +### Search Conversations + +Use `searchKeyword` to 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) + + + + + +```dart + ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..searchKeyword = "Hiking" + ).build(); +``` + + + +When conversations are fetched successfully, the response includes conversations where the user or group name matches the search keyword. + +### Unread Conversations + +Use `unread = true` to fetch only conversations with unread messages. + + + +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 + ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ..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(); +``` + + + + +`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. + +### 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. + + + +```dart +ConversationsRequest conversationRequest = (ConversationsRequestBuilder() + ..limit = 50 + ).build(); + +conversationRequest.fetchNext( + onSuccess: (List conversations){ + + + }, onError: (CometChatException e){ + + }); +``` + + + + +**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 | +| --------------------- | -------------------------------------------------------------------- | +| `conversationId` | ID of the conversation | +| `conversationType` | Type of conversation (user/group) | +| `lastMessage` | Last message the conversation | +| `conversationWith` | `User` or `Group` object containing the details of the user or group | +| `unreadMessageCount` | Unread message count for the conversation | +| `unreadMentionsCount` | the count of unread mentions in the conversation. | +| `lastReadMessageId` | the ID of the last read message in the conversation. | + +## Tag Conversation + +*In other words, as a logged-in user, how do I tag a conversation?* + +Use `tagConversation()` to add tags to a conversation. + +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | +| `tags` | Array of tags to add | + + + +```dart +String conversationWith = "cometchat-uid-1"; //id of the user/group +String conversationType = "user"; +List tags = []; +tags.add("archived"); + +CometChat.tagConversation(conversationWith, conversationType, tags, + onSuccess: (Conversation conversation) { + debugPrint("Conversation tagged Successfully : $conversation"); + }, onError: (CometChatException e) { + debugPrint("Conversation tagging failed : ${e.message}"); + } +); +``` + + + + +**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. + + + +## Retrieve Single Conversation + +*In other words, as a logged-in user, how do I retrieve a specific conversation?* + +Use `getConversation()` to fetch a specific conversation. + +| Parameter | Description | +| --- | --- | +| `conversationWith` | UID or GUID of the user/group | +| `conversationType` | `user` or `group` | + + + +```dart +String conversationWith = "cometchat-uid-1"; //id of the user/group +String conversationType = "user"; +CometChat.getConversation(conversationWith, conversationType, + onSuccess: (Conversation conversation) { + debugPrint("Fetch Conversation Successfully : $conversation"); + }, onError: (CometChatException e) { + debugPrint("Fetch Conversation failed : ${e.message}"); + } +); +``` + + + + +**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. + + + +```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. + + +--- + +## 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/v4/retrieve-group-members.mdx b/sdk/flutter/v4/retrieve-group-members.mdx new file mode 100644 index 000000000..1eaa8a1ba --- /dev/null +++ b/sdk/flutter/v4/retrieve-group-members.mdx @@ -0,0 +1,222 @@ +--- +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. + + +**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. + + + +```dart +String GUID = "GUID"; + GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) + ..limit = 20 + ).build(); +``` + + + + + +### Set Search Keyword + +This method allows you to set the search string based on which the group members are to be fetched. + + + +```dart +String GUID = "GUID"; +GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) + ..limit = 20 + ..searchKeyword = "abc" + ).build(); +``` + + + + + +### Set Scopes + +This method allows you to fetch group members based on the specified scopes. + + + +```dart +List scopes =[]; +scopes.add("admin"); +scopes.add("moderator"); +String GUID = "GUID"; +GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) + ..limit = 20 + ..scopes = scopes + ).build(); +``` + + + + + +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. + + + +```dart +String GUID = "GUID"; +GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) + ..limit = 20 + ).build(); + +groupMembersRequest.fetchNext(onSuccess: (List groupMemberList){ + debugPrint("Group Members fetched Successfully : $groupMemberList "); + }, onError: (CometChatException e) { + debugPrint("Delete Group failed with exception: ${e.message}"); + }); +``` + + + + + +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/v4/retrieve-groups.mdx b/sdk/flutter/v4/retrieve-groups.mdx new file mode 100644 index 000000000..d5182cea2 --- /dev/null +++ b/sdk/flutter/v4/retrieve-groups.mdx @@ -0,0 +1,346 @@ +--- +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 + +*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* + +In order to fetch the list of groups, you can use the `GroupsRequest` class. To use this class i.e to create an object of the `GroupsRequest` class, you need to use the `GroupsRequestBuilder` class. The `GroupsRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. + +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 + +Sets the number of groups to fetch per request. + + + +```dart +GroupsRequest groupsRequest = (GroupsRequestBuilder() + ..limit= 20 +).build(); +``` + + + + + +### Set Search Keyword + +Filters groups by a search string. + + + +```dart +GroupsRequest groupsRequest = (GroupsRequestBuilder() + ..limit= 20 + ..searchKeyword = "abc" +).build(); +``` + + + + + +### Joined Only + +When `true`, returns only groups the logged-in user has joined or is a part of. + + + +```dart +GroupsRequest groupsRequest = (GroupsRequestBuilder() + ..limit= 20 + ..joinedOnly = true +).build(); +``` + + + + + +### Set Tags + +Filters groups by specified tags. The list fetched will only contain the groups that have been tagged with the specified tags. + + + +```dart +List tags =[]; +tags.add("archived"); +GroupsRequest groupsRequest = (GroupsRequestBuilder() + ..limit= 20 + ..tags = tags +).build(); +``` + + + + + +### With Tags + +When `true`, includes tag data in the returned group objects. + + + +```dart +GroupsRequest groupsRequest = (GroupsRequestBuilder() + ..limit= 20 + ..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. + +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. + + + +```dart +GroupsRequest groupsRequest = (GroupsRequestBuilder() + ..limit= 20 +).build(); + +groupsRequest.fetchNext(onSuccess: (List groupList) { + debugPrint("Fetched Group Successfully : $groupList "); + }, onError: (CometChatException e) { + debugPrint("Group Request failed with exception: ${e.message}"); + }); +``` + + + + + + +**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?* + +To get the information of a group, you can use the `getGroup()` method. + + + +```dart +String GUID = "GUID"; + +CometChat.getGroup(GUID, onSuccess: (Group group) { + debugPrint("Fetched Group Successfully : $group "); + }, onError: (CometChatException e) { + debugPrint("Group Request failed with exception: ${e.message}"); + }); +``` + + + + + +| Parameter | Description | +| --------- | ------------------------------------------------------------ | +| `GUID` | The GUID of the group for whom the details are to be fetched | + +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 + +To get the total count of online users in particular groups, you can use the `getOnlineGroupMemberCount()` method. + + + +```dart +List guids = []; +guids.add("cometchat-guid-1"); +guids.add("cometchat-guid-11"); + +CometChat.getOnlineGroupMemberCount(guids, + onSuccess: (Map count) { + debugPrint("Fetched Online Group Member Count Successfully : $count "); + }, onError: (CometChatException e) { + debugPrint("Online Group Member failed with exception: ${e.message}"); + }); +``` + + + + + +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/v4/retrieve-users.mdx b/sdk/flutter/v4/retrieve-users.mdx new file mode 100644 index 000000000..1331d8932 --- /dev/null +++ b/sdk/flutter/v4/retrieve-users.mdx @@ -0,0 +1,453 @@ +--- +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 + +Use `getLoggedInUser()` to get the current user's details. Returns `null` if no user is logged in. + + + +```dart +User? user = await CometChat.getLoggedInUser(); +``` + + + +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. + +### 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 + +Sets the number of users to fetch per request. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ).build(); +``` + + + +### Set Search Keyword + +Filters users by a search string. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..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 + +Filters users by online status: + +- `CometChatUserStatus.online` — Only online users +- `CometChatUserStatus.offline` — Only offline users + +If not set, returns all users. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..userStatus = CometChatUserStatus.online + ).build(); +``` + + + +### Hide Blocked Users + +When `true`, excludes users blocked by the logged-in user from the results. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..hideBlockedUsers = true + ).build(); +``` + + + +### Set Roles + +Filters users by specified roles. + + + +```dart +List roles = []; +roles.add("role1"); +roles.add("role2"); +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..roles = roles + ).build(); +``` + + + +### Friends Only + +When `true`, returns only friends of the logged-in user. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..friendsOnly = true + ).build(); +``` + + + +### Set Tags + +Filters users by specified tags. + + + +```dart +List tags = []; +tags.add("tag1"); +tags.add("tag2"); +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..tags = tags + ).build(); +``` + + + +### With Tags + +When `true`, includes tag data in the returned user objects. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 50 + ..withTags = true + ).build(); +``` + + + +### Set UIDs + +Fetches specific users by their UIDs. Maximum 25 users per request. + + + +```dart +List uids = []; +uids.add("UID1"); +uids.add("UID2"); +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 25 + ..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(); +``` + + + +### Sort By Order + +Sets the sort order. Default is ascending (`"asc"`). Use `"desc"` for descending. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 30 + ..sortByOrder = "desc" + ).build(); +``` + + + +After configuring the builder, call `build()` to get the `UsersRequest` object, then call `fetchNext()` to retrieve users. + + + +```dart +UsersRequest usersRequest = (UsersRequestBuilder() + ..limit = 25 + ).build(); + +usersRequest.fetchNext(onSuccess: (List userList){ + debugPrint("User List Fetched Successfully : $userList"); + },onError: (CometChatException e){ + 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 + +Use `getUser()` to fetch a specific user's details by UID. + + + +```dart +String UID = "UID"; + +CometChat.getUser(UID, onSuccess: (User user){ + debugPrint("User Fetched Successfully : $user"); + }, onError: (CometChatException e){ + debugPrint("User Fetch Failed: ${e.message}"); + }); +``` + + + +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 `User` object containing the details of the user is returned. + + +**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` | + + + + + +| 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. + + + +```dart +CometChat.getOnlineUserCount(onSuccess: (int count){ + debugPrint("Online User Count: $count"); + }, onError: (CometChatException e){ + 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/v4/send-message.mdx b/sdk/flutter/v4/send-message.mdx new file mode 100644 index 000000000..57cc58dfa --- /dev/null +++ b/sdk/flutter/v4/send-message.mdx @@ -0,0 +1,1264 @@ +--- +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 | + +```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 | + +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. + +## 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`](/sdk/reference/messages#textmessage) object to it. + +### Add Metadata + +To send custom data along with a text message, you can use the `setMetadata` method and pass a `Map` to it. + + + +```dart +Map metadata = {}; +metadata["lattitude"] = "50.6192171633316" ; +metadata["longitude"] = "-72.68182268750002" ; +textMessage.metadata = metadata; +``` + + + + + +### Add Tags + +To add a tag to a message you can assign value in `.tags` variable of the TextMessage Class. `tags` accepts a list of tags. + + + +```dart +List tags = []; +tags.add("pinned"); +textMessage.tags = tags; +``` + + + + + +Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. + + + +```dart +String receiverID = "cometchat-uid-1"; +String messageText = "messageText"; +String receiverType = CometChatConversationType.user; +String type = CometChatMessageType.text; + +TextMessage textMessage = TextMessage(text: messageText, + receiverUid: receiverID, + receiverType: receiverType, + type: type); +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 = "cometchat-guid-1"; +String messageText = "messageText"; +String receiverType = CometChatConversationType.group; +String type = CometChatMessageType.text; + +TextMessage textMessage = TextMessage(text: messageText, + receiverUid: receiverID, + receiverType: receiverType, + type: type); +CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) { +debugPrint("Message sent successfully: $message"); +}, onError: (CometChatException e) { +debugPrint("Message sending failed with exception: ${e.message}"); +}); +``` + + + + + +The `TextMessage` class constructor takes the following parameters: + +| Parameter | Description | | +| -------------- | -------------------------------------------------------------------------------------------------------------- | -------- | +| `receiverID` | `UID` of the user or `GUID` of the group receiving the message | Required | +| `messageText` | The text message | Required | +| `receiverType` | The type of the receiver- `CometChatReceiverType.user` (user) or `CometChatReceiverType.group` (group) | Required | +| type | The type of the message that needs to be sent which in this case can be: `CometChatMessageType.text`\_\_(text) | | + +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. + + + + +```dart +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. + + + +```dart +String receiverID = "UID"; +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; +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}"); + }, +); +``` + + + + + +The `TextMessage` class constructor takes the following parameters: + +| Parameter | Description | | +| -------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------- | +| `receiverID` | `UID` of the user or `GUID` of the group receiving the message | Required | +| `messageText` | The text message | Required | +| `receiverType` | The type of the receiver- `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`](/sdk/reference/messages#mediamessage) object to it. + +### Add Metadata + +To send custom data along with a media message, you can use the `setMetadata` method and pass a `Map` to it. + + + +```dart +Map metadata = {}; +metadata["lattitude"] = "50.6192171633316" ; +metadata["longitude"] = "-72.68182268750002" ; +mediaMessage.metadata = metadata; +``` + + + + + +### Add Caption(Text along with Media Message) + + + +```dart +mediaMessage.caption = "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. + + + +```dart +List tags = []; +tags.add("pinned"); +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 = "cometchat-uid-1"; +String messageType = CometChatMessageType.image; +String receiverType = CometChatConversationType.user; +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}"); + } +); +``` + + + + +```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}"); + } +); +``` + + + + + +The `MediaMessage` class constructor takes the following parameters: + +| Parameter | Description | | +| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | +| receiverId | The UID or GUID of the recipient | Required | +| file | The file object to be sent | Required | +| messageType | The type of the message that needs to be sent which, in this case, can be:
1. `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 | + + +**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, + 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}"); + } +); +``` + + + + +```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}"); + } +); +``` + + + + + +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 + +*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`](/sdk/reference/messages#custommessage) which can be obtained using the below constructor. + + + +```dart +CustomMessage customMessage = CustomMessage( receiverUid: UID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, + ); +``` + + + + + +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 `CustomMessage` class constructor takes the following parameters: + +| 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. + + + +```dart +List tags = []; +tags.add("pinned"); +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. + + + +```dart +String UID = "UID"; +String subType = "LOCATION"; +String receiverType = CometChatConversationType.user; +String type = CometChatMessageType.custom; + +Map customData = {}; +customData["latitude"] = "19.0760"; +customData["longitude"] = "72.8777"; + +CustomMessage customMessage = CustomMessage( + receiverUid: UID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, +); + +CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { + debugPrint("Custom Message Sent Successfully : $message"); +}, onError: (CometChatException e) { + debugPrint("Custom message sending failed with exception: ${e.message}"); +}); +``` + + + + +```dart +String GUID = "GUID"; +String subType = "LOCATION"; +String receiverType = CometChatConversationType.group; +String type = CometChatMessageType.custom; + +Map customData = {}; +customData["latitude"] = "19.0760"; +customData["longitude"] = "72.8777"; + +CustomMessage customMessage = CustomMessage( + receiverUid: GUID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, +); + +CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { + debugPrint("Custom Message Sent Successfully : $message"); +}, onError: (CometChatException e) { + debugPrint("Custom message sending failed with exception: ${e.message}"); +}); +``` + + + + + +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. + + +**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?* + +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 `updateConversation` (boolean value) method of the Custom Message. + + + +```dart +String UID = "UID"; +String subType = "LOCATION"; +String receiverType = CometChatConversationType.user; +String type = CometChatMessageType.custom; + +Map customData = {}; +customData["latitude"] = "19.0760"; +customData["longitude"] = "72.8777"; + +CustomMessage customMessage = CustomMessage( + receiverUid: UID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, +); +customMessage.updateConversation = false; + +CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { + debugPrint("Custom Message Sent Successfully : $message"); +}, onError: (CometChatException e) { + debugPrint("Custom message sending failed with exception: ${e.message}"); +}); +``` + + + + +```dart +String GUID = "GUID"; +String subType = "LOCATION"; +String receiverType = CometChatConversationType.group; +String type = CometChatMessageType.custom; + +Map customData = {}; +customData["latitude"] = "19.0760"; +customData["longitude"] = "72.8777"; + +CustomMessage customMessage = CustomMessage( + receiverUid: GUID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, +); +customMessage.updateConversation = false; + +CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { + debugPrint("Custom Message Sent Successfully : $message"); +}, onError: (CometChatException e) { + debugPrint("Custom message sending failed with exception: ${e.message}"); +}); +``` + + + + + +### 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` method of Custom Message class. + + + +```dart +String UID = "UID"; +String subType = "LOCATION"; +String receiverType = CometChatConversationType.user; +String type = CometChatMessageType.custom; + +Map customData = {}; +customData["latitude"] = "19.0760"; +customData["longitude"] = "72.8777"; + +CustomMessage customMessage = CustomMessage( + receiverUid: UID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, +); +customMessage.conversationText = "Custom Notification Body"; + +CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { + debugPrint("Custom Message Sent Successfully : $message"); +}, onError: (CometChatException e) { + debugPrint("Custom message sending failed with exception: ${e.message}"); +}); +``` + + + + +```dart +String GUID = "GUID"; +String subType = "LOCATION"; +String receiverType = CometChatConversationType.group; +String type = CometChatMessageType.custom; + +Map customData = {}; +customData["latitude"] = "19.0760"; +customData["longitude"] = "72.8777"; + +CustomMessage customMessage = CustomMessage( + receiverUid: GUID, + type: type, + customData: customData, + receiverType: receiverType, + subType: subType, +); +customMessage.conversationText = "Custom Notification Body"; + +CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { + debugPrint("Custom Message Sent Successfully : $message"); +}, onError: (CometChatException e) { + debugPrint("Custom message sending failed with exception: ${e.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/v4/setup.mdx b/sdk/flutter/v4/setup.mdx new file mode 100644 index 000000000..877c9e0e6 --- /dev/null +++ b/sdk/flutter/v4/setup.mdx @@ -0,0 +1,246 @@ +--- +title: "Setup" +sidebarTitle: "Setup" +description: "Install, configure, and initialize the CometChat Flutter SDK in your application." +--- + +{/* TL;DR for Agents and Quick Reference */} + + +```yaml +# Install (pubspec.yaml) +cometchat_sdk: ^4.0.33 +``` + +```dart +import 'package:cometchat_sdk/cometchat_sdk.dart'; + +AppSettings appSettings = (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region = "APP_REGION" + ..autoEstablishSocketConnection = true +).build(); + +CometChat.init("APP_ID", appSettings, + onSuccess: (msg) => debugPrint("Init success"), + onError: (e) => debugPrint("Init failed: ${e.message}") +); + +// 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** + + +**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. + + +## Installation + +Add the following dependency to your `pubspec.yaml` file and run `pub get`: + + + +```yaml +cometchat_sdk: ^4.0.33 +``` + + + +### iOS Setup + +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) + +//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 +``` + + + + +**Apple Silicon (M1/M2/M3) users:** Excluding `arm64` from the simulator build prevents the app from running natively on Apple Silicon Macs. If you are developing on an Apple Silicon Mac, consider excluding only `i386` instead of `arm64 i386` to enable native simulator builds. + + +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 the SDK + + + + +```dart +import 'package:cometchat_sdk/cometchat_sdk.dart'; +``` + + + +## Initialization + +The `init()` method initializes the SDK and must be called before any other CometChat method. Call it once at app startup, typically in your root widget's `initState()` or `main()` function. + + + +```dart +String region = "APP_REGION"; +String appId = "APP_ID"; + +AppSettings appSettings= (AppSettingsBuilder() + ..subscriptionType = CometChatSubscriptionType.allUsers + ..region= region + ..adminHost = "" //optional + ..clientHost = "" //optional + ..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}"); + } +); +``` + + + +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: + +| 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."` | + + +### WebSocket Connection + +By default, the SDK manages WebSocket connections automatically. To manage them manually: + +```dart +AppSettings appSettings = (AppSettingsBuilder() + ..region = region + ..autoEstablishSocketConnection = false +).build(); +``` + +See [Connection Behaviour](/sdk/flutter/connection-behaviour) for manual control. + +--- + +## Next Steps + + + + Log in users with Auth Key or Auth Token + + + Send your first message + + diff --git a/sdk/flutter/v4/threaded-messages.mdx b/sdk/flutter/v4/threaded-messages.mdx new file mode 100644 index 000000000..d2b1e40f9 --- /dev/null +++ b/sdk/flutter/v4/threaded-messages.mdx @@ -0,0 +1,536 @@ +--- +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 | + +```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 + +As mentioned in the [Send a Message](send-message) section, you can send a message to a User or a Group by mentioning the receiver (uid/guid) and `receiverType`(user/group). + +A message can be categorized as: + +1. Text Message +2. Media Message +3. Custom Message +4. Interactive Message + +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. + + + + +```dart +String receiverID = "UID"; +String messagesText = "Hello"; +String receiverType = CometChatConversationType.user; +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"); +}, 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"); +}, onError: (CometChatException e) { + 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) 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"); +``` + + + + +```dart +class Class_Name with MessageListener { + int activeParentMessageId= 103; +//CometChat.addMessageListener("listenerId", this); + @override +void onTextMessageReceived(TextMessage textMessage) { + if(textMessage.parentMessageId == activeParentMessageId){ + debugPrint("Text message received successfully: $textMessage"); + } + +} + +@override +void onMediaMessageReceived(MediaMessage mediaMessage) { + if(mediaMessage.parentMessageId== activeParentMessageId){ + debugPrint("Media message received successfully: $mediaMessage"); + } +} + +@override +void onCustomMessageReceived(CustomMessage customMessage) { + if(customMessage.parentMessageId== activeParentMessageId){ + debugPrint("Custom message received successfully: $customMessage"); + } +} +} +``` + + + + +### Fetch all the messages for any particular thread. + +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. + + +`MessagesRequestBuilder` Parameters: + +| 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 | + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..parentMessageId = 103 + ..limit = 50).build(); + +messageRequest.fetchPrevious(onSuccess: (List list) { + debugPrint("Message fetching Successful"); + }, onError: (CometChatException e) { + debugPrint("Message fetching failed with exception: ${e.message}"); + }); +``` + + + + + +**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. Use `hideReplies = true` on the `MessagesRequestBuilder` to exclude threaded messages from the list. + + + +```dart +String UID = "cometchat-uid-1"; + +MessagesRequest messageRequest = (MessagesRequestBuilder() + ..uid = UID + ..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}"); + }); +``` + + + + +```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}"); + }); +``` + + + + + + +**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/v4/transfer-group-ownership.mdx b/sdk/flutter/v4/transfer-group-ownership.mdx new file mode 100644 index 000000000..d5c67b622 --- /dev/null +++ b/sdk/flutter/v4/transfer-group-ownership.mdx @@ -0,0 +1,95 @@ +--- +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. + + +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). + +## Transfer Ownership + +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) + + + + +```dart +String UID = "cometchat-uid-1"; +String GUID = conversationWith; +CometChat.transferGroupOwnership(guid: GUID,uid: UID, + onSuccess: (String message) { + debugPrint("Owner Transferred Successfully : $message"); + }, + onError: (CometChatException e) { + debugPrint("Owner Transferred failed : ${e.message}"); + }); +``` + + + + + +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/v4/transient-messages.mdx b/sdk/flutter/v4/transient-messages.mdx new file mode 100644 index 000000000..9b7654664 --- /dev/null +++ b/sdk/flutter/v4/transient-messages.mdx @@ -0,0 +1,167 @@ +--- +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`](/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}"); +}); +``` + + + + +```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}"); +}); +``` + + + + + +`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. + + + +```dart +class Class_Name with MessageListener { + +//CometChat.addMessageListener("listenerId", this); +@override +void onTransientMessageReceived(TransientMessage message) { + // TODO: implement onTransientMessageReceived +} + + +} +``` + + + + + +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 + + + + 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/v4/troubleshooting.mdx similarity index 100% rename from sdk/flutter/troubleshooting.mdx rename to sdk/flutter/v4/troubleshooting.mdx diff --git a/sdk/flutter/v4/typing-indicators.mdx b/sdk/flutter/v4/typing-indicators.mdx new file mode 100644 index 000000000..19640d53d --- /dev/null +++ b/sdk/flutter/v4/typing-indicators.mdx @@ -0,0 +1,181 @@ +--- +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 + +*In other words, as a sender, how do I let the recipient(s) know that I'm typing?* + +### Start Typing + +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( + receiverUid: "UID", + receiverType: CometChatReceiverType.user, +); +``` + + + + +```dart +CometChat.startTyping( + 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 + +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( + receiverUid: "UID", + receiverType: CometChatReceiverType.user, +); +``` + + + + +```dart +CometChat.endTyping( + receiverUid: "GUID", + receiverType: CometChatReceiverType.group, +); +``` + + + + + +`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 | + +`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?* + +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"); +``` + + + + +```dart +class Class_Name with MessageListener { + +//CometChat.addMessageListener("listenerId", this); +@override +void onTypingStarted(TypingIndicator typingIndicator) { + // TODO: implement onTypingStarted +} + +@override +void onTypingEnded(TypingIndicator typingIndicator) { + // TODO: implement onTypingEnded +} + + +} +``` + + + + + +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 + + + + Track message delivery and read status + + + Send ephemeral real-time messages like live reactions + + diff --git a/sdk/flutter/v4/update-group.mdx b/sdk/flutter/v4/update-group.mdx new file mode 100644 index 000000000..8371e41af --- /dev/null +++ b/sdk/flutter/v4/update-group.mdx @@ -0,0 +1,128 @@ +--- +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. 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 | + + + +```dart +String GUID = "GUID"; + String groupName = "Hello Group!"; + String groupType = CometChatGroupType.public; + String password = ""; + + Group _group = Group(guid: GUID, name: groupName, type: groupType); + + + await CometChat.updateGroup(group: _group, onSuccess: (Group group ){ + debugPrint("Group Created Successfully : $group "); + }, onError:(CometChatException e) { + debugPrint("Group Creation failed with exception: ${e.message}"); + } ); +``` + + + + + + +**On Success** — A `Group` object containing all details of the updated 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 | `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). + + +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/v4/upgrading-from-v3-guide.mdx similarity index 100% rename from sdk/flutter/upgrading-from-v3-guide.mdx rename to sdk/flutter/v4/upgrading-from-v3-guide.mdx diff --git a/sdk/flutter/v4/user-management.mdx b/sdk/flutter/v4/user-management.mdx new file mode 100644 index 000000000..95622f92c --- /dev/null +++ b/sdk/flutter/v4/user-management.mdx @@ -0,0 +1,282 @@ +--- +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}"); +}); +``` + +**Note:** User creation/deletion should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com). + + +Users must exist in CometChat before they can log in. This page covers creating, updating, and deleting users. All methods that return user data return a [`User`](/sdk/reference/entities#user) object. + +The typical flow: +1. User registers in your app → Create user in CometChat +2. User logs into your app → [Log user into CometChat](/sdk/flutter/authentication-overview) + + +User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-user) — there is no client-side SDK method for it. + + +## Creating a User + +User creation should ideally happen on your backend via the [REST API](https://api-explorer.cometchat.com/reference/creates-user). + + +**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 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 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 + +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. + + +**On Success** — A `User` object containing all details of the updated user: + +| 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` | + + + + +| 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}"); +}); +``` + + + +### 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 + +User deletion is only available via the [REST API](https://api-explorer.cometchat.com/reference/delete-user). + +## User Class + +| Field | Editable | Information | +| ------------- | --------------------------------------------------- | -------------------------------------------------------------------- | +| uid | specified on user creation. Not editable after that | Unique identifier of the user | +| name | Yes | Display name of the user | +| avatar | Yes | URL to profile picture of the user | +| link | Yes | URL to profile page | +| role | Yes | User role of the user for role based access control | +| metadata | Yes | Additional information about the user as JSON | +| status | No | Status of the user. Could be either online/offline | +| 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 | +| 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/v4/user-presence.mdx b/sdk/flutter/v4/user-presence.mdx new file mode 100644 index 000000000..c1f0fecea --- /dev/null +++ b/sdk/flutter/v4/user-presence.mdx @@ -0,0 +1,152 @@ +--- +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"); +``` + + +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?* + +Configure presence subscription in `AppSettings` during SDK initialization. The `AppSettingsBuilder` provides three subscription options: + +| 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 | + +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/flutter/setup) for details. + + +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. + + + +```dart +class Class_Name with UserListener { + +//CometChat.addUserListener("user_Listener_id", this); + @override +void onUserOnline(User user) { + // TODO: implement onUserOnline +} +@override +void onUserOffline(User user) { + // TODO: implement onUserOffline +} + + +} +``` + + + + + +| Parameter | Description | +| ------------ | ----------------------------------------------------------------------------------------------- | +| `listenerID` | An ID that uniquely identifies that listener. We recommend using the activity or fragment name. | + +### 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. + +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: + + + +```dart +String listenerID = "UNIQUE_LISTENER_ID"; + +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) 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 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/v4/users-overview.mdx b/sdk/flutter/v4/users-overview.mdx new file mode 100644 index 000000000..32e83bbb2 --- /dev/null +++ b/sdk/flutter/v4/users-overview.mdx @@ -0,0 +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 + + +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/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/v4/webhooks-overview.mdx b/sdk/flutter/v4/webhooks-overview.mdx new file mode 100644 index 000000000..d52007a59 --- /dev/null +++ b/sdk/flutter/v4/webhooks-overview.mdx @@ -0,0 +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" +--- + + + +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/flutter/v5/additional-message-filtering.mdx b/sdk/flutter/v5/additional-message-filtering.mdx deleted file mode 100644 index 1d9687d68..000000000 --- a/sdk/flutter/v5/additional-message-filtering.mdx +++ /dev/null @@ -1,598 +0,0 @@ ---- -title: "Additional Message Filtering" ---- - - - -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: - -## 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`. The default limit is `30`. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..limit = 30).build(); -``` - - - - - -## Direct Page Navigation - -*In other words, how do I jump to a specific page of messages* - -You can use the `setPage()` method to directly navigate to a specific page of messages. This enables direct page navigation and improved data handling in paginated responses. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..limit = 30 - ..page = 2).build(); -``` - - - - - -## Messages for a user conversation - -*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. - - - -```dart -String UID = "cometchat-uid-1"; -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..limit = 50).build(); -``` - - - - - -## Messages for a group conversation - -*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. - - - -```dart -String GUID = "cometchat-uid-1"; -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..guid = GUID - ..limit = 50).build(); -``` - - - - - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..messageId = 50 - ..limit = 50).build(); -``` - - - - - -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. - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..timestamp = DateTime.now() - ..limit = 50).build(); -``` - - - - - -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. - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..unread = true - ..limit = 50).build(); -``` - - - - - -This method along with `GUID` or `UID` 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` 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..hideMessagesFromBlockedUsers = true - ..limit = 50).build(); -``` - - - - - -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. - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..updatedAfter = DateTime.now() - ..limit = 50).build(); -``` - - - - - -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. - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..updatedAfter = DateTime.now() - ..updatesOnly = true - ..limit = 50).build(); -``` - - - - - -## 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](/sdk/flutter/v5/messaging-overview#message-structure-and-hierarchy) guide 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. - - - -```dart -String UID = "cometchat-uid-1"; -List categories = []; -categories.add("message"); -categories.add("custom"); - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..categories = categories - ..limit = 50).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 `UID` and GUID 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 you refer to the [Message Structure and Hierarchy](/sdk/flutter/v5/messaging-overview#message-structure-and-hierarchy) guide 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. - - - -```dart -String UID = "cometchat-uid-1"; -List types = []; -types.add("image"); -types.add("video"); - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..types = types - ..limit = 50).build(); -``` - - - - - -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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..parentMessageId = 103 - ..limit = 50).build(); -``` - - - - - -The above code snippet returns the messages that belong to the thread with parent id 103. - -## 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` 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..hideReplies = true - ..limit = 50).build(); -``` - - - - - -## 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 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..hideDeleted = 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. - - - -```dart -String UID = "cometchat-uid-1"; -List tags = []; -tags.add("tag1"); -tags.add("tag2"); - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..tags = tags - ..limit = 50).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` 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` . - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ...withTags = true - ..limit = 50).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 `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`. - - - -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 - ..hasLinks = true - ..limit = 50).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 `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`. - - - -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 - ..hasAttachments = true - ..limit = 50).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 `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`. - - - -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 - ..hasReactions = true - ..limit = 50).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 `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`. - - - -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 - ..hasMentions = true - ..limit = 50).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 `mentionedUids` parameter. This parameter accepts a list of UIDs. 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) - - - - - -```dart -String UID = "cometchat-uid-1"; -List mentionedUIDs = []; -tags.add("cometchat-uid-1"); -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..mentionedUids = mentionedUIDs - ..limit = 50).build(); -``` - - - - - - -## Messages by attachment types - -*In other words, how do I fetch messages with specific attachment types* - -In order to do this, you can use the `attachmentTypes` parameter. This parameter accepts a list of attachment types. This tells the SDK to fetch messages only with the specified attachment types. - - - -```dart -String UID = "cometchat-uid-1"; -List attachmentTypes = []; -attachmentTypes.add("image"); -attachmentTypes.add("video"); - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..attachmentTypes = attachmentTypes - ..limit = 50).build(); -``` - - - - - -The available attachment types are: -- `image` - Image attachments -- `video` - Video attachments -- `audio` - Audio attachments -- `file` - File/document attachments - -## Hide quoted messages - -*In other words, how do I exclude quoted messages from the response* - -In order to do this, you can use the `hideQuotedMessages` parameter. This parameter accepts boolean as input. When set to `true`, the SDK will not include the quoted message object in the response. The default value for this parameter is `false`. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..hideQuotedMessages = true - ..limit = 50).build(); -``` - - - - - -This can be useful when you want to reduce the payload size and don't need the full quoted message details in the response. diff --git a/sdk/flutter/v5/ai-agents.mdx b/sdk/flutter/v5/ai-agents.mdx deleted file mode 100644 index 1ee853823..000000000 --- a/sdk/flutter/v5/ai-agents.mdx +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: "AI Agents" ---- - -# 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**. - -## 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`**. - -### 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. - - - - ```dart -import 'package:flutter/foundation.dart'; -import 'package:cometchat_sdk/cometchat_sdk.dart'; - -class AIAssistantEventHandler with AIAssistantListener { - final String _sdkStreamListenerId = "unique_listener_id"; - - /// Call this to start listening to AI Assistant events - void addListener() { - CometChat.addAIAssistantListener(_sdkStreamListenerId, this); - debugPrint("AIAssistantListener added successfully."); - } - - /// Call this to remove the AI Assistant listener - void removeListener() { - CometChat.removeAIAssistantListener(_sdkStreamListenerId); - debugPrint("AIAssistantListener removed successfully."); - } - - @override - void onAIAssistantEventReceived(AIAssistantBaseEvent aiAssistantBaseEvent) { - debugPrint( - "Received AI Event: ${aiAssistantBaseEvent.type} for Run ID: ${aiAssistantBaseEvent.id}", - ); - } -} - ``` - - - -#### 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. - - - - ```dart - const listenerId = "unique_listener_id"; - - class Class_Name with MessageListener { - // Adding the MessageListener - // CometChat.addMessageListener(listenerId, this); - @override - void onAIAssistantMessageReceived(AIAssistantMessage aiAssistantMessage) { - debugPrint("AI Assistant Message Received: ${aiAssistantMessage.toString()}"); - } - - @override - void onAIToolResultReceived(AIToolResultMessage aiToolArgumentMessage) { - debugPrint("AI Assistant Message Received: ${aiToolArgumentMessage.toString()}"); - } - - @override - void onAIToolArgumentsReceived(AIToolArgumentMessage aiToolArgumentMessage) { - debugPrint("AI Assistant Message Received: ${aiToolArgumentMessage.toString()}"); - } - } - ``` - - \ No newline at end of file diff --git a/sdk/flutter/v5/ai-chatbots-overview.mdx b/sdk/flutter/v5/ai-chatbots-overview.mdx deleted file mode 100644 index 7a460169b..000000000 --- a/sdk/flutter/v5/ai-chatbots-overview.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: "Bots" -url: "/ai-chatbots/overview" ---- diff --git a/sdk/flutter/v5/ai-moderation.mdx b/sdk/flutter/v5/ai-moderation.mdx deleted file mode 100644 index e0414eb82..000000000 --- a/sdk/flutter/v5/ai-moderation.mdx +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: "AI Moderation" ---- - -## 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. - - -For a broader understanding of moderation features, configuring rules, and managing flagged messages, 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 - -## How It Works - -```mermaid -sequenceDiagram - participant App - participant SDK - participant CometChat - participant Moderation - - App->>SDK: sendMessage() - SDK->>CometChat: Send Message - CometChat->>Moderation: Process Message - CometChat-->>SDK: Message (status: PENDING) - SDK-->>App: onSuccess (PENDING) - Moderation-->>CometChat: Moderation Result - CometChat-->>SDK: onMessageModerated - SDK-->>App: APPROVED or DISAPPROVED -``` - -| Step | Description | -|------|-------------| -| 1. Send Message | App sends a text, image, or video message | -| 2. Pending Status | Message is sent with `PENDING` moderation status | -| 3. AI Processing | Moderation service analyzes the content | -| 4. Result Event | `onMessageModerated` event fires with final status | - -## 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 | - -## Moderation Status - -The `moderationStatus` property returns one of the following enum values: - -| Status | Enum Value | Description | -|--------|------------|-------------| -| Pending | `ModerationStatusEnum.PENDING` | Message is being processed by moderation | -| Approved | `ModerationStatusEnum.APPROVED` | Message passed moderation and is visible | -| Disapproved | `ModerationStatusEnum.DISAPPROVED` | Message violated rules and was blocked | - -## Implementation - -### Step 1: Send a Message and Check Initial Status - -When you send a text, image, or video message, check the initial moderation status: - - - - ```dart - TextMessage textMessage = TextMessage( - text: "Hello, how are you?", - receiverUid: receiverUID, - receiverType: ReceiverTypeConstants.user, - ); - - CometChat.sendMessage( - textMessage, - onSuccess: (TextMessage message) { - // Check moderation status - if (message.moderationStatus?.value == ModerationStatusEnum.PENDING.value) { - print("Message is under moderation review"); - // Show pending indicator in UI - } - }, - onError: (CometChatException e) { - print("Message sending failed: ${e.message}"); - }, - ); - ``` - - - -### Step 2: Listen for Moderation Results - -Implement the `MessageListener` to receive moderation results in real-time: - - - - ```dart - class ModerationListener with MessageListener { - - @override - void onMessageModerated(BaseMessage message) { - if (message is TextMessage) { - switch (message.moderationStatus?.value) { - case ModerationStatusEnum.APPROVED: - print("Message ${message.id} approved"); - // Update UI to show message normally - break; - - case ModerationStatusEnum.DISAPPROVED: - print("Message ${message.id} blocked"); - // Handle blocked message (hide or show warning) - handleDisapprovedMessage(message); - break; - } - } else if (message is MediaMessage) { - switch (message.moderationStatus?.value) { - case ModerationStatusEnum.APPROVED: - print("Media message ${message.id} approved"); - break; - - case ModerationStatusEnum.DISAPPROVED: - print("Media message ${message.id} blocked"); - handleDisapprovedMessage(message); - break; - } - } - } - } - - // Register the listener - CometChat.addMessageListener("MODERATION_LISTENER", ModerationListener()); - - // Don't forget to remove the listener when done - // CometChat.removeMessageListener("MODERATION_LISTENER"); - ``` - - - -### Step 3: Handle Disapproved Messages - -When a message is disapproved, handle it appropriately in your UI: - - - - ```dart - void handleDisapprovedMessage(BaseMessage message) { - int messageId = message.id; - - // Option 1: Hide the message completely - hideMessageFromUI(messageId); - - // Option 2: Show a placeholder message - showBlockedPlaceholder(messageId, "This message was blocked by moderation"); - - // Option 3: Notify the sender (if it's their message) - if (message.sender?.uid == currentUserUID) { - showNotification("Your message was blocked due to policy violation"); - } - } - ``` - - - -## 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. diff --git a/sdk/flutter/v5/ai-user-copilot-overview.mdx b/sdk/flutter/v5/ai-user-copilot-overview.mdx deleted file mode 100644 index 3e798a3fb..000000000 --- a/sdk/flutter/v5/ai-user-copilot-overview.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: "AI" -url: "/fundamentals/ai-user-copilot/overview" ---- \ No newline at end of file diff --git a/sdk/flutter/v5/authentication-overview.mdx b/sdk/flutter/v5/authentication-overview.mdx deleted file mode 100644 index 87b335748..000000000 --- a/sdk/flutter/v5/authentication-overview.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: "Authentication" -sidebarTitle: "Overview" ---- - -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**. The user does not ever directly login 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, you can associate them as friends in CometChat. - -### Typical Workflow - -```mermaid -sequenceDiagram - participant App as Your App - participant Server as Your Server - participant CC as CometChat - - Note over App,CC: Registration - App->>Server: User registers - Server->>Server: Store user in DB - Server->>CC: Create user via REST API - - Note over App,CC: Login - App->>Server: User logs in - Server->>Server: Verify credentials - Server->>CC: Generate Auth Token - Server-->>App: Return Auth Token - App->>CC: CometChat.login(uid, authToken) - CC-->>App: Session established - - Note over App,CC: Messaging - App->>CC: Send and receive messages -``` - -| Your App | Your Server | CometChat | -|----------|-------------|-----------| -| User registers | Store user info in your database | Create user via REST API (ID & name) | -| User logs in | Verify credentials, retrieve user ID | Log in user programmatically | -| User sends a friend request | Display the request to the potential friend | No action required | -| User accepts a friend request | Display the users as friends | Add both users as friends via REST API | - -## Create User - -Before you login the user, you must add the user to CometChat. - -1. **For proof of concept/MVPs**: Create the user using the [CometChat Dashboard](https://app.cometchat.com/). -2. **For production apps**: Use the CometChat [Create User API](https://api-explorer.cometchat.com/reference/creates-user) to create the user when your user signs up in your app. - - - -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`. - - - -Once initialization is successful, 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. - - - -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. - - - -## 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. - - - -```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}"); - }); -} -``` - - - - - -| Parameter | Description | -| --------- | -------------------------------------------------- | -| UID | The `UID` of the user that you would like to login | -| authKey | CometChat App Auth Key | - -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. - -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. - - - -```dart -String authToken = "AUTH_TOKEN"; -var user = await CometChat.getLoggedInUser(onSuccess: (_){}, onError: (_){}); -if (user == null) { - if(authToken!=null){ - await CometChat.loginWithAuthToken(authToken, - onSuccess: (User loggedInUser){ - debugPrint("Login Successful : $user" ); - }, onError: ( CometChatException e){ - debugPrint("Login failed with exception: ${e.message}"); - }); - } -} -``` - - - - - -| Parameter | Description | -| ---------------------------------------------- | ----------- | -| authToken | Auth Token of the user you would like to login | - -After the user logs in, their information is returned in the `User` object. - -## 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. - - - -```dart -CometChat.logout( onSuccess: ( successMessage) { - debugPrint("Logout successful with message $successMessage"); - }, onError: (CometChatException e ){ - debugPrint("Logout failed with exception: ${e.message}"); - } - ); -``` - - - - diff --git a/sdk/flutter/v5/block-users.mdx b/sdk/flutter/v5/block-users.mdx deleted file mode 100644 index 8613e6df1..000000000 --- a/sdk/flutter/v5/block-users.mdx +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: "Block Users" ---- - - - -## 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. - - - -```dart -List uids = []; -uids.add("UID1"); -uids.add("UID2"); -uids.add("UID3"); -CometChat.blockUser(uids, onSuccess: (Map map) { -debugPrint("Blocked User Successfully $map "); -}, onError: (CometChatException e) { -debugPrint("Blocked User Unsuccessful ${e.message} "); -}); -``` - - - - - -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. - - - -```dart -List uids = []; -uids.add("UID1"); -uids.add("UID2"); -uids.add("UID3"); - -CometChat.unblockUser(uids, onSuccess: (Map map) { - debugPrint("Blocked User Successfully $map "); - }, onError: (CometChatException e) { - debugPrint("Blocked User Unsuccessful ${e.message} "); - }); -``` - - - - - -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 - -*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: - -### Set Limit - -This method sets the limit i.e. the number of blocked users that should be fetched in a single iteration. - - - -```dart -BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() - ..limit = 50 - ).build(); -``` - - - - - -### Set Search Keyword - -This method allows you to set the search string based on which the blocked users are to be fetched. - - - -```dart -BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() - ..limit = 50 - ..searchKeyword = "abc" - ).build(); -``` - - - - - -### Set Direction - -* `CometChatBlockedUsersDirection.`*directionBlockedByMe* - This will ensure that the list of blocked users only contains the users blocked by the logged in user. -* `CometChatBlockedUsersDirection.`*directionHasBlockedMe* - This will ensure that the list of blocked users only contains the users that have blocked the logged in user. -* `CometChatBlockedUsersDirection.`*directionBoth* - 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. - - - -```dart -BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() - ..limit = 50 - .direction = CometChatBlockedUsersDirection.directionBlockedByMe - ).build(); -``` - - - - - -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. - -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. - - - -```dart -BlockedUsersRequest blockedUsersRequest = (BlockedUsersRequestBuilder() - ..limit = 30 - ).build(); - -blockedUsersRequest.fetchNext(onSuccess: (List userList){ - debugPrint("Custom Message Sent Successfully : $userList "); - }, onError: (CometChatException e){ - debugPrint("Blocked User Request failed with exception: ${e.message}"); -}); -``` - - - - diff --git a/sdk/flutter/v5/connection-status.mdx b/sdk/flutter/v5/connection-status.mdx deleted file mode 100644 index a0877d610..000000000 --- a/sdk/flutter/v5/connection-status.mdx +++ /dev/null @@ -1,86 +0,0 @@ ---- -title: "Connection Status" ---- - - - -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 | -| onConnectionError | This method is called when the CometChat SDK gets error due to any issue while maintaining the connection like network fluctuations, etc. | - -Once the connection is broken, the disconnected callback is triggered, the SDK automatically tries to establish the connection again, thus going into the connecting state and triggering the `connecting` method. Once the attempt to connect is successful, the `connected` method is triggered thus letting the developer know that the connection is established and is active. - -In order to use the ConnectionListeners, you need to add the ConnectionListeners using the `addConnectionListener` method provided by the SDK. You can add multiple listeners as shown below. Just make sure you add listeners with unique IDs. - - - -```dart -class Class_Name with ConnectionListener { -//1. Register Connection listener -//CometChat.addConnctionListener("listenerId", this); - -//2. Ovveride the ConnectionListener methods -@override -void onConnected() { - // TODO: implement onConnected -} - -@override -void onConnecting() { - // TODO: implement onConnecting -} - -@override -void onDisconnected() { - // TODO: implement onDisconnected -} - -@override -void onFeatureThrottled() { - // TODO: implement onFeatureThrottled -} - -@override -void onConnectionError(CometChatException error) { - // TODO: implement onFeatureThrottled -} - -} -``` - - - - - -You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK - - - -```dart -String connectionStatus = CometChat.getConnectionStatus(); -``` - - - - - -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) - - diff --git a/sdk/flutter/v5/create-group.mdx b/sdk/flutter/v5/create-group.mdx deleted file mode 100644 index feb4149fc..000000000 --- a/sdk/flutter/v5/create-group.mdx +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: "Create A Group" ---- - - - -## 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. - -The `groupType` needs to be either of the below 3 values: - -1.`CometChatGroupType.`*public* (public) - -2.`CometChatGroupType.`*password* (password) - -3.`CometChatGroupType.`*private* (private) - - - -```dart -String GUID = "GUID"; - String groupName = "Hello Group!"; - String groupType = CometChatGroupType.public; - String password = ""; - - Group _group = Group(guid: GUID, name: groupName, type: groupType); - - - await CometChat.createGroup(group: _group, onSuccess: (Group group ){ - debugPrint("Group Created Successfully : $group "); - }, onError:(CometChatException e) { - debugPrint("Group Creation failed with exception: ${e.message}"); - } ); -``` - - - - - -The `createGroup()` method takes the following parameters: - -| 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. - - - -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - - -## Create a Group with Members - -*In other words, how do I create a group and add members in a single step?* - -You can create a group and add members simultaneously using the `createGroupWithMembers()` method. This is more efficient than creating a group first and then adding members separately. - - - -```dart -String GUID = "GUID"; -String groupName = "Hello Group!"; -String groupType = CometChatGroupType.public; - -Group group = Group(guid: GUID, name: groupName, type: groupType); - -// Create a list of group members to add -List members = []; -members.add(GroupMember(uid: "cometchat-uid-1", scope: CometChatMemberScope.participant)); -members.add(GroupMember(uid: "cometchat-uid-2", scope: CometChatMemberScope.moderator)); -members.add(GroupMember(uid: "cometchat-uid-3", scope: CometChatMemberScope.admin)); - -await CometChat.createGroupWithMembers( - group: group, - members: members, - onSuccess: (Group group, Map failedMembers) { - debugPrint("Group Created Successfully : $group"); - if (failedMembers.isNotEmpty) { - debugPrint("Failed to add some members: $failedMembers"); - } - }, - onError: (CometChatException e) { - debugPrint("Group Creation failed with exception: ${e.message}"); - } -); -``` - - - - - -The `createGroupWithMembers()` method takes the following parameters: - -| Parameter | Description | -| --------- | ---------------------------------------------------------- | -| `group` | An instance of `Group` class | -| `members` | A list of `GroupMember` objects to be added to the group | - -The `onSuccess` callback returns: -- `group`: The created `Group` object -- `failedMembers`: A map containing UIDs of members that failed to be added along with the error reason - -The `GroupMember` class takes the following parameters: - -| Parameter | Description | -| --------- | ------------------------------------------------------------------------------------------------ | -| `uid` | The UID of the user to be added as a member | -| `scope` | The scope of the member: `CometChatMemberScope.participant`, `moderator`, or `admin` | - -## Group Class - -| Field | Editable | Information | -| ------------ | --------------------------------------------------------------- | ------------------------------------------------------------------------- | -| guid | Needs to be specified at group creation. Cannot be edited later | A unique identifier for a group | -| name | Yes | Name of the group | -| type | No | Type of the group: Can be 1. Public 2. Password 3. Private | -| password | No | Password for the group in case the group is of type password. | -| icon | Yes | An URL to group icon | -| description | Yes | Description about the group | -| owner | Yes | UID of the owner of the group. | -| metadata | Yes | Additional data for the group as JSON | -| 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. | -| isBannedFromGroup | No | A boolean indicating whether the logged-in user is banned from the group. | diff --git a/sdk/flutter/v5/delete-conversation.mdx b/sdk/flutter/v5/delete-conversation.mdx deleted file mode 100644 index 57473b8ca..000000000 --- a/sdk/flutter/v5/delete-conversation.mdx +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: "Delete A Conversation" ---- - - - -In case you want to delete a conversation, you can use the `deleteConversation()` method. - -This method takes two parameters. The unique id (UID/GUID) of the conversation to be deleted & the type (user/group) of conversation to be deleted. - - - -```dart -String conversationWith = "UID"; -String conversationType = CometChatConversationType.user; -await CometChat.deleteConversation(conversationWith, conversationType, - onSuccess: (String str){ - debugPrint("Conversation deleted successfully at : $str"); - }, - onError: (CometChatException e){ - debugPrint("Conversation deletion failed : ${e.message}"); - } -); -``` - - - - -```dart -String conversationWith = "GUID"; -String conversationType = CometChatConversationType.group; -await CometChat.deleteConversation(conversationWith, conversationType, - onSuccess: (String str){ - debugPrint("Conversation deleted successfully at : $str"); - }, - onError: (CometChatException e){ - debugPrint("Conversation deletion failed : ${e.message}"); - } -); -``` - - - - - -This method deletes the conversation only for the logged-in user. To delete a conversation for all the users of the conversation, please refer to our REST API documentation [here](https://api-explorer.cometchat.com/reference/deletes-conversation). - -The `deleteConversation()` method takes the following parameters: - -| Parameter | Description | Required | -| ---------------- | --------------------------------------------------------------------------------- | -------- | -| conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | -| conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | diff --git a/sdk/flutter/v5/delete-group.mdx b/sdk/flutter/v5/delete-group.mdx deleted file mode 100644 index 2bc36f2e0..000000000 --- a/sdk/flutter/v5/delete-group.mdx +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: "Delete A Group" ---- - - - -## 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. - - - -```dart -String GUID = "GUID"; - -CometChat.deleteGroup(GUID, onSuccess: (String message) { -debugPrint("Deleted Group Successfully : $message "); -}, onError: (CometChatException e) { -debugPrint("Delete Group failed with exception: ${e.message}"); -}); -``` - - - - - -The `deleteGroup()` method takes the following parameters: - -| Parameter | Description | -| --------- | ---------------------------------------------- | -| `GUID` | The GUID of the group you would like to delete | diff --git a/sdk/flutter/v5/delete-message.mdx b/sdk/flutter/v5/delete-message.mdx deleted file mode 100644 index ebf63f117..000000000 --- a/sdk/flutter/v5/delete-message.mdx +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: "Delete A Message" ---- - - - -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. - -## 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. - - - -```dart -int messageId=1234; - -await CometChat.deleteMessage(messageId, - onSuccess: (BaseMessage message){ - debugPrint("Message deleted successfully at : $message"); - }, onError: (CometChatException e){ - debugPrint("Message deletion failed : ${e.message}"); - } -); -``` - - - - - -Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. - -By default, CometChat allows certain roles to delete a message. - -## 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?* - -| 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 | - -In order to receive real-time events for a message being deleted, you need to override the `onMessageDeleted()` method of the `MessageListener` class. - - - -```dart -class Class_Name with MessageListener { - -//CometChat.addMessageListener("listenerId", this); -@override -void onMessageDeleted(BaseMessage message) { - // TODO implement onMessageDeleted -} - - -} -``` - - - - - -## 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, 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. - -For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- - -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. - - - -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. - - diff --git a/sdk/flutter/v5/delivery-read-receipts.mdx b/sdk/flutter/v5/delivery-read-receipts.mdx deleted file mode 100644 index 19be057f3..000000000 --- a/sdk/flutter/v5/delivery-read-receipts.mdx +++ /dev/null @@ -1,280 +0,0 @@ ---- -title: "Delivery & Read Receipts" ---- - - - -## Mark Messages as Delivered - -*In other words, as a recipient, how do I inform the sender that I've received a message?* - -You can mark the messages for a particular conversation as read using the `markAsDelivered()` method. This method takes the below parameters as input: - -| Parameter | Information | -| ------------ | ---------------------------------------------------------------------------------------------------------- | -| 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. - -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. - -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 `markAsDelivered()` method with the callbacks as shown below: - - - -```dart -CometChat.markAsDelivered(message, onSuccess: (String unused) { -debugPrint("markAsDelivered : $unused "); -}, onError: (CometChatException e) { -debugPrint("markAsDelivered unsuccessful : ${e.message} "); -}); -``` - - - - - -## 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: - -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). | - -Messages for both user and group conversations can be marked as read using this method. - -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: - -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 `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 and pass it to the `markAsRead()` method - -This method will mark all the messages before the message specified, for the conversation with `receiverId` and `receiverType` (user/group) as read. - -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. - - - -```dart -CometChat.markAsRead(message) -``` - - - - - -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: - - - -```dart -CometChat.markAsRead(message, onSuccess: (String unused) { - debugPrint("markAsRead : $unused "); - reinitiateList(); - }, onError: (CometChatException e) { - debugPrint("markAsRead unsuccessfull : ${e.message} "); - }); -``` - - - - - -## 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 message as unread?* - -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 `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. | - - - -```dart -CometChat.markMessageAsUnread( - message, - onSuccess: (success) { - debugPrint("markMessageAsUnread : $success"); - }, - onError: (error) { - debugPrint("markMessageAsUnread unsuccessful : $error"); - }, - ); -``` - - - - - -## Mark Conversation as Delivered - -*In other words, how do I mark an entire conversation as delivered?* - -You can mark an entire conversation as delivered using the `markConversationAsDelivered()` method. This is useful when you want to signal that all messages in a conversation have been delivered to the recipient. - - - -```dart -CometChat.markConversationAsDelivered( - conversation, - onSuccess: (success) { - debugPrint("markConversationAsDelivered : $success"); - }, - onError: (error) { - debugPrint("markConversationAsDelivered unsuccessful : $error"); - }, - ); -``` - - - - - -## Mark Conversation as Read - -*In other words, how do I mark an entire conversation as read?* - -You can mark an entire conversation as read using the `markConversationAsRead()` method. This updates the status of all messages in the conversation to "read". - - - -```dart -CometChat.markConversationAsRead( - conversation, - onSuccess: (success) { - debugPrint("markConversationAsRead : $success"); - }, - onError: (error) { - debugPrint("markConversationAsRead unsuccessful : $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 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. - - - -```dart -class Class_Name with MessageListener { - -//CometChat.addMessageListener("listenerId", this); -@override -void onMessagesDelivered(MessageReceipt messageReceipt) { - // TODO: implement onMessagesDelivered -} - -@override -void onMessagesRead(MessageReceipt messageReceipt) { - // TODO: implement onMessagesRead -} - -@override -void onMessagesDeliveredToAll(MessageReceipt messageReceipt) { - // TODO: implement onMessagesDeliveredToAll -} - -@override -void onMessagesReadByAll(MessageReceipt messageReceipt) { - // TODO: implement onMessagesReadByAll -} - -} -``` - - - - - -You will receive events in the form of `MessageReceipt` objects. The message receipt contains the following 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. | -| `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 - -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. - -### Receipt History for a Single Message - -In order to fetch the message receipts, you can use the `getMessageReceipts()` method. - - - -```dart -private 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 -} -}); -``` - - - - - -You will receive a list of `MessageReceipt` objects in the `onSuccess()` method. - - - -The following features will be available only if the **Enhanced Messaging Status** feature is enabled for your app. - -* `onMessagesDeliveredToAll` event, -* `onMessagesReadByAll` event, -* `deliveredAt` field in a group message, -* `readAt` field in a group message. -* `markMessageAsUnread` method. -* `markConversationAsDelivered` method. -* `markConversationAsRead` method. - - diff --git a/sdk/flutter/v5/edit-message.mdx b/sdk/flutter/v5/edit-message.mdx deleted file mode 100644 index 76ae225c6..000000000 --- a/sdk/flutter/v5/edit-message.mdx +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: "Edit A Message" ---- - - - -While editing a message is straightforward, receiving events for edited messages with CometChat has two parts: - -1. Adding a listener to receive [real-time message edit events](/sdk/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 - -## 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. - - - -```dart -List tags = []; -tags.add("pinned"); -textMessage.tags = tags; -``` - - - - - -Once the message object is ready, you can use the `editMessage()` method and pass the message object to it. - - - -```dart -TextMessage updatedMessage = TextMessage( - text: updatedText, - receiverUid: receiverID, - receiverType: receiverType, - type: type); - -updatedMessage.id = message.id; - -await CometChat.editMessage(updatedMessage, - onSuccess: (BaseMessage message){ - debugPrint("Message Edited successfully: $message"); - }, onError: (CometChatException e){ - debugPrint("Message Edited failed with exception: ${e.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 roles 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 | - -## 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. - - - -```dart -class Class_Name with MessageListener { - -//CometChat.addMessageListener("listenerId", this); -@override -void onMessageEdited(BaseMessage message) { - // TODO: implement onMessageEdited -} - - -} -``` - - - - -## 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. 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.. - -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- - -1. `action` - `edited` -2. `actionOn` - Updated message object with the edited details. -3. `actionBy` - User object containing the details of the user who has edited the message. -4. `actionFor` - User/group object having the details of the receiver to which the message was sent. - - - -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. - - diff --git a/sdk/flutter/v5/extensions-overview.mdx b/sdk/flutter/v5/extensions-overview.mdx deleted file mode 100644 index 29c1774bd..000000000 --- a/sdk/flutter/v5/extensions-overview.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: "Extensions" -url: "/fundamentals/extensions-overview" ---- \ No newline at end of file diff --git a/sdk/flutter/v5/group-add-members.mdx b/sdk/flutter/v5/group-add-members.mdx deleted file mode 100644 index e125be98b..000000000 --- a/sdk/flutter/v5/group-add-members.mdx +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: "Add Members To A Group" ---- - - - -## Add Members to Group - -You can add members to the group using the `addMembersToGroup()` method. This method takes the below parameters: - -1. `GUID` - GUID of the group users are to be added to. -2. `List members` - This is a list of `GroupMember` objects. In order to add members, you need to create an object of the `GroupMember` class. The `UID` and the scope of the `GroupMember` are mandatory. -3. `List bannedMembers` - This is the list of `UIDs` that need to be banned from the group. This can be set to `null` if there are no members to be banned. - - - -```dart -List groupMembers = []; -GroupMember firstMember = GroupMember.fromUid( -scope: CometChatMemberScope.participant, -uid: "cometchat-uid-3",name: "name"); -GroupMember secondMember = GroupMember.fromUid(scope: CometChatMemberScope.admin, -uid: "cometchat-uid-4",name: "name"); - -groupMembers = [firstMember, secondMember]; - -CometChat.addMembersToGroup( guid: conversationWith, - groupMembers: groupMembers, - onSuccess: (Map result) { - debugPrint("Group Member added Successfully : $result"); - }, - onError: (CometChatException e) { - debugPrint("Group Member addition failed with exception: ${e.message}"); - }); -``` - - - - - -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. - -## 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. - - - -```dart -class Class_Name with GroupListener { - -//CometChat.addGroupListener("group_Listener_id", this); -@override -void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo) { - print("onMemberAddedToGroup"); -} -} -``` - - - - - -## 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 diff --git a/sdk/flutter/v5/group-change-member-scope.mdx b/sdk/flutter/v5/group-change-member-scope.mdx deleted file mode 100644 index 412b54b93..000000000 --- a/sdk/flutter/v5/group-change-member-scope.mdx +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: "Change Member Scope" ---- - - - -## Change Scope of a Group Member - -In order to change the scope of a group member, you can use the `changeGroupMemberScope()`. - - - -```dart -String UID = "UID"; -String GUID = "GUID"; -String scope = CometChatMemberScope.admin; - -CometChat.updateGroupMemberScope(guid: GUID, uid: UID,scope: scope, - onSuccess: (String message) { - debugPrint("Group Member Scope Changed Successfully : $message"); - }, - onError: (CometChatException e) { - debugPrint("Group Member Scope Change failed : ${e.message}"); - }); -``` - - - - - -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) | - -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 - -*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 - - - -```dart -class Class_Name with GroupListener { - -//CometChat.addGroupListener("group_Listener_id", this); -@override -void onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - print("onGroupMemberScopeChanged "); - -} -} -``` - - - - - -## 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- - -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 diff --git a/sdk/flutter/v5/groups-overview.mdx b/sdk/flutter/v5/groups-overview.mdx deleted file mode 100644 index f219e6c57..000000000 --- a/sdk/flutter/v5/groups-overview.mdx +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: "Groups" -sidebarTitle: "Overview" ---- - -A group can be used for multiple users to communicate with each other on a particular topic or interest. - -## GUID - -- 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. - - -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - -## Group Types - -CometChat supports three different types of groups: - -```mermaid -flowchart LR - G["Group"] --> Public - G --> Password - G --> Private - - Public -.- P1["Visible to all, anyone can join"] - Password -.- P2["Visible to all, requires password"] - Private -.- P3["Hidden, invite only"] -``` - -| Type | Visibility | Participation | -|------|-----------|---------------| -| Public | All users | Any user can choose to join | -| Password | All users | Any user with a valid password can join | -| Private | Only members | Invited users are auto-joined | - -## Member Scopes - -Once a participant joins a group, they become a member. Members remain part of the group indefinitely — to stop receiving messages, calls, and notifications, a member must be kicked, banned, or leave the group. - -```mermaid -flowchart TD - Admin["Admin (Group creator)"] - Moderator["Moderator"] - Participant["Participant (Default scope)"] - - Admin -->|Can promote or demote| Moderator - Admin -->|Can promote or demote| Participant - Moderator -->|Can promote or demote| Participant - - Admin -.- A1["Full control: manage members, update/delete group, message & call"] - Moderator -.- M1["Moderate: kick/ban participants, update group, message & call"] - Participant -.- P1["Basic: send & receive messages & calls"] -``` - -| Scope | Default | Privileges | -|-------|---------|-----------| -| Admin | Group creator | Manage all members, add members, kick & ban anyone, send & receive messages & calls, update & delete group | -| Moderator | — | Change scope of participants, kick & ban participants, update group, send & receive messages & calls | -| Participant | All other members | Send & receive messages & calls | diff --git a/sdk/flutter/v5/interactive-messages.mdx b/sdk/flutter/v5/interactive-messages.mdx deleted file mode 100644 index ce85974c3..000000000 --- a/sdk/flutter/v5/interactive-messages.mdx +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: "Interactive Messages" ---- - - - -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 - - }); -``` - - - - - -### 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. - -### 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 - -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: - - - -```dart -final Map interactiveData = { - "title": "Survey", - "formFields": [ - { - "elementType": "textInput" , - "elementId": "name", - "optional": false, - "label": "Name", - "placeholder": { - "text": "Enter text here" - } - }, - { - "elementType": "textInput", - "elementId": "age", - "optional": true, - "label": "Age", - "maxLines": 1, - "placeholder": { - "text": "Enter text here" - } - }, - { - "elementType": "Select", - "elementId": "checkBox1", - "optional": true, - "label": "Check box element", - "defaultValue":["chk_option_2"], - "options" : [ - { - "label": "Option 1", - "value": "chk_option_1", - }, - { - "label": "Option 2", - "value": "chk_option_2", - } - - ] - }, - { - "elementType": "dropdown", - "elementId": "gender", - "optional": false, - "label": "Gender", - "defaultValue":"male", - "options" : [ - { - "label": "Male", - "value": "male", - }, - { - "label": "Female", - "value": "female", - } - - ] - }, - ], - "submitElement": { - "elementType": "button", - "elementId": "submitButton", - "buttonText": "Submit", - "disableAfterInteracted": false, - "action": { - "actionType": "urlNavigation", - "url": "https://www.cometchat.com/", - } - }, -}; - - - -InteractiveMessage interactiveMessage = -InteractiveMessage(interactiveData: interactiveData, - receiverUid: "cometchat-uid-3", //Replace this with receiver id - type: "form", - receiverType: "user",//replace this with receiver type - allowSenderInteraction: true, - muid: DateTime.now().millisecondsSinceEpoch.toString(), - interactionGoal: InteractionGoal( - type: InteractionGoalType.none - ) - ); - - -CometChat.sendInteractiveMessage(interactiveMessage, onSuccess: (InteractiveMessage message){ - -print(interactiveMessage); - -}, onError: (CometChatException excep){ -print(excep); -}); -``` - - - - - -### Event Listeners - -CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. - -### On InteractiveMessage Received - -The `onInteractiveMessageReceived` event listener is triggered when an `InteractiveMessage` is received. - -Here is an example: - - - -```dart -class DemoClass with MessageListener{ - -String listenerId = "UNIQUE_LISTENER_ID"; //Replace with unique listener id - - -CometChat.addMessageListener(_listenerId, this); - - - - @override -void onInteractiveMessageReceived(InteractiveMessage message){ - - //TODO implement onInteractiveMessageReceived event -} - -} -``` - - - - - -### On Interaction Goal Completed - -The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. - -Here is an exampl - - - -```dart -class DemoClass with MessageListener{ - -String listenerId = "UNIQUE_LISTENER_ID"; //Replace with unique listener id - - -CometChat.addMessageListener(_listenerId, this); - - - -@override -void onInteractionGoalCompleted(InteractionReceipt receipt) { - //TODO implement onInteractionGoalCompleted -} - -} -``` - - - - - -These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience. - -### Usage - -An `InteractiveMessage` is constructed with the receiver's UID, the receiver type, the interactive type, and interactive data as a JSONObject. Once created, the `InteractiveMessage` can be sent using CometChat's `sendInteractiveMessage()` method. Incoming `InteractiveMessages` can be received and processed via CometChat's message listener framework. diff --git a/sdk/flutter/v5/join-group.mdx b/sdk/flutter/v5/join-group.mdx deleted file mode 100644 index 41e6b00da..000000000 --- a/sdk/flutter/v5/join-group.mdx +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: "Join A Group" ---- - - - -## 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. - - - -```dart -String GUID = "GUID"; -String groupType = CometChatGroupType.public; -String password = ""; - -CometChat.joinGroup(GUID, groupType, password: password, - onSuccess: (Group group) { - debugPrint("Group Joined Successfully : $group "); - }, onError: (CometChatException e) { - debugPrint("Group Joining failed with exception: ${e.message}"); - }); -``` - - - - - -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.CometChatGroupType.*public* (public). 2.CometChatGroupType.*password* (password) 3.CometChatGroupType.*private* (private) | -| `password` | Password is mandatory in case of a password protected group. | - -Once you have joined a group successfully, you can send and receive messages in that group. - -CometChat keeps a track of the groups joined and you do not need to join the group everytime you want to communicate in the group. - -You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. - -## 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. - - - -```dart -class Class_Name with GroupListener { - -//CometChat.addGroupListener("group_Listener_id", this); -@override -void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { - debugPrint("onGroupMemberJoined"); -} -``` - - - - - -## 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 diff --git a/sdk/flutter/v5/leave-group.mdx b/sdk/flutter/v5/leave-group.mdx deleted file mode 100644 index f73638b8d..000000000 --- a/sdk/flutter/v5/leave-group.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: "Leave A 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. - - - -```dart -String GUID = "GUID"; - -CometChat.leaveGroup(GUID, onSuccess: ( String message) { - debugPrint("Group Left Successfully : $message"); - },onError: (CometChatException e) { - debugPrint("Group Left failed : ${e.message}"); - }); -``` - - - - - -| Parameter | Description | -| --------- | --------------------------------------------- | -| `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. - -## 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. - - - -```dart -class Class_Name with GroupListener { - -//CometChat.addGroupListener("group_Listener_id", this); -@override -void onGroupMemberLeft(Action action, User leftUser, Group leftGroup) { - print("onGroupMemberLeft "); - -} -} -``` - - - - - -## 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 diff --git a/sdk/flutter/v5/mentions.mdx b/sdk/flutter/v5/mentions.mdx deleted file mode 100644 index 2a0ad288e..000000000 --- a/sdk/flutter/v5/mentions.mdx +++ /dev/null @@ -1,227 +0,0 @@ ---- -title: "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. - -## 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>`" - - - -```dart -String receiverID = "UID"; -User sender = User(name: "Sender", uid: "senderUID"); -String messageText = "Hello, <@uid:cometchat-uid-1>"; -String receiverType = CometChatReceiverType.user; - -TextMessage textMessage = TextMessage( - text: messageText, - sender: sender, - receiverUid: receiverID, - receiverType: receiverType, - category: CometChatMessageCategory.message, - type: CometChatMessageType.text); - -CometChat.sendMessage(textMessage, onSuccess:(TextMessage textMessage) { - print("Message sent successfully: ${textMessage.text}, mentioned users: ${textMessage.mentionedUsers}"); - }, - onError:(CometChatException e) { - print("Message sending failed with exception: $e"); - } -); -``` - - - - -```dart -String receiverID = "GUID"; -User sender = User(name: "Sender", uid: "senderUID"); -String messageText = "Hello, <@uid:cometchat-uid-1>"; -String receiverType = CometChatReceiverType.group; - -TextMessage textMessage = TextMessage( - text: messageText, - sender: sender, - receiverUid: receiverID, - receiverType: receiverType, - category: CometChatMessageCategory.message, - type: CometChatMessageType.text); - -CometChat.sendMessage(textMessage, onSuccess:(TextMessage textMessage) { - print("Message sent successfully: ${textMessage.text}, mentioned users: ${textMessage.mentionedUsers}"); - }, - onError:(CometChatException e) { - print("Message sending failed with exception: $e"); - } -); -``` - - - - - - - -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. - -| Setting | Description | Default Value | -| ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -| `mentionsWithTagInfo(bool 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. | false | -| `mentionsWithBlockedInfo(bool 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. | false | - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messagesRequest = (MessagesRequestBuilder() -..limit=50 -..uid=UID -..mentionsWithTagInfo(true)) -.build(); - -messagesRequest.fetchPrevious(onSuccess:(List messages) { - for (BaseMessage message in messages){ - for (User user in message.mentionedUsers){ - print("mentioned user tags: ${user.tags}"); - } - } - }, - onError: (CometChatException e) { - print("error: $e"); - } -); -``` - - - - -```dart -String GUID = "cometchat-guid-1"; - -MessagesRequest messagesRequest = (MessagesRequestBuilder() -..limit=50 -..guid=GUID -..mentionsWithTagInfo(true)) -.build(); - -messagesRequest.fetchPrevious(onSuccess:(List messages) { - for (BaseMessage message in messages){ - for (User user in message.mentionedUsers){ - print("mentioned user tags: ${user.tags}"); - } - } - }, - onError: (CometChatException e) { - print("error: $e"); - } -); -``` - - - - - -## 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messagesRequest = (MessagesRequestBuilder() -..limit=50 -..uid=UID -..mentionsWithBlockedInfo(true)) -.build(); - -messagesRequest.fetchPrevious(onSuccess:(List messages) { - for (BaseMessage message in messages){ - for (User user in message.mentionedUsers){ - print("mentioned user has blocked me? ${user.hasBlockedMe}"); - print("mentioned user is blocked by me? ${user.blockedByMe}"); - } - } - }, - onError: (CometChatException e) { - print("error: $e"); - } -); -``` - - - - -```dart -String GUID = "cometchat-guid-1"; - -MessagesRequest messagesRequest = (MessagesRequestBuilder() -..limit=50 -..guid=GUID -..mentionsWithBlockedInfo(true)) -.build(); - -messagesRequest.fetchPrevious(onSuccess:(List messages) { - for (BaseMessage message in messages){ - for (User user in message.mentionedUsers){ - print("mentioned user has blocked me? ${user.hasBlockedMe}"); - print("mentioned user is blocked by me? ${user.blockedByMe}"); - } - } - }, - onError: (CometChatException e) { - print("error: $e"); - } -); -``` - - - - - -## 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 -``` - - - - - -## 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`. - - - -```dart -message.hasMentionedMe -``` - - - - diff --git a/sdk/flutter/v5/overview.mdx b/sdk/flutter/v5/overview.mdx deleted file mode 100644 index 05e859b8a..000000000 --- a/sdk/flutter/v5/overview.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: "Chat SDK" -sidebarTitle: "Overview" ---- - -The CometChat Chat SDK for Flutter enables real-time messaging, user management, group conversations, and more in your Flutter application. Built as a pure Dart implementation in v5, it removes the dependency on platform channels and works seamlessly across Android, iOS, Web, and desktop. - - -This is a **beta release** of the CometChat Flutter Chat SDK v5. APIs and features may change before the stable release. - - - -**Faster Integration with UI Kits** - -If you're using CometChat UI Kits, messaging features can be quickly integrated with pre-built components: -- Conversation lists, message composers, and thread views -- Typing indicators, read receipts, and reactions -- Group management and user profiles - -👉 [Flutter UI Kit Overview](/ui-kit/flutter/overview) - -Use this Chat SDK directly only if you need custom UI or advanced control. - - - -**Upgrading from v4?** - -If you're migrating an existing app from CometChat SDK v4, check out the [Upgrading from v4](/sdk/flutter/v5/upgrading-from-v4-guide) guide for breaking changes, deprecated methods, and migration instructions. - - -Before integrating the Chat SDK, ensure you have a [CometChat Account](https://app.cometchat.com/signup) with your App ID, Region, and Auth Key. Flutter SDK `>=1.2` is required, with Android API Level 21+ and iOS 11+. Users must exist in CometChat to send or receive messages — see [Authentication](/sdk/flutter/v5/authentication-overview) for details. - -```mermaid -sequenceDiagram - participant App - participant CometChat - - App->>CometChat: init(appId, appSettings) - App->>CometChat: login(uid, authKey) - CometChat-->>App: User - App->>CometChat: sendMessage() / addMessageListener() - CometChat-->>App: Real-time events (messages, typing, presence) - App->>CometChat: logout() -``` - - - - - Send text, media, and custom messages in 1-on-1 or group conversations - - - - Create, join, and manage group conversations with member roles and scopes - - - - Listen for messages, typing indicators, read receipts, and presence changes in real time - - - - Show real-time typing status for users and groups - - - - Track online/offline status of users with configurable subscription modes - - - - Add and manage emoji reactions on messages - - - - Organize conversations with message threads - - - - Track message delivery and read status - - - - Integrate AI-powered agents into your chat experience - - - - Voice and video calling with built-in UI components - - - - -| Component | Description | -|-----------|-------------| -| `CometChat` | Main entry point for initialization, authentication, messaging, and real-time events | -| `AppSettings` | Configuration for SDK initialization (App ID, Region, presence subscription) | -| `User` | Represents a CometChat user with UID, name, avatar, and metadata | -| `Group` | Represents a group conversation with GUID, type, and member management | -| `BaseMessage` | Base class for all message types (text, media, custom, action) | -| `MessageListener` | Event interface for real-time message, typing, and receipt events | -| `ConnectionListener` | Event interface for WebSocket connection status changes | diff --git a/sdk/flutter/v5/reactions.mdx b/sdk/flutter/v5/reactions.mdx deleted file mode 100644 index 86824cf6c..000000000 --- a/sdk/flutter/v5/reactions.mdx +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: "Reactions" ---- - - - -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. - -## Add a Reaction -Users can add a reaction to a message by calling `addReaction` with the message ID and the reaction emoji. - - - -```dart -int messageId = 1; - -CometChat.addReaction(messageId, "😴", onSuccess: (message) { - debugPrint("Success : ${message.getReactions().last}"); -}, onError: (e) { - debugPrint("Error: ${e.message}"); -}); -``` - - - - - -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. - - - -```dart - -int messageId = 1; - -CometChat.removeReaction(messageId, "😴", onSuccess: (message) { - debugPrint("Success : ${message.getReactions().last}"); -}, onError: (e) { - debugPrint("Error: ${e.message}"); -}); -``` - - - - - -## Fetch Reactions for a Message -To get all reactions for a specific message, first create a `ReactionRequest` using `ReactionRequestBuilder`. You can specify the number of reactions to fetch with `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. - - -| 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 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(); - -reactionRequest.fetchNext( - onSuccess: (messageReactions) { - for (MessageReaction messageReaction in messageReactions) { - debugPrint("Success: ${messageReaction.getReactions()}"); - } - }, - onError: (e) { - debugPrint("Error: ${e.message}"); - }, -); -``` - - - - -## Fetch Previous -The `fetchPrevious()` method fetches the previous set of reactions for the message. - - - -```dart -int messageId = 1; - -ReactionRequest reactionRequest = (ReactionRequestBuilder()..limit = 30..messageId = messageId).build(); - -reactionRequest.fetchPrevious( - onSuccess: (messageReactions) { - for (MessageReaction messageReaction in messageReactions) { - debugPrint("Success: ${messageReaction.getReactions()}"); - } - }, - onError: (e) { - debugPrint("Error: ${e.message}"); - }, -); -``` - - - - -## 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. - - - - -```dart -class MyClass with MessageListener { - - String listenerID = "UNIQUE_LISTENER_ID"; - - MyClass() { - CometChat.addMessageListener(listenerID, this); - } - - @override - void onMessageReactionAdded(ReactionEvent reactionEvent) { - debugPrint("Reaction added ${reactionEvent.reaction}"); - } - - @override - void onMessageReactionRemoved(ReactionEvent reactionEvent) { - debugPrint("Reaction removed ${reactionEvent.reaction}"); - } -} -``` - - - - - - -## Removing a Reaction Listener -To stop listening for reaction events, remove the listener as follows: - - - -```dart -String listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.removeMessageReactionListener(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 -``` - - - - - -## 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`. - - - -```dart -for (ReactionCount reactionCount in message.reactions) { - debugPrint("isReactedByMe ${reactionCount.reactedByMe}"); //Return true is logged-in user reacted on that message, otherwise false -} -``` - - - - -## 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 = ...; - -// 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 -); -``` - - - diff --git a/sdk/flutter/v5/real-time-listeners.mdx b/sdk/flutter/v5/real-time-listeners.mdx deleted file mode 100644 index e1685bb8e..000000000 --- a/sdk/flutter/v5/real-time-listeners.mdx +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: "All Real Time Listeners" ---- - - - -CometChat provides 4 listeners viz. - -1. [UserListener](#user-listener) -2. [GroupListener](#group-listener) -3. [MessageListener](#message-listener) - -## 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. | - -To add the `UserListener`, you need to use the `addUserListener()` method provided by the `CometChat` class. - - - -```dart -class Class_Name with UserListener { - //CometChat.addUserListener("user_Listener_id", this); - @override - void onUserOnline(User user) { - - } - - @override - void onUserOffline(User user) { - - } - -} -``` - - - - - -where `UNIQUE_LISTENER_ID` is the unique identifier for the listener. Please make sure that no two listeners are added with the same listener id as this could lead to unexpected behavior resulting in loss of events. - -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. - - - -```dart -CometChat.removeUserListener(UNIQUE_LISTENER_ID) -``` - - - - - -## Group Listener - -The `GroupListener` class provides you with all the real-time events related to groups. Below are the callback methods provided by the `GroupListener` class. - -| 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. | - -To add the `GroupListener`, you need to use the `addGroupListener()` method provided by the `CometChat` class. - - - -```dart -class Class_Name with GroupListener { - //CometChat.addGroupListener("UNIQUE_LISTENER_ID", this); - - @override - void onGroupMemberJoined(Action action, User joinedUser, Group joinedGroup) { - - } - - @override - void onGroupMemberLeft(Action action, User leftUser, Group leftGroup) { - - } - - @override - void onGroupMemberKicked(Action action, User kickedUser, User kickedBy, Group kickedFrom) { - - } - - @override - void onGroupMemberBanned(Action action, User bannedUser, User bannedBy, Group bannedFrom) { - - } - - @override - void onGroupMemberUnbanned(Action action, User unbannedUser, User unbannedBy, Group unbannedFrom) { - - } - - @override - void onGroupMemberScopeChanged(Action action, User updatedBy, User updatedUser, String scopeChangedTo, String scopeChangedFrom, Group group) { - - } - - @override - void onMemberAddedToGroup(Action action, User addedby, User userAdded, Group addedTo) { - - } - -} -``` - - - - - -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. - - - -```dart -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. - -| 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. | - -To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. - - - -```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) { - - } - -} -``` - - - - - -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. diff --git a/sdk/flutter/v5/receive-messages.mdx b/sdk/flutter/v5/receive-messages.mdx deleted file mode 100644 index 92246df7f..000000000 --- a/sdk/flutter/v5/receive-messages.mdx +++ /dev/null @@ -1,641 +0,0 @@ ---- -title: "Receive A Message" ---- - - - -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 - -## Real-time Messages - -*In other words, as a recipient, how do I receive messages when my app is running?* - -For every activity or fragment you wish to receive messages in, you need to register the `MessageListener` using the `addMessageListener()` method. - -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 MessageListener { - -//CometChat.addMessageListener("listenerId", this); - @override -void onTextMessageReceived(TextMessage textMessage) { - debugPrint("Text message received successfully: $textMessage"); -} - -@override -void onMediaMessageReceived(MediaMessage mediaMessage) { - debugPrint("Media message received successfully: $mediaMessage"); -} - -@override -void onCustomMessageReceived(CustomMessage customMessage) { - debugPrint("Custom message received successfully: $customMessage"); -} - -@override -onInteractiveMessageReceived(InteractiveMessage message) { - -} - - -} -``` - - - - - -| 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 `dispose()` method. - - - -```dart -private String listenerID = "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 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 - -### For a Particular One-on-one Conversation - - - -```dart -int limit = 30; -int lastMessageId = -1; -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..limit = limit - ..messageId = lastMessageId - ).build(); - -messageRequest.fetchNext(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - - -### For a Particular Group Conversation - - - -```dart -int limit = 30; -int lastMessageId = -1; -String GUID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..guid = GUID - ..limit = limit - ..messageId = lastMessageId - ).build(); - -messageRequest.fetchNext(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("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` so that only the unread messages are fetched. - -### For a Particular One-on-one Conversation - - - -```dart -int limit = 30; -int lastMessageId = -1; -String GUID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..guid = GUID - ..limit = limit - ..messageId = lastMessageId - ..unread = true - ).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - - -### For a Particular Group Conversation - - - -```dart -int limit = 30; -int lastMessageId = -1; -String GUID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..guid = GUID - ..limit = limit - ..messageId = lastMessageId - ..unread = true - ).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - - - -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. - - - -## Message History - -*In other words, as a logged-in user, how do I fetch the message history for a user or a group conversation?* - -### 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 of the builder. This UID is the unique id of the user for which the conversation needs to be fetched. - - - -```dart -int limit = 30; -int lastMessageId = -1; -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..limit = limit - ).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("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. - -### For 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 of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched. - - - -```dart -int limit = 30; -String GUID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..guid = GUID - ..limit = limit - ).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - - -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 `searchKeyword` 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 | ❌ | ✅ | - -### For a Particular One-on-one Conversation - - - -```dart -int limit = 30; -int searchKeyword = "search keyboard"; -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..limit = limit - .searchKeyword=searchKeyword - ).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - - -### For a Particular Group Conversation - - - -```dart -int limit = 30; -int searchKeyword = "search keyboard"; -String GUID = "cometchat-guid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..guid = GUID - ..limit = limit - .searchKeyword=searchKeyword - ).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - for (BaseMessage message in list) { - if(message is TextMessage){ - debugPrint("Text message received successfully: "+(message as TextMessage).toString()); - }else if(message is MediaMessage){ - debugPrint("Media message received successfully: "+(message as MediaMessage).toString()); - } - } - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - - -## Unread Messages 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 - -*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: - - - -```dart -CometChat.getUnreadMessageCountForUser(String UID, Callbacks); -``` - - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: - - - -```dart -CometChat.getUnreadMessageCountForUser(String UID, boolean hideMessagesFromBlockedUsers, Callbacks); -``` - - - - - - - -```dart -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 -} -}); -``` - - - - - -In the `onSuccess()` callback, you will receive a `Map` which will contain the `UID` of the user as the key and the unread message count as the value. - -### For 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: - - - -```dart -Map? ab = await CometChat.getUnreadMessageCountForGroup(guid: guid); -``` - - - - - -If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: - - - -```dart -Map? ab = await CometChat.getUnreadMessageCountForGroup(guid: guid,hideMessagesFromBlockedUsers: hideBlockedUser); -``` - - - - - - - -```dart -private String GUID = "cometchat-guid-1" - -CometChat.getUnreadMessageCountForGroup(guid: GUID,hideMessagesFromBlockedUsers: hideBlockedUser, - onSuccess: (Map map) { - - }, - onError: (CometChatException e) { - - }); -``` - - - - - -In the `onSuccess()` callback, you will receive a `Map` which will contain the `GUID` of the group as the key and the unread message count as the value. - -### For 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: - - - -```dart -await CometChat.getUnreadMessageCount(); -``` - - - - - -If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: - - - -```dart -await CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: true); -``` - - - - - - - -```dart -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers: hideBlockedUser, - onSuccess: (Map> map) { - - },onError: (CometChatException e) { - - }); -``` - - - - - -In the `onSuccess()` callback, you will receive a `Map` having two keys: - -1. `user` - The value for this key holds another `Map` that holds the `UIDs` of users and their corresponding unread message counts. -2. `group` - The value for this key holds another `Map` that holds the `GUIDs` of groups and their corresponding unread message counts. - -### For Unread Count for 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: - - - -```dart -await CometChat.getUnreadMessageCountForAllUsers(); -``` - - - - - -If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to `true`: - - - -```dart -await CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: true); -``` - - - - - - - -```dart -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers, - onSuccess: (Map map) { - - }, - onError: (CometChatException e) { - - }); -``` - - - - - -In the `onSuccess()` callback, you will receive a `Map` that will contain the `UIDs` of users as the key and the unread message counts as the values. - -### Fetch Unread Count for all Group Conversations - -*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: - - - -```dart -await CometChat.getUnreadMessageCountForAllGroups(); -``` - - - - - -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to `true`: - - - -```dart -await CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: true); -``` - - - - - - - -```dart -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers: hideMessagesFromBlockedUsers, - onSuccess: (Map map) { - - }, - onError: (CometChatException e) { - - }); -``` - - - - - -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. diff --git a/sdk/flutter/v5/retrieve-conversations.mdx b/sdk/flutter/v5/retrieve-conversations.mdx deleted file mode 100644 index 690d1d42b..000000000 --- a/sdk/flutter/v5/retrieve-conversations.mdx +++ /dev/null @@ -1,384 +0,0 @@ ---- -title: "Retrieve Conversations" ---- - - - -## 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: - -### Set Limit - -This method sets the limit i.e. the number of conversations that should be fetched in a single iteration. - - - -```dart -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: - -* 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. - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..conversationType = CometChatConversationType.user -).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. - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..withUserAndGroupTags = true -).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` - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..withTags = true -).build(); -``` - - - - - -### Set Tags - -This method helps you fetch the conversations based on the specified tags. - - - -```dart -List tags = []; -tags.add("archived"); -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..tags = tags -).build(); -``` - - - - - -### Include Blocked Users - -This method helps you fetch the conversations of users whom the logged-in user has blocked. - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..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. - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..withBlockedInfo = true -).build(); -``` - - - - - -### Search Conversations - -This method helps you search a conversation based on 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) - - - - - -```dart - ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..searchKeyword = "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) - - - - - -```dart - ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..unread = true - ).build(); -``` - - - - - -### Filter by User Tags - -This method helps you filter conversations based on specific user tags. - - - -```dart -List userTags = ["premium", "verified"]; -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..userTags = userTags -).build(); -``` - - - - - -### Filter by Group Tags - -This method helps you filter conversations based on specific group tags. - - - -```dart -List groupTags = ["support", "sales"]; -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..groupTags = groupTags -).build(); -``` - - - - - -### Hide Agentic Conversations - -This method helps you hide AI-driven (agentic) conversations from the list. Agentic conversations are those involving AI agents. - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ..hideAgentic = true -).build(); -``` - - - - - -### Only Agentic Conversations - -This method helps you fetch only AI-driven (agentic) conversations. This is useful when you want to display a separate list of 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. - -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. - -A Maximum of only 50 Conversations can be fetched at once. - - - -```dart -ConversationsRequest conversationRequest = (ConversationsRequestBuilder() - ..limit = 50 - ).build(); - -conversationRequest.fetchNext( - onSuccess: (List conversations){ - - - }, onError: (CometChatException e){ - - } -``` - - - - - -The `Conversation`object consists of the below fields: - -| Field | Information | -| --------------------- | -------------------------------------------------------------------- | -| `conversationId` | ID of the conversation | -| `conversationType` | Type of conversation (user/group) | -| `lastMessage` | Last message the conversation | -| `conversationWith` | `User` or `Group` object containing the details of the user or group | -| `unreadMessageCount` | Unread message count for the conversation | -| `unreadMentionsCount` | the count of unread mentions in the conversation. | -| `lastReadMessageId` | the ID of the last read message in the conversation (int type). | - -## Tag Conversation - -*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: - - 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. - - - -```dart -String conversationWith = "cometchat-uid-1"; //id of the user/group -String conversationType = "user"; -List tags = []; -tags.add("archived"); - -CometChat.tagConversation(conversationWith, conversationType, tags, - onSuccess: (Conversation conversation) { - debugPrint("Conversation tagged Successfully : $conversation"); - }, onError: (CometChatException e) { - debugPrint("Conversation tagging failed : ${e.message}"); - } -); -``` - - - - - - - -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?* - -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: - -* user - Only fetches user conversation. -* group - Only fetches group conversations. - - - -```dart -String conversationWith = "cometchat-uid-1"; //id of the user/group -String conversationType = "user"; -CometChat.getConversation(conversationWith, conversationType, - onSuccess: (Conversation conversation) { - debugPrint("Fetch Conversation Successfully : $conversation"); - }, onError: (CometChatException e) { - debugPrint("Fetch Conversation failed : ${e.message}"); - } -); -``` - - - - - -## 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. - - - -```dart -Conversation conversation = CometChat.getConversationFromMessage(message); -``` - - - - - - - -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. - - diff --git a/sdk/flutter/v5/retrieve-group-members.mdx b/sdk/flutter/v5/retrieve-group-members.mdx deleted file mode 100644 index 517799414..000000000 --- a/sdk/flutter/v5/retrieve-group-members.mdx +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: "Retrieve Group Members" ---- - - - -## 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. - -### Set Limit - -This method sets the limit i.e. the number of members that should be fetched in a single iteration. - - - -```dart -String GUID = "GUID"; - GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) - ..limit = 20 - ).build(); -``` - - - - - -### Set Search Keyword - -This method allows you to set the search string based on which the group members are to be fetched. - - - -```dart -String GUID = "GUID"; -GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) - ..limit = 20 - ..searchKeyword = "abc" - ).build(); -``` - - - - - -### Set Scopes - -This method allows you to fetch group members based on the specified scopes. - - - -```dart -List scopes =[]; -scopes.add("admin"); -scopes.add("moderator"); -String GUID = "GUID"; -GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) - ..limit = 20 - ..scopes = scopes - ).build(); -``` - - - - - -### Set Status - -This method allows you to filter group members based on their online/offline status. - - - -```dart -String GUID = "GUID"; -GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) - ..limit = 20 - ..status = CometChatUserStatus.online // or CometChatUserStatus.offline - ).build(); -``` - - - - - -The `status` parameter can contain one of the below two values: -* `CometChatUserStatus.online` - will return only online group members. -* `CometChatUserStatus.offline` - will return only offline group members. - -If this parameter is not set, all group members will be returned regardless of their status. - -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. - - - -```dart -String GUID = "GUID"; -GroupMembersRequest groupMembersRequest = (GroupMembersRequestBuilder(GUID) - ..limit = 20 - ).build(); - -groupMembersRequest.fetchNext(onSuccess: (List groupMemberList){ - debugPrint("Group Members fetched Successfully : $groupMemberList "); - }, onError: (CometChatException e) { - debugPrint("Delete Group failed with exception: ${e.message}"); - }); -``` - - - - diff --git a/sdk/flutter/v5/retrieve-groups.mdx b/sdk/flutter/v5/retrieve-groups.mdx deleted file mode 100644 index 23417e0b0..000000000 --- a/sdk/flutter/v5/retrieve-groups.mdx +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: "Retrieve Groups" ---- - - - -## Retrieve List of Groups - -*In other words, as a logged-in user, how do I retrieve the list of groups I've joined and groups that are available?* - -In order to fetch the list of groups, you can use the `GroupsRequest` class. To use this class i.e to create an object of the `GroupsRequest` class, you need to use the `GroupsRequestBuilder` class. The `GroupsRequestBuilder` class allows you to set the parameters based on which the groups are to be fetched. - -### Set Limit - -This method sets the limit i.e. the number of groups that should be fetched in a single iteration. - - - -```dart -GroupsRequest groupsRequest = (GroupsRequestBuilder() - ..limit= 20 -).build(); -``` - - - - - -### Set Search Keyword - -This method allows you to set the search string based on which the groups are to be fetched. - - - -```dart -GroupsRequest groupsRequest = (GroupsRequestBuilder() - ..limit= 20 - ..searchKeyword = "abc" -).build(); -``` - - - - - -### Joined Only - -This method when used, will ask CometChat to only return the groups that the user has joined or is a part of. - - - -```dart -GroupsRequest groupsRequest = (GroupsRequestBuilder() - ..limit= 20 - ..joinedOnly = true -).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. - - - -```dart -List tags =[]; -tags.add("archived"); -GroupsRequest groupsRequest = (GroupsRequestBuilder() - ..limit= 20 - ..tags = tags -).build(); -``` - - - - - -### With Tags - -This property when set to true will fetch tags data along with the list of groups. - - - -```dart -GroupsRequest groupsRequest = (GroupsRequestBuilder() - ..limit= 20 - ..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. - -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. - -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. - - - -```dart -GroupsRequest groupsRequest = (GroupsRequestBuilder() - ..limit= 20 -).build(); - -groupsRequest.fetchNext(onSuccess: (List groupList) { - debugPrint("Fetched Group Successfully : $groupList "); - }, onError: (CometChatException e) { - debugPrint("Group Request failed with exception: ${e.message}"); - }); -``` - - - - - -## 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. - - - -```dart -String GUID = "GUID"; - -CometChat.getGroup(GUID, onSuccess: (Group group) { - debugPrint("Fetched Group Successfully : $group "); - }, onError: (CometChatException e) { - debugPrint("Group Request failed with exception: ${e.message}"); - }); -``` - - - - - -| Parameter | Description | -| --------- | ------------------------------------------------------------ | -| `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. - -## Get online group member count - -To get the total count of online users in particular groups, you can use the `getOnlineGroupMemberCount()` method. - - - -```dart -List guids = []; -guids.add("cometchat-guid-1"); -guids.add("cometchat-guid-11"); - -CometChat.getOnlineGroupMemberCount(guids, - onSuccess: (Map count) { - debugPrint("Fetched Online Group Member Count Successfully : $count "); - }, onError: (CometChatException e) { - debugPrint("Online Group Member failed with exception: ${e.message}"); - }); -``` - - - - - -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. diff --git a/sdk/flutter/v5/retrieve-users.mdx b/sdk/flutter/v5/retrieve-users.mdx deleted file mode 100644 index 9284b158f..000000000 --- a/sdk/flutter/v5/retrieve-users.mdx +++ /dev/null @@ -1,337 +0,0 @@ ---- -title: "Retrieve Users" ---- - - - -## 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. - - - -```dart -User user = await CometChat.getLoggedInUser() -``` - - - - - -This method will return a `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: - -### Set Limit - -This method sets the limit i.e. the number of users that should be fetched in a single iteration. - - - -```dart -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. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..searchKeyword = "abc" - ).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: - -* CometChatUserStatus.online - will return the list of only online users. -* CometChatUserStatus.offline - will return the list of only offline users. - -If this parameter is not set, will return all the available users. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..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. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..hideBlockedUsers = true - ).build(); -``` - - - - - -### Set Roles - -This method allows you to fetch the users based on multiple roles. - - - -```dart -List roles = []; -roles.add("role1"); -roles.add("role2"); -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..roles = roles - ).build(); -``` - - - - - -### Friends Only - -This property when set to true will return only the friends of the logged-in user. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..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. - - - -```dart -List tags = []; -tags.add("tag1"); -tags.add("tag2"); -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..tags = tags - ).build(); -``` - - - - - -### With Tags - -This property when set to true will fetch tags data along with the list of users. - - - -```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. - - - -```dart -List uids = []; -uids.add("UID1"); -uids.add("UID2"); -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 25 - ..uids = uids - ).build(); -``` - - - - - -### Search In - -This method allows you to specify which user fields to search in when using the search keyword. You can search in `name`, `uid`, or both. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..searchKeyword = "john" - ..searchIn = ["name", "uid"] - ).build(); -``` - - - - - -### Sort By - -This method allows you to specify the field by which the users should be sorted. You can sort by `name`, `status`, or `createdAt`. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..sortBy = "name" - ).build(); -``` - - - - - -### Sort By Order - -This method allows you to specify the order in which the users should be sorted. You can use `asc` for ascending or `desc` for descending order. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..sortBy = "name" - ..sortByOrder = "asc" - ).build(); -``` - - - - - -You can combine these parameters for more precise user filtering and ordering: - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 50 - ..searchKeyword = "john" - ..searchIn = ["name"] - ..sortBy = "name" - ..sortByOrder = "asc" - ).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 depending on the limit set. - - - -```dart -UsersRequest usersRequest = (UsersRequestBuilder() - ..limit = 25 - ).build(); - -usersRequest.fetchNext(onSuccess: (List userList){ - debugPrint("User List Fetched Successfully : $userList"); - },onError: (CometChatException e){ - debugPrint("User List Fetch Failed: ${e.message}"); - }); -``` - - - - - -## Retrieve Particular User Details - -To get the information of a user, you can use the `getUser()` method. - - - -```dart -String UID = "UID"; - -CometChat.getUser(UID, onSuccess: (User user){ - debugPrint("User Fetched Successfully : $user"); - }, onError: (CometChatException e){ - debugPrint("User Fetch Failed: ${e.message}"); - }); -``` - - - - - -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 `User` object containing the details of the user is returned. - -## Get online user count - -To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. - - - -```dart -CometChat.getOnlineUserCount(onSuccess: (int count){ - debugPrint("Online User Count: $count"); - }, onError: (CometChatException e){ - debugPrint("User Count Fetch Failed: ${e.message}"); - }); -``` - - - - diff --git a/sdk/flutter/v5/send-message.mdx b/sdk/flutter/v5/send-message.mdx deleted file mode 100644 index fd2c833d9..000000000 --- a/sdk/flutter/v5/send-message.mdx +++ /dev/null @@ -1,646 +0,0 @@ ---- -title: "Send A Message" ---- - - - -Using CometChat, you can send three types of messages: - -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 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 `Map` to it. - - - -```dart -Map metadata = {}; -metadata["lattitude"] = "50.6192171633316" ; -metadata["longitude"] = "-72.68182268750002" ; -textMessage.metadata = metadata; -``` - - - - - -### Add Tags - -To add a tag to a message you can assign value in `.tags` variable of the TextMessage Class. `tags` accepts a list of tags. - - - -```dart -List tags = []; -tags.add("pinned"); -textMessage.tags = tags; -``` - - - - - -Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. - - - -```dart -String receiverID = "cometchat-uid-1"; -String messageText = "messageText"; -String receiverType = CometChatConversationType.user; -String type = CometChatMessageType.text; - -TextMessage textMessage = TextMessage(text: messageText, - receiverUid: receiverID, - receiverType: receiverType, - type: type); -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 = "cometchat-guid-1"; -String messageText = "messageText"; -String receiverType = CometChatConversationType.group; -String type = CometChatMessageType.text; - -TextMessage textMessage = TextMessage(text: messageText, - receiverUid: receiverID, - receiverType: receiverType, - type: type); -CometChat.sendMessage(textMessage, onSuccess: (TextMessage message) { -debugPrint("Message sent successfully: $message"); -}, onError: (CometChatException e) { -debugPrint("Message sending failed with exception: ${e.message}"); -}); -``` - - - - - -The `TextMessage` class constructor takes the following parameters: - -| Parameter | Description | | -| -------------- | -------------------------------------------------------------------------------------------------------------- | -------- | -| `receiverID` | `UID` of the user or `GUID` of the group receiving the message | Required | -| `messageText` | The text message | Required | -| `receiverType` | The type of the receiver- `CometChatReceiverType.user` (user) or `CometChatReceiverType.group` (group) | Required | -| type | The type of the message that needs to be sent which in this case can be: `CometChatMessageType.text`\_\_(text) | | - -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 `setQuotedMessageId` and `setQuotedMessage` method of the TextMessage class. This method accepts the ID of the message to be quoted. - - - - -```dart -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. - - - -```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}"); - }, - ); -``` - - - -```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}"); - }, - ); -``` - - - - - -The `TextMessage` class constructor takes the following parameters: - -| Parameter | Description | | -| -------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------- | -| `receiverID` | `UID` of the user or `GUID` of the group receiving the message | Required | -| `messageText` | The text message | Required | -| `receiverType` | The type of the receiver- `CometChatConstants.RECEIVER_TYPE_USER` (user) or `CometChatConstants.RECEIVER_TYPE_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. - -## 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 `Map` to it. - - - -```dart -Map metadata = {}; -metadata["lattitude"] = "50.6192171633316" ; -metadata["longitude"] = "-72.68182268750002" ; -mediaMessage.metadata = metadata; -``` - - - - - -### Add Caption(Text along with Media Message) - - - -```dart -mediaMessage.caption = "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. - - - -```dart -List tags = []; -tags.add("pinned"); -mediaMessage.tags = tags; -``` - - - - - -There are 2 ways you can send Media Messages using the CometChat SDK: - -1. **By providing the File :** You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the sendMediaMessage() method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the sendMediaMessage() function. - - - -```dart -String receiverID; -String messageType = CometChatMessageType.image; -String receiverType = CometChatConversationType.user ; -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}"); - } -); -``` - - - - - -The `MediaMessage` class constructor takes the following parameters: - -| Parameter | Description | | -| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -| receiverId | The UID or GUID of the recipient | Required | -| file | The file object to be sent | Required | -| messageType | The type of the message that needs to be sent which, in this case, can be:
1. `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: - - - -```dart -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}"); - } -); -``` - - - - - -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 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`. - -### Send Multiple Media Files - -You can send multiple media files (images, videos, audio, or documents) in a single message. This enables richer and more efficient conversations. - - - -```dart -String receiverID = "cometchat-uid-1"; -String receiverType = CometChatConversationType.user; -String messageType = CometChatMessageType.image; - -// Create a list of file paths -List filePaths = [ - "storage/emulated/0/Download/image1.jpg", - "storage/emulated/0/Download/image2.jpg", - "storage/emulated/0/Download/image3.jpg", -]; - -MediaMessage mediaMessage = MediaMessage( - receiverType: receiverType, - type: messageType, - receiverUid: receiverID, - files: filePaths, // Use 'files' for multiple files -); - -await CometChat.sendMediaMessage(mediaMessage, - onSuccess: (MediaMessage message) { - debugPrint("Multiple media files sent successfully"); - // Access the list of attachments - List? attachments = message.attachments; - for (var attachment in attachments ?? []) { - debugPrint("Attachment URL: ${attachment.fileUrl}"); - } - }, - onError: (CometChatException e) { - debugPrint("Media message sending failed: ${e.message}"); - } -); -``` - - - - - -### File Size and Count Validation - -The SDK automatically validates file size and count when sending media messages. You can configure these limits through Settings in the CometChat Dashboard. - -| Validation | Description | -|------------|-------------| -| File Size | Maximum size per file (configurable in Dashboard) | -| File Count | Maximum number of files per message (configurable in Dashboard) | - -If validation fails, the `onError` callback will be triggered with details about the validation error. - - - -```dart -await CometChat.sendMediaMessage(mediaMessage, - onSuccess: (MediaMessage message) { - debugPrint("Media message sent successfully"); - }, - onError: (CometChatException e) { - // Handle validation errors - if (e.code == "ERR_FILE_SIZE_EXCEEDED") { - debugPrint("File size exceeds the allowed limit"); - } else if (e.code == "ERR_FILE_COUNT_EXCEEDED") { - debugPrint("Too many files in a single message"); - } else { - debugPrint("Error: ${e.message}"); - } - } -); -``` - - - - - -## 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. - - - -```dart -CustomMessage customMessage = CustomMessage( receiverUid: UID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, - ); -``` - - - - - -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. `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`. - -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 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. - - - -```dart -List tags = []; -tags.add("pinned"); -textMessage.tags = tags; -``` - - - - - -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. - - - -```dart -String UID = "UID"; -String subType = "LOCATION"; -String receiverType = CometChatConversationType.user; -String type = CometChatMessageType.custom; - -Map customData = {}; -customData["latitude"] = "19.0760"; -customData["longitude"] = "72.8777"; - -CustomMessage customMessage = CustomMessage( - receiverUid: UID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, -); - -CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { - debugPrint("Custom Message Sent Successfully : $message"); -}, onError: (CometChatException e) { - debugPrint("Custom message sending failed with exception: ${e.message}"); -}); -``` - - - - -```dart -String GUID = "GUID"; -String subType = "LOCATION"; -String receiverType = CometChatConversationType.group; -String type = CometChatMessageType.custom; - -Map customData = {}; -customData["latitude"] = "19.0760"; -customData["longitude"] = "72.8777"; - -CustomMessage customMessage = CustomMessage( - receiverUid: GUID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, -); - -CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { - debugPrint("Custom Message Sent Successfully : $message"); -}, onError: (CometChatException e) { - debugPrint("Custom message sending failed with exception: ${e.message}"); -}); -``` - - - - - -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 - -*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 `updateConversation` (boolean value) method of the Custom Message. - - - -```dart -String UID = "UID"; -String subType = "LOCATION"; -String receiverType = CometChatConversationType.user; -String type = CometChatMessageType.custom; - -Map customData = {}; -customData["latitude"] = "19.0760"; -customData["longitude"] = "72.8777"; - -CustomMessage customMessage = CustomMessage( - receiverUid: UID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, -); -customMessage.updateConversation = false; - -CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { - debugPrint("Custom Message Sent Successfully : $message"); -}, onError: (CometChatException e) { - debugPrint("Custom message sending failed with exception: ${e.message}"); -}); -``` - - - - -```dart -String GUID = "GUID"; -String subType = "LOCATION"; -String receiverType = CometChatConversationType.group; -String type = CometChatMessageType.custom; - -Map customData = {}; -customData["latitude"] = "19.0760"; -customData["longitude"] = "72.8777"; - -CustomMessage customMessage = CustomMessage( - receiverUid: GUID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, -); -customMessage.updateConversation = false; - -CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { - debugPrint("Custom Message Sent Successfully : $message"); -}, onError: (CometChatException e) { - debugPrint("Custom message sending failed with exception: ${e.message}"); -}); -``` - - - - - -### 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` method of Custom Message class. - - - -```dart -String UID = "UID"; -String subType = "LOCATION"; -String receiverType = CometChatConversationType.user; -String type = CometChatMessageType.custom; - -Map customData = {}; -customData["latitude"] = "19.0760"; -customData["longitude"] = "72.8777"; - -CustomMessage customMessage = CustomMessage( - receiverUid: UID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, -); -customMessage.conversationText = "Custom Notification Body"; - -CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { - debugPrint("Custom Message Sent Successfully : $message"); -}, onError: (CometChatException e) { - debugPrint("Custom message sending failed with exception: ${e.message}"); -}); -``` - - - - -```dart -String GUID = "GUID"; -String subType = "LOCATION"; -String receiverType = CometChatConversationType.group; -String type = CometChatMessageType.custom; - -Map customData = {}; -customData["latitude"] = "19.0760"; -customData["longitude"] = "72.8777"; - -CustomMessage customMessage = CustomMessage( - receiverUid: GUID, - type: type, - customData: customData, - receiverType: receiverType, - subType: subType, -); -customMessage.conversationText = "Custom Notification Body"; - -CometChat.sendCustomMessage(customMessage, onSuccess: (CustomMessage message) { - debugPrint("Custom Message Sent Successfully : $message"); -}, onError: (CometChatException e) { - debugPrint("Custom message sending failed with exception: ${e.message}"); -}); -``` - - - - - - - -It is also possible to send interactive messages from CometChat , to know more [click here](/sdk/flutter/interactive-messages) - - diff --git a/sdk/flutter/v5/setup.mdx b/sdk/flutter/v5/setup.mdx deleted file mode 100644 index 62827343b..000000000 --- a/sdk/flutter/v5/setup.mdx +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: "Setup" ---- - - -This is a **beta release** of the CometChat Flutter Chat SDK v5. APIs and features may change before the stable release. - - -### 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 - -* Android API Level 21 -* AndroidX Compatibility -* iOS 11 or higher -* Flutter SDK 1.2 or higher - - - -### Add the CometChat Dependency - -### Cloudsmith (Current Beta) - -For the current beta release, add the Cloudsmith hosted repository and dependency to your `pubspec.yaml`: - -```yaml -dependencies: - cometchat_sdk: - hosted: - url: https://dart.cloudsmith.io/cometchat/cometchat/ - version: 5.0.0-beta.1 -``` - -Then run: -```bash -flutter pub get -``` - - -**Upgrading from v4?** - -If you're migrating an existing app from CometChat SDK v4, check out the [Upgrading from v4](/sdk/flutter/v5/upgrading-from-v4-guide) guide for breaking changes, deprecated methods, and migration instructions. - - -2. Add following code to podfile inside iOS section of your app - - - -```ruby -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 -``` - - - - - - -**Apple Silicon (M1/M2/M3) users:** Excluding `arm64` from the simulator build prevents the app from running natively on Apple Silicon Macs. If you are developing on an Apple Silicon Mac, consider excluding only `i386` instead of `arm64 i386` to enable native simulator builds. - - -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 - - - - - -Import CometChat SDK using following code in dart - - - -```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. - -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. - - - -```dart -String region = "REGION"; -String appId = "APP_ID"; - -AppSettings appSettings= (AppSettingsBuilder() - ..subscriptionType = CometChatSubscriptionType.allUsers - ..region= region - ..adminHost = "" //optional - ..clientHost = "" //optional - ..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}"); - } -); -``` - - - - - -We suggest you call the `init()` method on app startup. - -## 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 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 in background | Disconnect the WebSocket connection if no ping is received within 30 seconds after the app goes in the background. | diff --git a/sdk/flutter/v5/threaded-messages.mdx b/sdk/flutter/v5/threaded-messages.mdx deleted file mode 100644 index 330506158..000000000 --- a/sdk/flutter/v5/threaded-messages.mdx +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: "Threaded Messages" ---- - - - -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](send-message) section, you can send a message to a User or a Group by mentioning the receiver (uid/guid) and `receiverType`(user/group). - -A message can be categorized as: - -1. Text Message -2. Media Message -3. Custom Message. -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. - -**Example to Send a Text Message in a thread in a user conversation.** - - - -```dart -String receiverID = "UID"; -String messagesText = "Hello"; -String receiverType = CometChatConversationType.user; -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"); -}, onError: (CometChatException e) { -debugPrint("Message sending failed with exception: ${e.message}"); -}); -``` - - - - -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. - - - -```dart -class Class_Name with MessageListener { - int activeParentMessageId= 103; -//CometChat.addMessageListener("listenerId", this); - @override -void onTextMessageReceived(TextMessage textMessage) { - if(textMessage.parentMessageId == activeParentMessageId){ - debugPrint("Text message received successfully: $textMessage"); - } - -} - -@override -void onMediaMessageReceived(MediaMessage mediaMessage) { - if(mediaMessage.parentMessageId== activeParentMessageId){ - debugPrint("Media message received successfully: $mediaMessage"); - } -} - -@override -void onCustomMessageReceived(CustomMessage customMessage) { - if(customMessage.parentMessageId== activeParentMessageId){ - debugPrint("Custom message received successfully: $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. - -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. - -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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..parentMessageId = 103 - ..limit = 50).build(); - -messageRequest.fetchPrevious(onSuccess: (List list) { - debugPrint("Message fetching Successful"); - }, onError: (CometChatException e) { - debugPrint("Message fetching failed with exception: ${e.message}"); - }); -``` - - - - -## Avoid Threaded Messages in User/Group Conversations - -While fetching messages for normal user/group conversations using the `MessagesRequest`, the threaded messages by default will be a part of the list of messages received. In order to exclude the threaded messages from the list of user/group messages, you need to use the `hideReplies` 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. - - - -```dart -String UID = "cometchat-uid-1"; - -MessagesRequest messageRequest = (MessagesRequestBuilder() - ..uid = UID - ..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 diff --git a/sdk/flutter/v5/transfer-group-ownership.mdx b/sdk/flutter/v5/transfer-group-ownership.mdx deleted file mode 100644 index 5c2b8b668..000000000 --- a/sdk/flutter/v5/transfer-group-ownership.mdx +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: "Transfer Group Ownership" ---- - - - -*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. - -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. - - - -```dart -String UID = "cometchat-uid-1"; -String GUID = conversationWith; -CometChat.transferGroupOwnership(guid: GUID,uid: UID, - onSuccess: (String message) { - debugPrint("Owner Transferred Successfully : $message"); - }, - onError: (CometChatException e) { - debugPrint("Owner Transferred failed : ${e.message}"); - }); -``` - - - - diff --git a/sdk/flutter/v5/transient-messages.mdx b/sdk/flutter/v5/transient-messages.mdx deleted file mode 100644 index e39b5e46f..000000000 --- a/sdk/flutter/v5/transient-messages.mdx +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: "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. - - - -```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}"); -}); -``` - - - - - -## 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. - - - -```dart -class Class_Name with MessageListener { - -//CometChat.addMessageListener("listenerId", this); -@override -void onTransientMessageReceived(TransientMessage message) { - // TODO: implement onTransientMessageReceived -} - - -} -``` - - - - - -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 - `CometChatReceiverType.user` (user) or `CometChatReceiverType.``group `(group) | -| **data** | A Map to provide data. | diff --git a/sdk/flutter/v5/typing-indicators.mdx b/sdk/flutter/v5/typing-indicators.mdx deleted file mode 100644 index c3787c105..000000000 --- a/sdk/flutter/v5/typing-indicators.mdx +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: "Typing Indicators" ---- - - - -## Send a Typing Indicator - -*In other words, as a sender, how do I let the recipient(s) know that I'm typing?* - -### Start Typing - -You can use the `startTyping()` method to inform the receiver that the logged in user has started typing. The receiver will receive this information in the `onTypingStarted()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. - - - -```dart -CometChat.startTyping( - receiverUid: "UID", - receiverType: CometChatReceiverType.user, - ); -``` - - - - -```dart -CometChat.startTyping( - receiverUid: "GUID", - receiverType: CometChatReceiverType.group, - ); -``` - - - - - -### 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. - - - -```dart -CometChat.endTyping( - receiverUid: "UID", - receiverType: CometChatReceiverType.user); -``` - - - - -```dart -CometChat.endTyping( - receiverUid: "GUID", - receiverType: CometChatReceiverType.group); -``` - - - - - - -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 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. - - - -## 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. - - - -```dart -class Class_Name with MessageListener { - -//CometChat.addMessageListener("listenerId", this); -@override -void onTypingStarted(TypingIndicator typingIndicator) { - // TODO: implement onTypingStarted -} - -@override -void onTypingEnded(TypingIndicator typingIndicator) { - // TODO: implement onTypingEnded -} - - -} -``` - - - - - -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` | `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 | diff --git a/sdk/flutter/v5/update-group.mdx b/sdk/flutter/v5/update-group.mdx deleted file mode 100644 index c9353f983..000000000 --- a/sdk/flutter/v5/update-group.mdx +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: "Update A Group" ---- - - - -## Update Group - -*In other words, as a group owner, how can I update the group details?* - -You can update the existing details of the group using the `updateGroup()` method. - - - -```dart -String GUID = "GUID"; - String groupName = "Hello Group!"; - String groupType = CometChatGroupType.public; - String password = ""; - - Group _group = Group(guid: GUID, name: groupName, type: groupType); - - - await CometChat.updateGroup(group: _group, onSuccess: (Group group ){ - debugPrint("Group Created Successfully : $group "); - }, onError:(CometChatException e) { - debugPrint("Group Creation failed with exception: ${e.message}"); - } ); -``` - - - - - -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 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) diff --git a/sdk/flutter/v5/user-management.mdx b/sdk/flutter/v5/user-management.mdx deleted file mode 100644 index b58d3da36..000000000 --- a/sdk/flutter/v5/user-management.mdx +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: "User Management" ---- - - - -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** - -1. You add the user details in your database -2. You create a user in CometChat - -**When a user logs into your app** - -1. You log in the user to your app -2. You [log in the user to CometChat](https://app.cometchat.com/login) - -## 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. - -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/flutter/user-management#user-class) - - - -```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}"); - - }); -``` - - - - - - - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - - -## 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. - -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. - - - -```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}"); - }); -``` - - - - - -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 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 Class - -| Field | Editable | Information | -| ------------- | --------------------------------------------------- | -------------------------------------------------------------------- | -| uid | specified on user creation. Not editable after that | Unique identifier of the user | -| name | Yes | Display name of the user | -| avatar | Yes | URL to profile picture of the user | -| link | Yes | URL to profile page | -| role | Yes | User role of the user for role based access control | -| metadata | Yes | Additional information about the user as JSON | -| status | No | Status of the user. Could be either online/offline | -| 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 | -| tags | Yes | A list of tags to identify specific users | diff --git a/sdk/flutter/v5/user-presence.mdx b/sdk/flutter/v5/user-presence.mdx deleted file mode 100644 index a9721a3d9..000000000 --- a/sdk/flutter/v5/user-presence.mdx +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: "User Presence" ---- - - - -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?* - -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. - -For presence subscription, the `AppSettingsBuilder` provides 3 methods : - -* `subscribePresenceForAllUsers()` - This will inform the logged-in user when any user in the app comes online or goes offline. -* `subscribePresenceForRoles(List roles)` - This will inform the logged-in user, only when the users with the specified roles come online or go offline. -* `subscribePresenceForFriends()` - This will inform the logged-in user when any of their friends come online or go offline. - -If none of the above methods are set, no presence will be sent to the logged-in user. - -For every activity or fragment you wish to receive user events in, you need to register the `UserListener` using the `addUserListener()` method. - -We suggest adding the listener in the `init` method of the activity or the fragment where you wish to receive these events in. - - - -```dart -class Class_Name with UserListener { - -//CometChat.addUserListener("user_Listener_id", this); - @override -void onUserOnline(User user) { - // TODO: implement onUserOnline -} -@override -void onUserOffline(User user) { - // TODO: implement onUserOffline -} - - -} -``` - - - - - -| Parameter | Description | -| ------------ | ----------------------------------------------------------------------------------------------- | -| `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 listener is not in use. - - - -```dart -String listenerID = "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 [retrieve the list of users](/sdk/flutter/retrieve-users) , in the[User](/sdk/flutter/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. diff --git a/sdk/flutter/v5/users-overview.mdx b/sdk/flutter/v5/users-overview.mdx deleted file mode 100644 index 8dcfcd91e..000000000 --- a/sdk/flutter/v5/users-overview.mdx +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: "Users" -sidebarTitle: "Overview" ---- - -A user is anyone who uses CometChat. The primary aim for the users functionality is to allow you to quickly retrieve and add users to CometChat. - -## UID - -- Each user is uniquely identified using a UID. -- The UID is typically the primary ID of the user from your database. - - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - - -## Auth Token - -- A single user can have multiple auth tokens. Auth tokens should be per user per device. -- It should 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. - -## 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. - -## Next Steps - -- [User Management](/sdk/flutter/v5/user-management) — sync your users to CometChat -- [Retrieve Users](/sdk/flutter/v5/retrieve-users) — fetch and display users in your app diff --git a/sdk/flutter/v5/webhooks-overview.mdx b/sdk/flutter/v5/webhooks-overview.mdx deleted file mode 100644 index 6c9724091..000000000 --- a/sdk/flutter/v5/webhooks-overview.mdx +++ /dev/null @@ -1,4 +0,0 @@ ---- -title: "Webhooks" -url: "/fundamentals/webhooks" ---- \ No newline at end of file diff --git a/sdk/flutter/webhooks-overview.mdx b/sdk/flutter/webhooks-overview.mdx index d52007a59..6c9724091 100644 --- a/sdk/flutter/webhooks-overview.mdx +++ b/sdk/flutter/webhooks-overview.mdx @@ -1,115 +1,4 @@ --- 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" ---- - - - -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 - - +--- \ No newline at end of file diff --git a/sdk/ios/campaigns.mdx b/sdk/ios/campaigns.mdx new file mode 100644 index 000000000..d1d08743a --- /dev/null +++ b/sdk/ios/campaigns.mdx @@ -0,0 +1,499 @@ +--- +title: "Campaigns" +description: "CometChat Campaigns SDK APIs — fetching feed items, managing engagement state, reporting interactions, and receiving real-time notifications." +--- + +CometChat Campaigns lets you deliver targeted, rich notifications to users via an in-app notification feed. Each notification is a Card Schema JSON — a structured layout rendered natively by the CometChat Cards library. The SDK provides APIs to fetch feed items, listen for real-time delivery, mark items as read/delivered, report engagement, and retrieve unread counts. + +--- + +## CometChatCardsSwift + +`CometChatCardsSwift` is the rendering library for Campaigns. The `NotificationFeedItem.content` field contains a Card Schema JSON — a structured layout definition. `CometChatCardsSwift` takes this JSON and produces a native UIKit view. Without it, `content` is just a raw dictionary. + +The library: + +- Parses the JSON schema into typed Swift models. +- Renders native UIKit views (no web views) for each element (text, images, buttons, rows, etc.). +- Handles light/dark mode color resolution from themed color pairs. +- Manages interactive actions — button taps emit structured `CometChatCardActionEvent` objects with the action type and element ID. +- Supports dynamic content — accordions expand/collapse, tabs switch panels, all with proper auto-layout height changes. + +If you use `CometChatNotificationFeed` (UI Kit), the Cards library is used internally and you don't interact with it directly. If you're building a custom feed UI, you import `CometChatCardsSwift` and use `CometChatCardView` to render each item's content. + +--- + +## Setting Up CometChatCardsSwift + +### Installation + +**Swift Package Manager** + +In Xcode: **File → Add Package Dependencies** → enter: + +``` +https://github.com/cometchat/cometchat-cards-sdk-ios +``` + +Add `CometChatCardsSwift` to your target. + +**CocoaPods** + +```ruby +pod 'CometChatCardsSwift' +``` + +```bash +pod install +``` + +No initialization is required. The library is stateless — import it and start rendering. + +### Rendering Feed Items as Cards + +```swift +import CometChatSDK +import CometChatCardsSwift + +// After fetching items via NotificationFeedRequest +request.fetchNext(onSuccess: { items in + for item in items { + guard let jsonData = try? JSONSerialization.data(withJSONObject: item.content), + let jsonString = String(data: jsonData, encoding: .utf8) else { continue } + + let cardView = CometChatCardView(frame: .zero) + cardView.translatesAutoresizingMaskIntoConstraints = false + cardView.themeMode = .auto + cardView.cardJson = jsonString + + cardView.actionCallback = { actionEvent in + // Report engagement on every action + CometChat.reportFeedEngagement(item, interactionString: actionEvent.elementId, onSuccess: {}, onError: { _ in }) + + switch actionEvent.action { + case .openUrl(let url, _): + if let link = URL(string: url) { + UIApplication.shared.open(link) + } + case .chatWithUser(let uid): + // Navigate to 1-on-1 chat + break + case .chatWithGroup(let guid): + // Navigate to group chat + break + default: + break + } + } + + container.addSubview(cardView) + } +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +### CometChatCardView Properties + +| Property | Type | Description | +| -------- | ---- | ----------- | +| `cardJson` | `String?` | Set this to render a card. Triggers a full re-render. | +| `themeMode` | `CometChatCardThemeMode` | `.auto` (follows system), `.light`, or `.dark`. | +| `actionCallback` | `((CometChatCardActionEvent) -> Void)?` | Called when user taps a button, link, or icon button inside the card. | +| `themeOverride` | `CometChatCardThemeOverride?` | Override default theme colors without modifying card JSON. | + +### Theme Override + +Override default card theme colors to match your app's brand: + +```swift +var override = CometChatCardThemeOverride() +override.textColor = CometChatCardColorValue(light: "#1A1A1A", dark: "#F0F0F0") +override.buttonFilledBg = CometChatCardColorValue(light: "#6852D6", dark: "#8B7AE8") +override.buttonFilledText = CometChatCardColorValue(light: "#FFFFFF", dark: "#FFFFFF") +override.fontFamily = "Avenir" + +cardView.themeOverride = override +``` + +### Content Size Changes + +Cards with expandable content (accordions, tabs) change height dynamically. Observe size changes to update your layout: + +```swift +NotificationCenter.default.addObserver( + forName: CometChatCardView.contentSizeDidChangeNotification, + object: cardView, + queue: .main +) { _ in + tableView.beginUpdates() + tableView.endUpdates() +} +``` + +--- + +## Key Concepts + +| Concept | Description | +| ------- | ----------- | +| NotificationFeedItem | A single notification in the feed. Contains Card Schema JSON in its `content` field, a category for filtering, timestamps, and metadata. | +| NotificationCategory | A category label used for filter chips (e.g., "Promotions", "Updates"). | +| Card Schema JSON | The fully rendered card layout (images, text, buttons) inside `NotificationFeedItem.content`. Passed directly to the CometChat Cards renderer. | +| PushNotification | Represents a campaign push notification payload received via APNs. | + +--- + +## How Cards Render in the Notification Feed + +Each `NotificationFeedItem` has a `content` field containing a `[String: Any]` dictionary — this is the Card Schema JSON. This JSON is passed directly to the CometChat Cards renderer library. + +The rendering flow: + +1. Fetch feed items via `NotificationFeedRequest` +2. For each item, extract `item.content` — this is the Card Schema JSON +3. Pass to the Cards renderer (`CometChatCardView`) +4. The renderer produces a native UIKit view from the JSON + +### Card Schema JSON Structure + +```json +{ + "version": "1.0", + "body": [ + { "type": "image", "id": "img_1", "url": "https://...", "height": 200 }, + { "type": "text", "id": "txt_1", "content": "Flash Sale!", "variant": "heading2" }, + { "type": "button", "id": "btn_1", "label": "Shop Now", "action": { "type": "openUrl", "url": "https://..." } } + ], + "style": { "background": {"light": "#FFFFFF", "dark": "#1E1E1E"}, "borderRadius": 12, "padding": 16 }, + "fallbackText": "Flash Sale! Shop Now: https://..." +} +``` + +The `body` array contains elements (text, image, button, row, column, etc.) rendered top-to-bottom. Interactive elements like buttons emit actions via a callback — the consumer handles navigation, deep links, or API calls. + +--- + +## Retrieve Notification Feed Items + +Use `NotificationFeedRequest` to fetch a paginated list of feed items. Uses cursor-based pagination internally. + +### Build the Request + +```swift +let request = NotificationFeedRequest.NotificationFeedRequestBuilder() + .set(limit: 20) + .set(readState: .unread) + .set(category: "Updates") + .build() +``` + +### Builder Parameters + +| Method | Type | Default | Description | +| ------ | ---- | ------- | ----------- | +| `set(limit:)` | `Int` | 20 | Items per page. | +| `set(readState:)` | `FeedReadState` | All | Filter by `.read` or `.unread`. Omit for all. | +| `set(category:)` | `String` | nil | Filter by category name. Sent as `templateCategory` query param. If `categoryId` is also set, `categoryId` takes priority. | +| `set(categoryId:)` | `String` | nil | Filter by category ID. Sent as `templateCategory` query param. Takes priority over `category` if both are set. | +| `set(channelId:)` | `String` | nil | Filter by channel. | +| `set(tags:)` | `[String]` | nil | Filter by tags (comma-joined). | +| `set(dateFrom:)` | `String` | nil | ISO 8601 date — items sent on or after. | +| `set(dateTo:)` | `String` | nil | ISO 8601 date — items sent on or before. | + + +`set(category:)` and `set(categoryId:)` both map to the same server-side filter (`templateCategory`). Use one or the other — not both. If both are provided, `categoryId` silently overwrites `category`. + + +### Fetch Items + +```swift +request.fetchNext(onSuccess: { items in + for item in items { + let cardJson = item.content + // Pass cardJson to CometChatCardView + } +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +Call `fetchNext()` repeatedly for pagination. When the server has no more items, subsequent calls return an empty array. + +### NotificationFeedItem Fields + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | `String` | Unique item identifier. | +| `category` | `String` | Notification category (e.g., "promotions"). | +| `categoryId` | `String` | Category ID. | +| `content` | `[String: Any]` | Card Schema JSON — pass to CometChat Cards renderer. | +| `readAt` | `Double` | Unix timestamp when read, or 0 if unread. | +| `deliveredAt` | `Double` | Unix timestamp when delivered, or 0. | +| `sentAt` | `Double` | Unix timestamp when sent. | +| `metadata` | `[String: Any]` | Custom key-value metadata. | +| `tags` | `[String]` | Tags for filtering. | +| `sender` | `String` | Sender identifier. | +| `receiver` | `String` | Receiver identifier. | +| `receiverType` | `String` | Receiver type. | +| `isRead` | `Bool` | Computed — `true` if `readAt != 0`. | + +--- + +## Retrieve Notification Categories + +Use `NotificationCategoriesRequest` to fetch available categories for filter chips. + +```swift +let categoriesRequest = NotificationCategoriesRequest.NotificationCategoriesRequestBuilder() + .set(limit: 50) + .build() + +categoriesRequest.fetchNext(onSuccess: { categories in + for category in categories { + print("Category: \(category.label)") + } +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +### NotificationCategory Fields + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | `String` | Category identifier. | +| `label` | `String` | Display label for filter UI. | + +--- + +## Real-Time Notification Feed Listener + +Listen for new feed items arriving via WebSocket. This listener is independent from `CometChatMessageDelegate`, `CometChatGroupDelegate`, and `CometChatCallDelegate`. + +```swift +CometChat.addNotificationFeedListener("feedListener", self) + +// Implement CometChatNotificationFeedDelegate +extension MyViewController: CometChatNotificationFeedDelegate { + func onFeedItemReceived(feedItem: NotificationFeedItem) { + print("New item: \(feedItem.id)") + let cardJson = feedItem.content + // Insert at top of feed and render + } +} +``` + +Remove the listener when no longer needed: + +```swift +CometChat.removeNotificationFeedListener("feedListener") +``` + +--- + +## Mark Feed Item as Read + +Mark a single item as read. Idempotent — safe to call multiple times. + +```swift +CometChat.markFeedItemAsRead(feedItem, onSuccess: { + print("Marked as read") +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +--- + +## Mark Feed Item as Delivered + +Mark a single item as delivered. Idempotent. + +```swift +CometChat.markFeedItemAsDelivered(feedItem, onSuccess: { + // Success +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +--- + +## Report Engagement + +Report that a user engaged with a feed item (e.g., viewed, clicked, interacted). Idempotent per topic. + +```swift +CometChat.reportFeedEngagement(feedItem, interactionString: "clicked", onSuccess: { + // Success +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +The `interactionString` parameter is a free-form string describing the engagement (e.g., "viewed", "clicked", "interacted"). + +--- + +## Get Unread Count + +Fetch the total number of unread notification feed items. Optionally filter by category. + +```swift +CometChat.getNotificationFeedUnreadCount(category: nil, onSuccess: { count in + print("Unread: \(count)") +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +--- + +## Fetch Single Feed Item + +Fetch a specific item by ID — useful for deep linking from push notifications. + +```swift +CometChat.getNotificationFeedItem(id: "item-id-123", onSuccess: { item in + let cardJson = item.content + // Render the card +}, onError: { error in + print("Error: \(error?.errorDescription ?? "")") +}) +``` + +--- + +## Push Notification Tracking + +When a campaign push notification arrives via APNs, use these methods to report delivery and click engagement. + +### Setting Up Notification Service Extension + +1. In Xcode: **File → New → Target** → select **Notification Service Extension**. +2. Enable **App Groups** on both your main app target and the extension target with the same group ID (e.g., `group.com.yourapp.cometchat`). +3. Add `CometChatSDK` as a dependency to the extension target. + +### Identifying Campaign Push Notifications + +Campaign pushes contain a `cometchat` dictionary with `"type": "business_messaging"`: + +```swift +func isCampaignNotification(userInfo: [AnyHashable: Any]) -> Bool { + if let cometchat = userInfo["cometchat"] as? [String: Any], + let type = cometchat["type"] as? String, + type == "business_messaging" { + return true + } + return false +} +``` + +### Push Payload Structure + +```json +{ + "aps": { "alert": { "title": "...", "body": "..." }, "badge": 1, "mutable-content": 1 }, + "cometchat": { + "type": "business_messaging", + "appId": "your-app-id", + "campaignId": "campaign-cuid", + "notificationId": "notification-cuid", + "pushNotificationId": "uuid-for-push-tracking", + "uid": "target-user-id", + "sentAt": "2026-05-21T12:43:55.206Z" + } +} +``` + +### Mark Push Notification as Delivered + +Call this in your Notification Service Extension: + +```swift +import UserNotifications +import CometChatSDK + +class NotificationService: UNNotificationServiceExtension { + override func didReceive(_ request: UNNotificationRequest, + withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { + let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)! + + // Required for extensions to share auth state via App Group container + CometChat.setExtensionGroupID(id: "group.your.app.group") + + let userInfo = bestAttemptContent.userInfo + if let cometchat = userInfo["cometchat"] as? [String: Any], + let type = cometchat["type"] as? String, + type == "business_messaging" { + let push = PushNotification.fromPayload(cometchat) + CometChat.markPushNotificationDelivered(push, onSuccess: {}, onError: { _ in }) + } + + contentHandler(bestAttemptContent) + } +} +``` + +### Mark Push Notification as Clicked + +Call this when the user taps the push notification: + +```swift +func userNotificationCenter(_ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void) { + let userInfo = response.notification.request.content.userInfo + + if let cometchat = userInfo["cometchat"] as? [String: Any], + let type = cometchat["type"] as? String, + type == "business_messaging" { + let push = PushNotification.fromPayload(cometchat) + CometChat.markPushNotificationClicked(push, onSuccess: {}, onError: { _ in }) + navigateToNotificationsTab() + completionHandler() + return + } + + completionHandler() +} +``` + +### PushNotification Fields + +| Field | Type | Description | +| ----- | ---- | ----------- | +| `id` | `String` | Push notification ID from the push payload. | +| `announcementId` | `String` | Notification/announcement ID. | +| `campaignId` | `String?` | Campaign ID if from a campaign. | +| `source` | `String` | Always "campaign" for notification feed pushes. | + +--- + +## FeedReadState Enum + +| Case | Value | Description | +| ---- | ----- | ----------- | +| `.read` | `"read"` | Only read items. | +| `.unread` | `"unread"` | Only unread items. | + +If not set, returns all items (default). + +--- + +## Supported Card Actions + +When a user taps a button or link inside a card, the action callback receives one of these action types: + +| Action Type | Parameters | Description | +| ----------- | ---------- | ----------- | +| `openUrl` | url, openIn | Open a URL in browser or webview. | +| `chatWithUser` | uid | Navigate to 1:1 chat. | +| `chatWithGroup` | guid | Navigate to group chat. | +| `sendMessage` | text, receiverUid, receiverGuid | Send a text message. | +| `copyToClipboard` | value | Copy text to clipboard. | +| `downloadFile` | url, filename | Download a file. | +| `initiateCall` | callType (audio/video), uid, guid | Start a call. | +| `apiCall` | url, method, headers, body | Make an HTTP request. | +| `customCallback` | callbackId, payload | App-specific logic. | diff --git a/sdk/ios/web-socket-connection-behaviour.mdx b/sdk/ios/web-socket-connection-behaviour.mdx index f2c96d97b..5ef7ddb55 100644 --- a/sdk/ios/web-socket-connection-behaviour.mdx +++ b/sdk/ios/web-socket-connection-behaviour.mdx @@ -36,7 +36,7 @@ CometChat SDK default connection behaviour is auto mode. The SDK automatically e 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. - + CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground | App State | Behaviour | @@ -61,7 +61,7 @@ To keep the WebSocket connection alive in the background, call the `CometChat.pi If you do not call `CometChat.ping()` within 30 seconds, the SDK will disconnect the WebSocket connection. - + CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow | App State | Behaviour | diff --git a/sdk/javascript/ai-agents.mdx b/sdk/javascript/ai-agents.mdx index cf8b4ac76..778800011 100644 --- a/sdk/javascript/ai-agents.mdx +++ b/sdk/javascript/ai-agents.mdx @@ -1,8 +1,9 @@ --- title: "AI Agents" +description: "Handle CometChat AI Agent events, tool calls, and agent messages in JavaScript apps." --- -# AI Agents Overview +## AI Agents Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). diff --git a/sdk/javascript/all-real-time-listeners.mdx b/sdk/javascript/all-real-time-listeners.mdx index 4bf96fa56..1fec5d8d7 100644 --- a/sdk/javascript/all-real-time-listeners.mdx +++ b/sdk/javascript/all-real-time-listeners.mdx @@ -1,5 +1,6 @@ --- title: "All Real Time Listeners" +description: "Use CometChat real-time listeners for user presence, groups, messages, calls, AI assistant events, and ongoing calls." --- CometChat provides 4 listeners viz. diff --git a/sdk/javascript/authentication-overview.mdx b/sdk/javascript/authentication-overview.mdx index 7b7cbf651..1b5fc8728 100644 --- a/sdk/javascript/authentication-overview.mdx +++ b/sdk/javascript/authentication-overview.mdx @@ -1,6 +1,7 @@ --- title: "Authentication" sidebarTitle: "Authentication" +description: "Create users and authenticate them securely with the CometChat JavaScript SDK." --- ## Create User diff --git a/sdk/javascript/block-users.mdx b/sdk/javascript/block-users.mdx index 43bf67b04..c6295b621 100644 --- a/sdk/javascript/block-users.mdx +++ b/sdk/javascript/block-users.mdx @@ -1,5 +1,6 @@ --- title: "Block Users" +description: "Block and unblock users in chat apps with the CometChat JavaScript SDK." --- ## Block Users diff --git a/sdk/javascript/delete-conversation.mdx b/sdk/javascript/delete-conversation.mdx index 6d3c6ac62..cad61c356 100644 --- a/sdk/javascript/delete-conversation.mdx +++ b/sdk/javascript/delete-conversation.mdx @@ -1,5 +1,6 @@ --- title: "Delete A Conversation" +description: "Delete user and group conversations with the CometChat JavaScript SDK." --- In case you want to delete a conversation, you can use the `deleteConversation()` method. diff --git a/sdk/javascript/delete-message.mdx b/sdk/javascript/delete-message.mdx index 03b800be2..9179852a6 100644 --- a/sdk/javascript/delete-message.mdx +++ b/sdk/javascript/delete-message.mdx @@ -1,5 +1,6 @@ --- title: "Delete A Message" +description: "Delete chat messages and handle delete events with the CometChat JavaScript SDK." --- While [deleting a message](/sdk/javascript/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: diff --git a/sdk/javascript/delivery-read-receipts.mdx b/sdk/javascript/delivery-read-receipts.mdx index 70a75c071..aa076ccb5 100644 --- a/sdk/javascript/delivery-read-receipts.mdx +++ b/sdk/javascript/delivery-read-receipts.mdx @@ -1,5 +1,6 @@ --- title: "Delivery & Read Receipts" +description: "Mark messages as delivered or read and handle receipts with the CometChat JavaScript SDK." --- ## Mark Messages as Delivered diff --git a/sdk/javascript/edit-message.mdx b/sdk/javascript/edit-message.mdx index e90eb1635..f4bab5085 100644 --- a/sdk/javascript/edit-message.mdx +++ b/sdk/javascript/edit-message.mdx @@ -1,5 +1,6 @@ --- title: "Edit A Message" +description: "Edit text and custom chat messages using the CometChat JavaScript SDK." --- While [editing a message](/sdk/javascript/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: diff --git a/sdk/javascript/flag-message.mdx b/sdk/javascript/flag-message.mdx index e2aea41c3..f94c01607 100644 --- a/sdk/javascript/flag-message.mdx +++ b/sdk/javascript/flag-message.mdx @@ -1,5 +1,6 @@ --- title: "Flag Message" +description: "Flag inappropriate chat messages for moderation with the CometChat JavaScript SDK." --- ## Overview diff --git a/sdk/javascript/groups-overview.mdx b/sdk/javascript/groups-overview.mdx index 8871d1575..35b673ee8 100644 --- a/sdk/javascript/groups-overview.mdx +++ b/sdk/javascript/groups-overview.mdx @@ -1,6 +1,7 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Learn how groups, group types, and group roles work in the CometChat JavaScript SDK." --- Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. diff --git a/sdk/javascript/key-concepts.mdx b/sdk/javascript/key-concepts.mdx index c1fd8c4d4..66b5c899f 100644 --- a/sdk/javascript/key-concepts.mdx +++ b/sdk/javascript/key-concepts.mdx @@ -1,5 +1,6 @@ --- title: "Key Concepts" +description: "Learn key CometChat JavaScript SDK concepts, including apps, users, auth keys, roles, and groups." --- ### CometChat Dashboard diff --git a/sdk/javascript/managing-web-sockets-connections-manually.mdx b/sdk/javascript/managing-web-sockets-connections-manually.mdx index b80404904..56ca24f0e 100644 --- a/sdk/javascript/managing-web-sockets-connections-manually.mdx +++ b/sdk/javascript/managing-web-sockets-connections-manually.mdx @@ -1,5 +1,6 @@ --- title: "Managing Web Sockets Connections Manually" +description: "Manage WebSocket connections manually with the CometChat JavaScript SDK." --- ## Default SDK behaviour on login diff --git a/sdk/javascript/mentions.mdx b/sdk/javascript/mentions.mdx index b6c176b6c..fc0accb02 100644 --- a/sdk/javascript/mentions.mdx +++ b/sdk/javascript/mentions.mdx @@ -1,5 +1,6 @@ --- title: "Mentions" +description: "Add user mentions to CometChat messages in one-on-one and group chats using UID-based mention syntax." --- 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. diff --git a/sdk/javascript/message-filtering.mdx b/sdk/javascript/message-filtering.mdx index f24d8c871..595b6964c 100644 --- a/sdk/javascript/message-filtering.mdx +++ b/sdk/javascript/message-filtering.mdx @@ -1,5 +1,6 @@ --- title: "Additional Message Filtering" +description: "Filter and paginate CometChat messages by user, group, type, category, tags, timestamps, and unread status." --- The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. diff --git a/sdk/javascript/message-structure-and-hierarchy.mdx b/sdk/javascript/message-structure-and-hierarchy.mdx index 27967c714..d3eaaa14c 100644 --- a/sdk/javascript/message-structure-and-hierarchy.mdx +++ b/sdk/javascript/message-structure-and-hierarchy.mdx @@ -1,6 +1,7 @@ --- title: "Message" sidebarTitle: "Message Structure And Hierarchy" +description: "Understand CometChat JavaScript SDK message categories, types, and object hierarchy." --- The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. diff --git a/sdk/javascript/overview.mdx b/sdk/javascript/overview.mdx index b96a01386..f6875446a 100644 --- a/sdk/javascript/overview.mdx +++ b/sdk/javascript/overview.mdx @@ -1,5 +1,6 @@ --- title: "Overview" +description: "Set up the CometChat JavaScript SDK to add real-time chat features to your web app." --- This guide demonstrates how to add chat to a JavaScript application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/javascript/key-concepts) guide. diff --git a/sdk/javascript/reactions.mdx b/sdk/javascript/reactions.mdx index 1d00573e2..0f42c7834 100644 --- a/sdk/javascript/reactions.mdx +++ b/sdk/javascript/reactions.mdx @@ -1,5 +1,6 @@ --- title: "Reactions" +description: "Add, remove, fetch, and listen for message reactions with the CometChat JavaScript SDK." --- Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. diff --git a/sdk/javascript/receive-message.mdx b/sdk/javascript/receive-message.mdx index 369d71007..3ecb4256b 100644 --- a/sdk/javascript/receive-message.mdx +++ b/sdk/javascript/receive-message.mdx @@ -1,5 +1,6 @@ --- title: "Receive A Message" +description: "Receive real-time, unread, and historical messages with the CometChat JavaScript SDK." --- Receiving messages with CometChat has two parts: diff --git a/sdk/javascript/retrieve-conversations.mdx b/sdk/javascript/retrieve-conversations.mdx index 6775a5092..b014834de 100644 --- a/sdk/javascript/retrieve-conversations.mdx +++ b/sdk/javascript/retrieve-conversations.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Conversations" +description: "Fetch recent CometChat conversations for chat lists, with support for one-on-one and group conversation filters." --- Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. diff --git a/sdk/javascript/retrieve-group-members.mdx b/sdk/javascript/retrieve-group-members.mdx index 517069056..0c1d34d5f 100644 --- a/sdk/javascript/retrieve-group-members.mdx +++ b/sdk/javascript/retrieve-group-members.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Group Members" +description: "Fetch and paginate group members using the CometChat JavaScript SDK." --- ## Retrieve the List of Group Members diff --git a/sdk/javascript/retrieve-groups.mdx b/sdk/javascript/retrieve-groups.mdx index 8a89f53f6..bc79702f6 100644 --- a/sdk/javascript/retrieve-groups.mdx +++ b/sdk/javascript/retrieve-groups.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Groups" +description: "Fetch, search, filter, and paginate groups using the CometChat JavaScript SDK." --- ## Retrieve List of Groups diff --git a/sdk/javascript/retrieve-users.mdx b/sdk/javascript/retrieve-users.mdx index bf5e28d1c..e3c05c4fc 100644 --- a/sdk/javascript/retrieve-users.mdx +++ b/sdk/javascript/retrieve-users.mdx @@ -1,5 +1,6 @@ --- title: "Retrieve Users" +description: "Retrieve users, logged-in user details, and online counts with the CometChat JavaScript SDK." --- ## Retrieve Logged In User Details diff --git a/sdk/javascript/send-message.mdx b/sdk/javascript/send-message.mdx index 9c775a5ca..38f37772e 100644 --- a/sdk/javascript/send-message.mdx +++ b/sdk/javascript/send-message.mdx @@ -1,5 +1,6 @@ --- title: "Send A Message" +description: "Send text, media, custom, and interactive chat messages with the CometChat JavaScript SDK." --- Using CometChat, you can send three types of messages: diff --git a/sdk/javascript/setup-sdk.mdx b/sdk/javascript/setup-sdk.mdx index 80c940d41..7d863932a 100644 --- a/sdk/javascript/setup-sdk.mdx +++ b/sdk/javascript/setup-sdk.mdx @@ -1,6 +1,7 @@ --- title: "Setup" sidebarTitle: "Setup" +description: "Install, import, and initialize the CometChat JavaScript SDK in your web app." --- diff --git a/sdk/javascript/threaded-messages.mdx b/sdk/javascript/threaded-messages.mdx index 6c9d279ea..1d6af168f 100644 --- a/sdk/javascript/threaded-messages.mdx +++ b/sdk/javascript/threaded-messages.mdx @@ -1,5 +1,6 @@ --- title: "Threaded Messages" +description: "Send, receive, and fetch threaded messages with the CometChat JavaScript SDK." --- Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. diff --git a/sdk/javascript/transfer-group-ownership.mdx b/sdk/javascript/transfer-group-ownership.mdx index f33195b70..802a1b368 100644 --- a/sdk/javascript/transfer-group-ownership.mdx +++ b/sdk/javascript/transfer-group-ownership.mdx @@ -1,5 +1,6 @@ --- title: "Transfer Group Ownership" +description: "Transfer group ownership to another member using the CometChat JavaScript SDK." --- _In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?_ diff --git a/sdk/javascript/transient-messages.mdx b/sdk/javascript/transient-messages.mdx index 83e0a4155..d615aff72 100644 --- a/sdk/javascript/transient-messages.mdx +++ b/sdk/javascript/transient-messages.mdx @@ -1,5 +1,6 @@ --- title: "Transient Messages" +description: "Send and receive real-time transient messages with the CometChat JavaScript SDK." --- Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. diff --git a/sdk/javascript/typing-indicators.mdx b/sdk/javascript/typing-indicators.mdx index 457832ae7..e0436b256 100644 --- a/sdk/javascript/typing-indicators.mdx +++ b/sdk/javascript/typing-indicators.mdx @@ -1,5 +1,6 @@ --- title: "Typing Indicators" +description: "Show real-time typing status in chat apps with the CometChat JavaScript SDK." --- ## Send a Typing Indicator diff --git a/sdk/javascript/upgrading-from-v3.mdx b/sdk/javascript/upgrading-from-v3.mdx index 0439d1e92..b5648ae2e 100644 --- a/sdk/javascript/upgrading-from-v3.mdx +++ b/sdk/javascript/upgrading-from-v3.mdx @@ -1,5 +1,6 @@ --- title: "Upgrading From V3" +description: "Upgrade from CometChat JavaScript SDK v3 to v4 with package and import changes." --- ## Upgrading From v3 diff --git a/sdk/javascript/user-management.mdx b/sdk/javascript/user-management.mdx index c94897805..5e4dbffb4 100644 --- a/sdk/javascript/user-management.mdx +++ b/sdk/javascript/user-management.mdx @@ -1,5 +1,6 @@ --- title: "User Management" +description: "Create and update CometChat users with the JavaScript SDK and REST API." --- When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. diff --git a/sdk/javascript/user-presence.mdx b/sdk/javascript/user-presence.mdx index 78fbef9b4..f8bbbcfb9 100644 --- a/sdk/javascript/user-presence.mdx +++ b/sdk/javascript/user-presence.mdx @@ -1,6 +1,7 @@ --- title: "User Presence" sidebarTitle: "Overview" +description: "Track online and offline user presence with the CometChat JavaScript SDK." --- {/* TL;DR for Agents and Quick Reference */} diff --git a/sdk/javascript/users-overview.mdx b/sdk/javascript/users-overview.mdx index c98e24ce4..e3c7249fc 100644 --- a/sdk/javascript/users-overview.mdx +++ b/sdk/javascript/users-overview.mdx @@ -1,6 +1,7 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Learn how users are managed and retrieved with the CometChat JavaScript SDK." --- The primary aim for our Users functionality is to allow you to quickly retrieve and add users to CometChat. diff --git a/sdk/javascript/webhooks.mdx b/sdk/javascript/webhooks.mdx new file mode 100644 index 000000000..ae3b4a614 --- /dev/null +++ b/sdk/javascript/webhooks.mdx @@ -0,0 +1,67 @@ +--- +title: "Webhooks" +description: "Webhooks — CometChat documentation." +--- + + + +CometChat can send webhook events that notify your application any time an event happens on your account. + +## Setting up webhooks + +### Create a webhook endpoint + +Webhook data is sent as JSON in the POST request body. Creating a webhook endpoint on your server is no different from creating any page on your website. With PHP, you might create a new .php file on your server; with a Ruby framework like Sinatra, you would add a new route with the desired URL. + +### Test the endpoint locally + +Once you’ve added an endpoint to your server, start an instance locally and use a tool like [ngrok](https://ngrok.com) to make your endpoint available for receiving events. + +Start ngrok in a command prompt with the same port number that you have configured for your server (e.g., ./ngrok http 8000). You should see information about your tunnel session such as status, expiration, and version. Take note of the Forwarding addresses (e.g., [https://xxxxxxxx.ngrok.io](https://xxxxxxxx.ngrok.io) -> localhost:8000) as this is required for the following step. + +### Configure webhook settings + +With your endpoint created, you need to tell CometChat about where to send events to. In the Dashboard's Webhooks section, click **Create Webhook** to reveal a form to add a new webhook for receiving events. You can enter any URL as the destination for events. However, this should be a dedicated page on your server that is set up to receive webhook events. + +Once you've created the webhook, click **View/Update** to add a trigger. We support two types of triggers- + +| Trigger | Description | +| --------------- | ----------------------------------------------------------- | +| after\_message | The endpoint will be triggered after a message is sent. | +| before\_message | The endpoint will be triggered when a message is in-flight. | + +The `after_message` trigger is fairly straightforward. CometChat will call your endpoint once a message has been sent. + +The `before_message` trigger is useful when you want to add metadata to a message before it reaches the recipient. The data you return will be automatically added to the message metadata: + + + +```json +{ +"@injected": { + "webhooks": { + "webhook-id": { + // JSON Object Response From Endpoint + } + } +} +} +``` + + + + + +You can also decide to drop a message by returning the following JSON object- + + + +```json +{ +"action": "do_not_propagate" +} +``` + + + + diff --git a/sdk/react-native/managing-web-sockets-connections-manually.mdx b/sdk/react-native/managing-web-sockets-connections-manually.mdx index ec7e84ce5..e2f642408 100644 --- a/sdk/react-native/managing-web-sockets-connections-manually.mdx +++ b/sdk/react-native/managing-web-sockets-connections-manually.mdx @@ -1,6 +1,6 @@ --- 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." +description: "Learn how to manage WebSocket connections in the CometChat React Native SDK, including connect, disconnect, and ping." --- @@ -33,7 +33,7 @@ When `autoEstablishSocketConnection` is `true` (the default): 3. The user immediately starts receiving real-time messages, presence updates, and call events - + CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground | App State | Behavior | @@ -96,6 +96,10 @@ CometChat.init(appID, appSetting).then( 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. + + CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow + + | App State | Behavior | | --- | --- | | App in foreground | Call `CometChat.connect()` to create the WebSocket connection | diff --git a/sdk/react-native/transient-messages.mdx b/sdk/react-native/transient-messages.mdx index 4340c4b95..79147999d 100644 --- a/sdk/react-native/transient-messages.mdx +++ b/sdk/react-native/transient-messages.mdx @@ -1,7 +1,7 @@ --- title: "Transient Messages" 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." +description: "Send and receive ephemeral real-time messages with the CometChat React Native SDK for live reactions and temporary indicators." --- {/* TL;DR for Agents and Quick Reference */} diff --git a/sdk/reference/auxiliary.mdx b/sdk/reference/auxiliary.mdx index 59a49e3a3..9d86add65 100644 --- a/sdk/reference/auxiliary.mdx +++ b/sdk/reference/auxiliary.mdx @@ -1,7 +1,7 @@ --- 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." +description: "Class reference for CometChat SDK auxiliary objects, including receipts, reactions, typing indicators, transient messages, attachments, and exceptions." --- This page documents the auxiliary classes used across all CometChat SDKs. These objects are returned by listener callbacks and specific SDK methods. diff --git a/sdk/reference/calls.mdx b/sdk/reference/calls.mdx index 07fbf5689..d37d5177c 100644 --- a/sdk/reference/calls.mdx +++ b/sdk/reference/calls.mdx @@ -1,7 +1,7 @@ --- 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." +description: "Class reference for CometChat Calls SDK objects, including call logs, users, groups, participants, recordings, listeners, and media devices." --- This page documents the classes used in the CometChat Calls SDK. These objects are returned by call log queries and call session methods. diff --git a/sdk/unreal/SAMPLE_APP.md b/sdk/unreal/SAMPLE_APP.md new file mode 100644 index 000000000..7a92dbe44 --- /dev/null +++ b/sdk/unreal/SAMPLE_APP.md @@ -0,0 +1,230 @@ +# CometChat Unreal Engine — Sample App (Group Chat Box) + +The CometChat plugin ships with a ready-to-use **Group Chat Box** widget (`UCometChatGroupChatBox`) that handles the entire chat flow out of the box: configure, login, join group, load history, send messages, and receive messages in real time. + +It's designed as a starting point — use it as-is for quick integration, or as a reference for building your own custom chat UI. + +## What It Does + +``` +Drop widget into viewport → Auto-configures SDK → Logs in user → Joins group → Loads message history → Ready — send & receive +``` + +--- + +## Quick Start + +### Blueprint + +1. Create a new **Widget Blueprint** (or open an existing HUD widget) +2. In the Palette, search for **CometChat Group Chat Box** +3. Drag it onto your canvas +4. In the **Details** panel, fill in the config properties: + +| Property | Value | +| -------- | ----- | +| **App Id** | Your CometChat App ID | +| **Region** | `us` or `eu` | +| **Auth Key** | Your CometChat Auth Key | +| **User Uid** | The UID of the player to log in as | +| **Group Guid** | The GUID of the group to join | + +5. Play — the widget handles everything automatically + +### C++ + +```cpp +#include "UI/CometChatGroupChatBox.h" + +void AMyHUD::BeginPlay() +{ + Super::BeginPlay(); + + UCometChatGroupChatBox* ChatBox = CreateWidget( + GetOwningPlayerController(), + UCometChatGroupChatBox::StaticClass() + ); + + ChatBox->AppId = TEXT("YOUR_APP_ID"); + ChatBox->Region = TEXT("us"); + ChatBox->AuthKey = TEXT("YOUR_AUTH_KEY"); + ChatBox->UserUid = TEXT("cometchat-uid-1"); + ChatBox->GroupGuid = TEXT("your-group-guid"); + + ChatBox->AddToViewport(10); +} +``` + +--- + +## How It Works + +When the widget is constructed, it runs an automatic flow: + +``` +NativeConstruct + → Configure SDK + → Bind OnMessageReceived + → Login with UserUid + AuthKey + → Success: Join group with GroupGuid + → Failure: Show error overlay + → Join group + → Success: Load message history + → Already a member: Load message history + → Failure: Show error overlay + → Load message history + → Success: Display messages + hide overlay + → Ready — user can type and send +``` + +The widget shows a loading overlay during each step ("Configuring...", "Logging in...", "Joining group...", "Loading messages...") and transitions to the chat view once ready. + +--- + +## Widget Structure + +The widget builds its entire UI programmatically in C++ — no Blueprint designer layout needed. + +``` +UCometChatGroupChatBox +├── SizeBox (PanelWidth x PanelHeight) +│ └── Overlay +│ ├── Border (rounded panel background) +│ │ └── VerticalBox +│ │ ├── ScrollBox (message list, fills available space) +│ │ │ └── Message rows (added dynamically) +│ │ └── HorizontalBox (composer row) +│ │ ├── Border (rounded input background) +│ │ │ └── EditableTextBox (message input) +│ │ ├── Button (send button, circular) +│ │ └── Button (options button, optional) +│ └── Border (loading overlay, hidden when ready) +│ └── TextBlock (status text) +``` + +Each message row contains: +- **Avatar** — circular with initial letter, loads actual image from URL asynchronously +- **Online indicator** — green dot on the avatar +- **Username** — colored differently for self vs others +- **Message text** — white, auto-wrapping +- **Timestamp** — gray, right-aligned (HH:MM format) + +--- + +## Customization + +Every visual aspect is exposed as a `UPROPERTY` — editable in the Blueprint Details panel or settable in C++. + +### Panel + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `PanelWidth` | `float` | `520` | Widget width in pixels | +| `PanelHeight` | `float` | `300` | Widget height in pixels | +| `PanelBackgroundColor` | `FLinearColor` | `(0, 0, 0, 0.35)` | Panel background with alpha | +| `PanelCornerRadius` | `float` | `12` | Rounded corner radius | +| `PanelPadding` | `float` | `12` | Inner padding | +| `MessageLimit` | `int32` | `30` | Messages to load from history | + +### Messages + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `SenderNameColor` | `FLinearColor` | Yellow | Your username color | +| `ReceiverNameColor` | `FLinearColor` | Blue | Other users' name color | +| `MessageTextColor` | `FLinearColor` | White (0.9 alpha) | Message body color | +| `UsernameFontSize` | `float` | `15` | Username text size | +| `MessageFontSize` | `float` | `15` | Message body text size | +| `MessageSpacing` | `float` | `6` | Vertical gap between messages | +| `bEnableTextShadow` | `bool` | `true` | Drop shadow on text | + +### Avatars + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `bShowAvatars` | `bool` | `true` | Show circular avatars | +| `AvatarSize` | `float` | `36` | Avatar diameter in pixels | +| `AvatarPlaceholderColor` | `FLinearColor` | Gray | Background when no image | +| `bShowOnlineIndicator` | `bool` | `true` | Green dot on avatar | +| `OnlineIndicatorColor` | `FLinearColor` | Green | Indicator dot color | + +### Composer + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `ComposerBackgroundColor` | `FLinearColor` | Dark gray | Input field background | +| `ComposerCornerRadius` | `float` | `20` | Input field corner radius | +| `ComposerPlaceholderText` | `FString` | `"Type a message..."` | Placeholder text | + +### Send Button + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `SendButtonLabel` | `FString` | `">"` | Button text | +| `SendButtonColor` | `FLinearColor` | Blue | Button background | +| `SendButtonWidth` | `float` | `42` | Button size (square) | +| `SendButtonCornerRadius` | `float` | `20` | Makes it circular | + +### Options Button + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `bShowOptionsButton` | `bool` | `true` | Show the "..." button | +| `OptionsButtonLabel` | `FString` | `"..."` | Button text | + +### Timestamps + +| Property | Type | Default | Description | +| -------- | ---- | ------- | ----------- | +| `bShowTimestamp` | `bool` | `true` | Show HH:MM timestamps | +| `TimestampColor` | `FLinearColor` | Gray | Timestamp text color | +| `TimestampFontSize` | `float` | `11` | Timestamp text size | + +--- + +## Events + +The widget exposes one event dispatcher: + +| Event | Description | +| ----- | ----------- | +| `OnOptionsClicked` | Fires when the user clicks the options ("...") button. Bind this to show a custom menu (e.g., leave group, mute, settings). | + +### Blueprint + +In the Details panel, find **On Options Clicked** under Events and click the **+** to bind it. + +### C++ + +```cpp +ChatBox->OnOptionsClicked.AddDynamic(this, &AMyHUD::HandleChatOptions); +``` + +--- + +## Real-Time Messages + +The widget automatically binds to `OnMessageReceived` on the `UCometChatSubsystem`. When a new group message arrives: + +1. It checks if the message belongs to the configured `GroupGuid` +2. It filters out messages sent by the current user (to avoid duplicates — sent messages are already added on send) +3. It creates a new message row and scrolls to the bottom + +No additional wiring needed. + +--- + +## Loading States + +The widget shows an overlay with status text during each phase: + +| State | Overlay Text | +| ----- | ------------ | +| Configuring | "Configuring..." | +| Logging In | "Logging in..." | +| Joining Group | "Joining group..." | +| Loading History | "Loading messages..." | +| Ready | Overlay hidden | +| Error | Error message displayed | + +The overlay background color and text style are customizable via the `Overlay` properties. diff --git a/ui-kit/android/core-features.mdx b/ui-kit/android/core-features.mdx index 4a40699c8..c1fb59c41 100644 --- a/ui-kit/android/core-features.mdx +++ b/ui-kit/android/core-features.mdx @@ -1,6 +1,6 @@ --- title: "Core" -description: "Overview of CometChat's core chat features including instant messaging, media sharing, read receipts, typing indicators, user presence, reactions, mentions, threaded conversations, search, and moderation." +description: "Overview of CometChat Android UI Kit core features, including messaging, media sharing, receipts, presence, reactions, search, and moderation." --- diff --git a/ui-kit/android/guide-ai-agent.mdx b/ui-kit/android/guide-ai-agent.mdx index 10dc1220b..357d9dc96 100644 --- a/ui-kit/android/guide-ai-agent.mdx +++ b/ui-kit/android/guide-ai-agent.mdx @@ -25,6 +25,10 @@ Enable intelligent conversational AI capabilities in your Android app using Come Transform your chat experience with AI-powered assistance that provides intelligent responses and offers seamless integration with your existing chat infrastructure. + +**1:1 conversations only.** AI Agents currently respond only in one-on-one conversations between an end user and the agent user. They do not respond to messages sent in groups, even if the agent user is added as a member or owner. Group support is on the roadmap — share your use case on [feedback.cometchat.com](https://feedback.cometchat.com). + + ## Overview Users can interact with AI agents through a dedicated chat interface that: diff --git a/ui-kit/android/v6/ai-assistant-chat-history.mdx b/ui-kit/android/v6/ai-assistant-chat-history.mdx new file mode 100644 index 000000000..00d8de003 --- /dev/null +++ b/ui-kit/android/v6/ai-assistant-chat-history.mdx @@ -0,0 +1,357 @@ +--- +title: "AI Assistant Chat History" +description: "Displays the conversation history between users and an AI assistant for easy review of past interactions." +--- + + +```json +{ + "component": "CometChatAIAssistantChatHistory", + "package": "com.cometchat.uikit.kotlin.presentation.aiassistantchathistory", + "xmlElement": "", + "description": "Displays the conversation history between users and an AI assistant for easy review of past interactions.", + "primaryOutput": { + "method": "setOnItemClickListener", + "type": "OnItemClickListener" + }, + "methods": { + "data": { + "setUser": { + "type": "User", + "required": true, + "note": "User must have role set to @agentic" + } + }, + "callbacks": { + "setOnItemClickListener": "OnItemClickListener", + "setOnItemLongClickListener": "OnItemLongClickListener", + "setOnNewChatClickListener": "OnClick", + "setOnCloseClickListener": "OnClick" + }, + "visibility": { + "setErrorStateVisibility": { "type": "int (View.VISIBLE | View.GONE)", "default": "View.VISIBLE" }, + "setEmptyStateVisibility": { "type": "int (View.VISIBLE | View.GONE)", "default": "View.VISIBLE" } + }, + "style": { + "setStyle": { + "type": "@StyleRes int", + "parent": "CometChatAIAssistantChatHistoryStyle" + } + } + }, + "events": [], + "sdkListeners": [] +} +``` + + + +## Quick Start + +1. Open your layout XML file. +2. Add the `CometChatAIAssistantChatHistory` XML element: + +```xml lines + +``` + +> **What this does:** Adds the `CometChatAIAssistantChatHistory` component to your layout. It fills the available width and height and renders the AI assistant chat history list. + +3. In your Activity or Fragment, create a `User` object with the role set to `@agentic` and pass it to the component: + + + + +```kotlin lines +val user = User() +user.uid = "userId" +user.name = "User Name" +user.role = "@agentic" // User role must be @agentic to use AI Assistant features + +binding.cometChatAiAssistantChatHistory.setUser(user) +``` + + + + +```kotlin lines +import com.cometchat.uikit.compose.presentation.aiassistantchathistory.ui.CometChatAIAssistantChatHistory + +@Composable +fun AIAssistantChatHistoryScreen() { + CometChatAIAssistantChatHistory( + modifier = Modifier.fillMaxSize(), + onCloseClick = { /* handle close */ }, + onNewChatClick = { /* handle new chat */ }, + onItemClick = { message -> /* handle item click */ } + ) +} +``` + + + + + +> **What this does:** Creates a `User` object with the `@agentic` role and sets it on the `CometChatAIAssistantChatHistory` component. This is required for the component to fetch and display the AI assistant chat histories for that user. + +4. Build and run your app. +5. Verify that the AI assistant chat history list appears with past conversation items. + + + + + +## Core Concepts + +- **`CometChatAIAssistantChatHistory`**: The main component class that renders the AI assistant chat history list. It is a Composite Component that can be launched via button clicks or any user-triggered action. +- **Actions**: Callbacks such as `setOnItemClickListener`, `setOnItemLongClickListener`, `setOnNewChatClickListener`, and `setOnCloseClickListener` that let you respond to user interactions. +- **Style**: XML theme styles applied via `setStyle()` to customize colors, fonts, and visual appearance of the chat history. +- **Functionality**: Methods like `setUser`, `setErrorStateVisibility`, and `setEmptyStateVisibility` that configure the component's behavior and state visibility. + +## Actions and Events + +### Callback Methods + +What you're changing: How the component responds to user interactions such as taps, long-presses, new chat clicks, and close clicks. + +- **Where**: Activity or Fragment where you hold a reference to `CometChatAIAssistantChatHistory`. +- **Applies to**: `CometChatAIAssistantChatHistory`. +- **Default behavior**: Predefined actions execute automatically when the user interacts with the component. +- **Override**: Call the corresponding setter method to replace the default behavior with your own logic. + +#### `setOnItemClickListener` + +Function invoked when a chat history item is clicked, used to open an AI assistant chat screen. + + + + +```kotlin YourActivity.kt lines +binding.cometchatAiAssistantChatHistory.setOnItemClickListener { view, position, message -> + + } +``` + + + +```kotlin lines +import com.cometchat.uikit.compose.presentation.aiassistantchathistory.ui.CometChatAIAssistantChatHistory + +CometChatAIAssistantChatHistory( + onItemClick = { message -> + Log.i(TAG, "Item clicked: ${message.id}") + } +) +``` + + + +> **What this does:** Replaces the default item-click behavior. When a user taps a chat history item, your custom lambda executes instead of the built-in navigation. + +#### `setOnItemLongClickListener` + +Function executed when a chat history item is long-pressed, allowing additional actions like delete or block. + + + + +```kotlin YourActivity.kt lines +binding.cometchatAiAssistantChatHistory.setOnItemLongClickListener { view, position, message -> + + } +``` + + + +```kotlin lines +CometChatAIAssistantChatHistory( + onItemLongClick = { message -> + Log.i(TAG, "Item long clicked: ${message.id}") + } +) +``` + + + +> **What this does:** Replaces the default long-press behavior. When a user long-presses a chat history item, your custom lambda executes. + +#### `setOnNewChatClickListener` + +Function triggered when the new chat button is clicked, used to start a new conversation with the AI assistant. + + + + +```kotlin YourActivity.kt lines +binding.cometchatAiAssistantChatHistory.setOnNewChatClickListener { + + } +``` + + + +```kotlin lines +CometChatAIAssistantChatHistory( + onNewChatClick = { + Log.i(TAG, "New chat clicked") + } +) +``` + + + +> **What this does:** Replaces the default new-chat-click behavior. When the user taps the new chat button, your custom logic runs instead of the built-in action. + +#### `setOnCloseClickListener` + +Function activated when the close button is clicked, used to exit the chat history view. + + + + +```kotlin YourActivity.kt lines +binding.cometchatAiAssistantChatHistory.setOnCloseClickListener { + + } +``` + + + +```kotlin lines +CometChatAIAssistantChatHistory( + onCloseClick = { + Log.i(TAG, "Close clicked") + } +) +``` + + + +> **What this does:** Replaces the default close-click behavior. When the user taps the close button, your custom logic runs instead of the built-in exit action. + +- **Verify**: After setting an action callback, trigger the corresponding user interaction (tap, long-press, new chat, close) and confirm your custom logic executes instead of the default behavior. + +## Styling + +What you're changing: The visual appearance of the AI Assistant Chat History component using XML theme styles. + +- **Where**: `themes.xml` for style definitions, and your Activity/Fragment for applying the style. +- **Applies to**: `CometChatAIAssistantChatHistory`. +- **Default behavior**: The component uses its default style. +- **Override**: Define a custom style in `themes.xml`, then call `setStyle()` on the component. + + + + + +- **Code**: + +```xml themes.xml lines + + + +``` + +> **What this does:** Defines a custom style `CustomAIAssistantChatHistoryStyle` that sets the background color to `#FFFAF6` for the component, header, new chat area, date separator, and items. It applies a Times New Roman font to the header, new chat text, date separator, and item text. A helper style `textStyleTimesNewRoman` defines the font family. + + + + +```kotlin lines +binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomAIAssistantChatHistoryStyle); +``` + + + +```kotlin lines +import com.cometchat.uikit.compose.presentation.aiassistantchathistory.style.CometChatAIAssistantChatHistoryStyle + +CometChatAIAssistantChatHistory( + style = CometChatAIAssistantChatHistoryStyle.default().copy( + chatHistoryBackgroundColor = Color(0xFFEDEAFA) + ) +) +``` + + + +> **What this does:** Applies the `CustomAIAssistantChatHistoryStyle` theme to the `CometChatAIAssistantChatHistory` component, changing the background colors and fonts. + +To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_assistant_chat_history.xml). + +- **Verify**: The chat history component displays with the `#FFFAF6` background color and Times New Roman font for header text, new chat text, date separator text, and item text. + +## Functionality + +What you're changing: Small functional customizations such as setting the user and toggling visibility of UI states. + +- **Where**: Activity or Fragment where you hold a reference to `CometChatAIAssistantChatHistory`. +- **Applies to**: `CometChatAIAssistantChatHistory`. +- **Default behavior**: All UI states are visible with default settings. +- **Override**: Call the corresponding method on the component instance. + +| Methods | Description | Code | +| --- | --- | --- | +| `setUser` | Sets the user whose chat histories with the AI assistant need to be fetched. This is a required property for the component to function. The user's role must be `@agentic`. | `.setUser(user);` | +| `setErrorStateVisibility` | Toggles the visibility of the error state of the component | `.setErrorStateVisibility(View.GONE);` | +| `setEmptyStateVisibility` | Toggles the visibility of the empty state of the component | `.setEmptyStateVisibility(View.GONE);` | + +- **Verify**: After calling `setUser(user)`, confirm the component fetches and displays the AI assistant chat histories for that user. After calling a visibility method, confirm the corresponding UI state is shown or hidden. + +## Customization Matrix + +| What you want to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Component background color | `themes.xml` | `cometChatAIAssistantChatHistoryBackgroundColor` | `#FFFAF6` | +| Header background color | `themes.xml` | `cometChatAIAssistantChatHistoryHeaderBackgroundColor` | `#FFFAF6` | +| Header text color | `themes.xml` | `cometChatAIAssistantChatHistoryHeaderTextColor` | `?attr/cometchatTextColorPrimary` | +| Header text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryHeaderTextAppearance` | `@style/textStyleTimesNewRoman` | +| New chat background color | `themes.xml` | `cometChatAIAssistantChatHistoryNewChatBackgroundColor` | `#FFFAF6` | +| New chat text color | `themes.xml` | `cometChatAIAssistantChatHistoryNewChatTextColor` | `?attr/cometchatTextColorPrimary` | +| New chat text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryNewChatTextAppearance` | `@style/textStyleTimesNewRoman` | +| Date separator text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryDateSeparatorTextAppearance` | `@style/textStyleTimesNewRoman` | +| Date separator text color | `themes.xml` | `cometChatAIAssistantChatHistoryDateSeparatorTextColor` | `?attr/cometchatTextColorTertiary` | +| Date separator background color | `themes.xml` | `cometChatAIAssistantChatHistoryDateSeparatorBackgroundColor` | `#FFFAF6` | +| Item background color | `themes.xml` | `cometChatAIAssistantChatHistoryItemBackgroundColor` | `#FFFAF6` | +| Item text appearance | `themes.xml` | `cometChatAIAssistantChatHistoryItemTextAppearance` | `@style/textStyleTimesNewRoman` | +| Item text color | `themes.xml` | `cometChatAIAssistantChatHistoryItemTextColor` | `?attr/cometchatTextColorPrimary` | +| Apply a custom style | Activity/Fragment | `setStyle(int styleRes)` | `binding.cometchatAiAssistantChatHistory.setStyle(R.style.CustomAIAssistantChatHistoryStyle);` | +| Set the user for fetching history | Activity/Fragment | `setUser(User)` | `.setUser(user);` | +| Error state visibility | Activity/Fragment | `setErrorStateVisibility(int)` | `.setErrorStateVisibility(View.GONE);` | +| Empty state visibility | Activity/Fragment | `setEmptyStateVisibility(int)` | `.setEmptyStateVisibility(View.GONE);` | + +## Next Steps + + + + Display messages in a conversation + + + Browse recent conversations + + + Browse and search available users + + + Search across conversations and messages + + \ No newline at end of file diff --git a/ui-kit/android/v6/ai-features.mdx b/ui-kit/android/v6/ai-features.mdx index 3a9ffa427..d9e7c149a 100644 --- a/ui-kit/android/v6/ai-features.mdx +++ b/ui-kit/android/v6/ai-features.mdx @@ -12,7 +12,7 @@ description: "Integrate AI-powered conversation starters, smart replies, and con | AI features | Conversation Starter, Smart Replies, Conversation Summary | | Key components | [Message List](/ui-kit/android/v6/message-list) (Conversation Starter), [Message Composer](/ui-kit/android/v6/message-composer) (Smart Replies, Summary) | | Activation | Enable each AI feature from the CometChat Dashboard — UI Kit auto-integrates them, no additional code required | -| Related | [Core Features](/ui-kit/android/v6/core-features), [Extensions](/ui-kit/android/v6/extensions), [AI Agent Guide](/ui-kit/android/guide-ai-agent) | +| Related | [Core Features](/ui-kit/android/v6/core-features), [Extensions](/ui-kit/android/v6/extensions), [AI Agent Guide](/ui-kit/android/v6/guide-ai-agent) | diff --git a/ui-kit/android/v6/call-features.mdx b/ui-kit/android/v6/call-features.mdx index 62041896a..ad738b447 100644 --- a/ui-kit/android/v6/call-features.mdx +++ b/ui-kit/android/v6/call-features.mdx @@ -33,8 +33,8 @@ Add the following dependency to your `build.gradle.kts` file: ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-kotlin-android:6.0.0-beta.1") - implementation("com.cometchat:calls-sdk-android:4.3.3") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` @@ -42,8 +42,8 @@ dependencies { ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-compose-android:6.0.0-beta.1") - implementation("com.cometchat:calls-sdk-android:4.3.3") + implementation("com.cometchat:chatuikit-compose-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` diff --git a/ui-kit/android/v6/calling-integration.mdx b/ui-kit/android/v6/calling-integration.mdx index d3c4902eb..825f1692a 100644 --- a/ui-kit/android/v6/calling-integration.mdx +++ b/ui-kit/android/v6/calling-integration.mdx @@ -19,8 +19,8 @@ Add the CometChat Calls SDK dependency alongside your chosen UI Kit module: ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-kotlin-android:6.0.0-beta.1") - implementation("com.cometchat:calls-sdk-android:4.3.3") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` @@ -28,8 +28,8 @@ dependencies { ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-compose-android:6.0.0-beta.1") - implementation("com.cometchat:calls-sdk-android:4.3.3") + implementation("com.cometchat:chatuikit-compose-android:6.0.0") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` diff --git a/ui-kit/android/v6/component-styling.mdx b/ui-kit/android/v6/component-styling.mdx index c04771737..d1313cc3b 100644 --- a/ui-kit/android/v6/component-styling.mdx +++ b/ui-kit/android/v6/component-styling.mdx @@ -704,6 +704,181 @@ Attribute references: - [Mentions attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_mentions.xml) - [Message Bubble attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_message_bubble.xml) +#### Search + +The `CometChatSearch` component provides cross-conversation and message search UI. + + + + + +What you're changing: search background and typography styles. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatSearch` + +- **Default behavior**: UI Kit default search colors and text appearance. + +- **Override**: set `cometchatSearchStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + + + +``` + +- **What this does**: applies custom search colors and text styles across search UI sections. + +- **Verify**: open Search and check section headers, chips, and list items. + +Attribute references: +- [Search attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_search.xml) + + +#### Message Information + +The `CometChatMessageInformation` component displays message metadata such as delivery and read status. + + + + + +What you're changing: message information styling for metadata views. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatMessageInformation` + +- **Default behavior**: UI Kit default metadata styling. + +- **Override**: set `cometchatMessageInformationStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: wires a custom Message Information style so you can override specific metadata attributes. + +- **Verify**: open Message Information and confirm your overrides apply. + +Attribute references: +- [Message Information attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_message_information.xml) + + +#### Message Option Sheet + +The `CometChatMessageOptionSheet` component is the action menu for message-level actions. + + + + + +What you're changing: option sheet background and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatMessageOptionSheet` + +- **Default behavior**: UI Kit default option sheet styling. + +- **Override**: set `cometchatPopupMenuStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: updates message option sheet icon tint and background color. + +- **Verify**: long-press a message and confirm the option sheet styling. + +Attribute references: +- [Message Option Sheet attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_message_option_sheet.xml) + + +#### Attachment Option Sheet + +The `CometChatAttachmentOptionSheet` component renders the attachment picker. + + + + + +What you're changing: attachment option sheet background and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatAttachmentOptionSheet` + +- **Default behavior**: UI Kit default attachment sheet styling. + +- **Override**: set `cometchatAttachmentOptionSheetStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies custom colors to the attachment picker sheet. + +- **Verify**: open the attachment menu and confirm background and icons. + +Attribute references: +- [Attachment Option Sheet attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_attachment_option_sheet.xml) + + --- ### Calling UI @@ -879,6 +1054,272 @@ Attribute references: - [Outgoing Call attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_outgoing_call.xml) - [Avatar attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_avatar.xml) +#### Call Buttons + +The `CometChatCallButton` component renders voice and video call buttons. + + + + + +What you're changing: button background, stroke, and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatCallButtons` + +- **Default behavior**: UI Kit default call button styling. + +- **Override**: set `cometchatCallButtonsStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes call button padding, background, and icon colors. + +- **Verify**: open a chat header and confirm button styling. + +Attribute references: +- [Call Buttons attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_call_buttons.xml) + + +--- + +### AI UI +#### AI Assistant Chat History + +The `CometChatAIAssistantChatHistory` component renders the AI conversation history view. + + + + + +What you're changing: background, header, and list typography. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatAIAssistantChatHistory` + +- **Default behavior**: UI Kit default AI history styling. + +- **Override**: set `cometChatAIAssistantChatHistoryStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + + + +``` + +- **What this does**: applies custom colors and font styling to the AI Assistant history screen. + +- **Verify**: open AI Assistant history and confirm background and header styling. + +Attribute references: +- [AI Assistant Chat History attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_assistant_chat_history.xml) + +#### AI Option Sheet + +The `CometChatAIOptionSheet` component renders AI action options. + + + + + +What you're changing: AI option sheet background and icon tint. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatAIOptionSheet` + +- **Default behavior**: UI Kit default AI option sheet styling. + +- **Override**: set `cometchatAIOptionSheetStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes AI option sheet colors. + +- **Verify**: open AI actions and confirm the option sheet styling. + +Attribute references: +- [AI Option Sheet attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_option_sheet.xml) + +#### Conversation Starter + +The `CometChatConversationStarter` component renders AI-powered conversation starters. + + + + + +What you're changing: conversation starter item backgrounds. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatConversationStarter` + +- **Default behavior**: UI Kit default conversation starter styling. + +- **Override**: set `cometchatAIConversationStarterStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies a custom background color to AI conversation starter items. + +- **Verify**: open a new chat and confirm the conversation starter chip color. + +Attribute references: +- [AI Conversation Starter attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_conversation_starter.xml) + +#### Conversation Summary + +The `CometChatConversationSummary` component renders AI-generated summaries of chats. + + + + + +What you're changing: conversation summary background color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatConversationSummary` + +- **Default behavior**: UI Kit default conversation summary styling. + +- **Override**: set `cometchatAIConversationSummaryStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies a custom background color to conversation summary cards. + +- **Verify**: open a chat summary and confirm the background color. + +Attribute references: +- [AI Conversation Summary attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_conversation_summary.xml) + +#### Smart Replies + +The `CometChatSmartReplies` component renders AI-generated reply suggestions. + + + + + +What you're changing: smart reply background, item color, and stroke. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatSmartReplies` + +- **Default behavior**: UI Kit default smart replies styling. + +- **Override**: set `cometchatAISmartRepliesStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes smart reply container and chip styling. + +- **Verify**: open a conversation with smart replies enabled and confirm chip styling. + +Attribute references: +- [AI Smart Replies attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_ai_smart_replies.xml) + + --- ### Base Components @@ -1092,6 +1533,184 @@ CometChatReactionList( Attribute references: - [Reaction List attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit-kotlin/src/main/res/values/attr_cometchat_reaction_list.xml) +#### Date + +The `CometChatDate` component formats timestamps in lists and message threads. + + + + + +What you're changing: date text color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatDate` + +- **Default behavior**: UI Kit default date styling. + +- **Override**: set `cometchatDateStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: customizes date text color in UI Kit lists and headers. + +- **Verify**: check any timestamp and confirm the color. + +Attribute references: +- [Date attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_date.xml) + + +#### Receipts + +The `CometChatReceipts` component renders read and delivered status icons. + + + + + +What you're changing: read receipt icon drawable. + +- **Where to change it**: `res/drawable/read_receipts.xml` and `res/values/themes.xml` + +- **Applies to**: `CometChatReceipts` + +- **Default behavior**: UI Kit default receipt icons. + +- **Override**: set `cometchatMessageReceiptStyle` in `AppTheme` and reference a custom drawable. + +- **Code**: +```xml res/drawable/read_receipts.xml lines + + + + +``` + +- **What this does**: defines a custom read receipt icon. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies the custom receipt icon to message status indicators. + +- **Verify**: send a message and check the receipt icon for read status. + +Attribute references: +- [Message Receipt attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_message_receipt.xml) + + +#### Media Recorder + +The `CometChatMediaRecorder` component controls audio and video message recording. + + + + + +What you're changing: recorder icon sizes and recording button background color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatMediaRecorder` + +- **Default behavior**: UI Kit default media recorder styling. + +- **Override**: set `cometchatMediaRecorderStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies custom sizing and color to the media recorder UI. + +- **Verify**: open the recorder and check icon sizes and record button color. + +Attribute references: +- [Media Recorder attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_media_recorder.xml) + + +#### Sticker Keyboard + +The `CometChatStickerKeyboard` component renders the sticker picker UI. + + + + + +What you're changing: sticker keyboard background color. + +- **Where to change it**: `res/values/themes.xml` + +- **Applies to**: `CometChatStickerKeyboard` + +- **Default behavior**: UI Kit default sticker keyboard styling. + +- **Override**: set `cometchatStickerKeyboardStyle` in `AppTheme`. + +- **Code**: +```xml res/values/themes.xml lines + + + + + +``` + +- **What this does**: applies a custom background color to the sticker keyboard. + +- **Verify**: open the sticker keyboard and confirm the background color. + +Attribute references: +- [Sticker Keyboard attributes](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_sticker_keyboard.xml) + + --- ## Customization matrix @@ -1103,5 +1722,10 @@ Attribute references: | Group list titles | `themes.xml` / style param | `cometchatGroupsStyle` | `cometchatGroupsTitleTextColor` | | Header call icons | `themes.xml` / style param | `cometchatMessageHeaderStyle` | `cometchatMessageHeaderCallButtonsStyle` | | Message list background | `themes.xml` / style param | `cometchatMessageListStyle` | `cometchatMessageListBackgroundColor` | +| Search styling | `themes.xml` / style param | `cometchatSearchStyle` | `cometchatSearchBackgroundColor` | +| Message Information | `themes.xml` / style param | `cometchatMessageInformationStyle` | `cometchatMessageInformationBackgroundColor` | +| AI Chat History | `themes.xml` / style param | `cometchatAIAssistantChatHistoryStyle` | `cometchatAIAssistantChatHistoryBackgroundColor` | +| Date formatting | `themes.xml` / style param | `cometchatDateStyle` | `cometchatDateTextColor` | +| Receipts icons | `themes.xml` / style param | `cometchatReceiptsStyle` | `cometchatReceiptsReadColor` | | Composer send button | `res/drawable/` + `themes.xml` | `cometchatMessageComposerActiveSendButtonDrawable` | `@drawable/active_send_button` | | Call buttons styling | `themes.xml` / style param | `cometchatCallButtonsStyle` | `cometchatCallButtonsVideoCallBackgroundColor` | diff --git a/ui-kit/android/v6/core-features.mdx b/ui-kit/android/v6/core-features.mdx index fcc6bef02..ad33a43b5 100644 --- a/ui-kit/android/v6/core-features.mdx +++ b/ui-kit/android/v6/core-features.mdx @@ -9,7 +9,7 @@ description: "Overview of CometChat's core chat features including instant messa | --- | --- | | Packages | `com.cometchat:chatuikit-kotlin-android` (Kotlin XML Views), `com.cometchat:chatuikit-compose-android` (Jetpack Compose) | | Required setup | `CometChatUIKit.init()` then `CometChatUIKit.login()` — must complete before rendering any component | -| Core features | Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Quoted Reply, Threaded Conversations, Moderation, Report Message, Group Chat | +| Core features | Instant Messaging, Media Sharing, Read Receipts, Mark as Unread, Typing Indicator, User Presence, Reactions, Mentions, Rich Text Formatting, Quoted Reply, Search, Threaded Conversations, Moderation, Report Message, Group Chat | | Key components | `CometChatConversations`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader`, `CometChatUsers`, `CometChatGroups`, `CometChatGroupMembers`, `CometChatMessageInformation`, `CometChatThreadHeader` | | Theming | See [Theming](/ui-kit/android/v6/theme-introduction) | @@ -124,6 +124,19 @@ Address specific users in a conversation by typing `@` to trigger mention sugges | [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Triggers mention suggestions on `@` and inserts formatted mentions. | | [CometChatMessageList](/ui-kit/android/v6/message-list) | Renders mentions with distinct styling in the message flow. | + +## Rich Text Formatting + +Rich Text Formatting allows users to style their messages with bold, italic, strikethrough, code, code blocks, blockquotes, ordered/unordered lists, and links. This brings richer expression to conversations and helps users emphasize key points. + + + + + +| Component | Role | +| --- | --- | +| [CometChatMessageComposer](/ui-kit/android/v6/message-composer) | Provides a built-in rich text editor with formatting toolbar and text selection menu items for bold, italic, strikethrough, code, links, lists, blockquotes, and code blocks. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Renders formatted messages with the appropriate styling automatically applied, ensuring that rich text formatting is displayed exactly as intended by the sender. | ## Threaded Conversations Respond directly to a specific message, keeping conversations organized. @@ -196,6 +209,21 @@ Learn more about flagged messages in the [Flagged Messages](/moderation/flagged- | --- | --- | | [CometChatMessageList](/ui-kit/android/v6/message-list) | Provides the "Report Message" option in message actions. | +## Conversation and Advanced Search + +Conversation and Advanced Search enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. + + + + + +| Component | Role | +| --- | --- | +| [CometChatSearch](/ui-kit/android/v6/search) | Allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | +| [CometChatMessageHeader](/ui-kit/android/v6/message-header) | Shows the search button in the chat header, allowing users to search within a conversation. | +| [CometChatMessageList](/ui-kit/android/v6/message-list) | Shows the selected message when clicked from search results and highlights it in the message list. | +| [CometChatConversations](/ui-kit/android/v6/conversations) | Displays the search input. | + --- ## Next Steps diff --git a/ui-kit/android/v6/getting-started-jetpack.mdx b/ui-kit/android/v6/getting-started-jetpack.mdx index 0c28eb164..d43964e57 100644 --- a/ui-kit/android/v6/getting-started-jetpack.mdx +++ b/ui-kit/android/v6/getting-started-jetpack.mdx @@ -98,10 +98,10 @@ android { dependencies { // CometChat Jetpack Compose UI Kit - implementation("com.cometchat:chatuikit-compose-android:6.0.0-beta.1") + implementation("com.cometchat:chatuikit-compose-android:6.0.0") // (Optional) Voice/video calling - implementation("com.cometchat:calls-sdk-android:latest") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` diff --git a/ui-kit/android/v6/getting-started-kotlin.mdx b/ui-kit/android/v6/getting-started-kotlin.mdx index 2170d4953..7a4988449 100644 --- a/ui-kit/android/v6/getting-started-kotlin.mdx +++ b/ui-kit/android/v6/getting-started-kotlin.mdx @@ -93,10 +93,10 @@ android { dependencies { // CometChat Kotlin UI Kit - implementation("com.cometchat:chatuikit-kotlin-android:6.0.0-beta.1") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") // (Optional) Voice/video calling - implementation("com.cometchat:calls-sdk-android:latest") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` diff --git a/ui-kit/android/v6/getting-started.mdx b/ui-kit/android/v6/getting-started.mdx index e44f68347..3ee397a3f 100644 --- a/ui-kit/android/v6/getting-started.mdx +++ b/ui-kit/android/v6/getting-started.mdx @@ -88,8 +88,8 @@ Inside `libs.versions.toml`, add the versions: ```toml libs.versions.toml [versions] -cometchat-ui-kit = "6.0.0-beta.1" -cometchat-calls-sdk = "4.3.3" +cometchat-ui-kit = "6.0.0" +cometchat-calls-sdk = "5.0.0-beta.2" ``` Define the libraries — pick the module for your UI toolkit: @@ -132,10 +132,10 @@ Open the app-level `build.gradle.kts` file and add the dependency for your chose ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-kotlin-android:6.0.0-beta.1") + implementation("com.cometchat:chatuikit-kotlin-android:6.0.0") // (Optional) Include if using voice/video calling features - implementation("com.cometchat:calls-sdk-android:4.3.3") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` @@ -143,10 +143,10 @@ dependencies { ```kotlin build.gradle.kts dependencies { - implementation("com.cometchat:chatuikit-compose-android:6.0.0-beta.1") + implementation("com.cometchat:chatuikit-compose-android:6.0.0") // (Optional) Include if using voice/video calling features - implementation("com.cometchat:calls-sdk-android:4.3.3") + implementation("com.cometchat:calls-sdk-android:5.0.0-beta.2") } ``` diff --git a/ui-kit/android/v6/guide-ai-agent.mdx b/ui-kit/android/v6/guide-ai-agent.mdx new file mode 100644 index 000000000..856abac5c --- /dev/null +++ b/ui-kit/android/v6/guide-ai-agent.mdx @@ -0,0 +1,423 @@ +--- +title: "AI Agent Integration" +sidebarTitle: "AI Agent Integration" +description: "Enable AI-powered conversational assistance with chat history, contextual responses, and seamless handoffs." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` · `com.cometchat:chatuikit-compose-android` | +| Key components | `CometChatAIAssistantChatHistory`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Purpose | Enable AI-powered conversational assistance with chat history, contextual responses, and seamless handoffs. | +| Related | [AI Assistant Chat History](/ui-kit/android/v6/ai-assistant-chat-history), [AI Features](/ui-kit/android/v6/ai-features), [All Guides](/ui-kit/android/v6/guide-overview) | + + + +Enable intelligent conversational AI capabilities in your Android app using CometChat UIKit v6 with AI Agent integration: + +- **AI Assistant Chat History** +- **Chat History Management** +- **Contextual Responses** +- **Agent Detection** +- **Seamless Handoffs** + +Transform your chat experience with AI-powered assistance that provides intelligent responses and seamless integration with your existing chat infrastructure. + + +**1:1 conversations only.** AI Agents currently respond only in one-on-one conversations between an end user and the agent user. They do not respond to messages sent in groups, even if the agent user is added as a member or owner. Group support is on the roadmap — share your use case on [feedback.cometchat.com](https://feedback.cometchat.com). + + +## Overview + +Users can interact with AI agents through a dedicated chat interface that: + +- Provides intelligent responses based on conversation context. +- Maintains chat history for continuity. +- Seamlessly integrates with your existing user chat system. + +The AI Agent chat interface provides a familiar messaging experience enhanced with AI capabilities, accessible through your main chat flow or as a standalone feature. + + + + + +## Prerequisites + +- Android Studio project with `com.cometchat:chatuikit-kotlin-android` or `com.cometchat:chatuikit-compose-android` in `build.gradle`. +- Internet permission in `AndroidManifest.xml`. +- Valid CometChat **App ID**, **Region**, and **Auth Key** configured via `UIKitSettings`. +- User logged in with `CometChatUIKit.login()`. +- AI Agent configured in your CometChat dashboard. + +## Components + +| Component / Class | Role | +|:----------------------------------|:-----| +| `AIAssistantChatActivity` | Main activity for AI agent chat. | +| `CometChatAIAssistantChatHistory` | Displays previous AI conversation history. | +| `CometChatMessageList` | Shows AI messages with threading support. | +| `CometChatMessageComposer` | Input interface for AI conversations. | +| `CometChatMessageHeader` | Header with AI agent info and controls. | + +## Integration Steps + +### Step 1 — Activity / Screen Setup + +Create the AI Assistant chat screen with proper layout configuration. + + + +```kotlin AIAssistantChatActivity.kt lines +class AIAssistantChatActivity : AppCompatActivity() { + private lateinit var binding: ActivityAiAssistantChatBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAiAssistantChatBinding.inflate(layoutInflater) + setContentView(binding.root) + + val messageJson = intent.getStringExtra(getString(R.string.app_base_message)) + val userJson = intent.getStringExtra(getString(R.string.app_user)) + + var user: User? = null + var parentMessage: BaseMessage? = null + + if (!userJson.isNullOrEmpty()) + user = User.fromJson(userJson) + if (!messageJson.isNullOrEmpty()) + parentMessage = BaseMessage.processMessage(JSONObject(messageJson)) + + initializeComponents(user, parentMessage) + initClickListeners() + } + + private fun initializeComponents(user: User?, parentMessage: BaseMessage?) { + user?.let { + binding.messageHeader.user = it + binding.messageList.user = it + binding.messageComposer.user = it + } + + if (parentMessage != null) { + binding.messageList.setParentMessage(parentMessage.getId()) + binding.messageComposer.setParentMessageId(parentMessage.getId()) + } + + binding.messageList.setStyle(R.style.CustomCometChatMessageListStyle) + binding.messageComposer.style = R.style.CustomMessageComposerStyle + } +} +``` + + + +```kotlin AIAssistantChatScreen.kt lines +import com.cometchat.uikit.compose.presentation.messageheader.ui.CometChatMessageHeader +import com.cometchat.uikit.compose.presentation.messagelist.ui.CometChatMessageList +import com.cometchat.uikit.compose.presentation.messagecomposer.ui.CometChatMessageComposer + +@Composable +fun AIAssistantChatScreen( + user: User, + parentMessageId: Int? = null, + onNewChatClick: () -> Unit = {}, + onChatHistoryClick: () -> Unit = {} +) { + Column(modifier = Modifier.fillMaxSize()) { + CometChatMessageHeader( + user = user + ) + + CometChatMessageList( + user = user, + parentMessageId = parentMessageId ?: 0, + modifier = Modifier.weight(1f) + ) + + CometChatMessageComposer( + user = user, + parentMessageId = parentMessageId ?: 0 + ) + } +} +``` + + + +**File reference:** +[`AIAssistantChatActivity.kt`](https://github.com/cometchat/cometchat-uikit-android/blob/v6/ai-sample-app/src/main/java/com/cometchat/ai/sampleapp/ui/activity/AIAssistantChatActivity.kt) + +### Step 2 — Layout (XML Views only) + +Add `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to your layout. + +```xml activity_ai_assistant_chat.xml lines + + + + + + + + + +``` + +> **Note:** In Jetpack Compose, layout is handled declaratively in the composable function — no XML needed. + +### Step 3 — Style of Message List & Composer (XML Views only) + +Define custom styles for the message list and composer to differentiate AI agent chats. + +```xml themes.xml lines + + + + + +``` + +> **Jetpack Compose:** Pass a custom style object via the `style` parameter on each composable instead of XML styles. + +### Step 4 — Initialize click listeners + +Initialize click listeners to handle new chat creation and chat history access. + + + +```kotlin AIAssistantChatActivity.kt lines +private fun initClickListeners() { + // New chat creation + binding.messageHeader.setNewChatButtonClick { + Utils.hideKeyBoard(this@AIAssistantChatActivity, binding.root) + val intent = Intent(this@AIAssistantChatActivity, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), user.toJson().toString()) + startActivity(intent) + finish() + } + + // Chat history access + binding.messageHeader.setChatHistoryButtonClick { + val intent = Intent(this@AIAssistantChatActivity, AIAssistantChatHistoryActivity::class.java) + intent.putExtra(getString(R.string.app_user), user.toJson().toString()) + startActivity(intent) + } +} +``` + + + +```kotlin AIAssistantChatScreen.kt lines +// In Jetpack Compose, pass callbacks as lambda parameters: +AIAssistantChatScreen( + user = aiUser, + onNewChatClick = { + // Navigate to a fresh AI chat screen + navController.navigate("ai_chat/${Gson().toJson(aiUser)}") + }, + onChatHistoryClick = { + // Navigate to chat history screen + navController.navigate("ai_chat_history/${Gson().toJson(aiUser)}") + } +) +``` + + + +### Step 5 — AI Assistant Chat History screen + +Create a screen to host the `CometChatAIAssistantChatHistory` component. + + + +```kotlin AIAssistantChatHistoryActivity.kt lines +class AIAssistantChatHistoryActivity : AppCompatActivity() { + private lateinit var binding: ActivityAiAssistantChatHistoryBinding + private var user: User? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivityAiAssistantChatHistoryBinding.inflate(layoutInflater) + setContentView(binding.root) + + val userJson = intent.getStringExtra(getString(R.string.app_user)) + + if (userJson != null && userJson.isNotEmpty()) { + user = User.fromJson(userJson) + binding.cometchatAiAssistantChatHistory.setUser(user) + } + + initClickListeners() + } + + private fun initClickListeners() { + binding.cometchatAiAssistantChatHistory.setOnItemClickListener { view, position, message -> + val appEntity = message.getReceiver() + if (appEntity is User) { + user = appEntity + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), appEntity.toJson().toString()) + intent.putExtra(getString(R.string.app_base_message), message.getRawMessage().toString()) + startActivity(intent) + finish() + } + } + + binding.cometchatAiAssistantChatHistory.setOnNewChatClickListener { + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), user!!.toJson().toString()) + startActivity(intent) + finish() + } + + binding.cometchatAiAssistantChatHistory.setOnCloseClickListener { + finish() + } + } +} +``` + + + +```kotlin AIAssistantChatHistoryScreen.kt lines +import com.cometchat.uikit.compose.presentation.aiassistantchathistory.ui.CometChatAIAssistantChatHistory + +@Composable +fun AIAssistantChatHistoryScreen( + user: User, + navController: NavController +) { + CometChatAIAssistantChatHistory( + modifier = Modifier.fillMaxSize(), + onCloseClick = { + navController.popBackStack() + }, + onNewChatClick = { + navController.navigate("ai_chat/${Gson().toJson(user)}") + }, + onItemClick = { message -> + val receiver = message.receiver + if (receiver is User) { + navController.navigate( + "ai_chat/${Gson().toJson(receiver)}/${message.rawMessage}" + ) + } + } + ) +} +``` + + + +### Step 6 — Chat History layout (XML Views only) + +```xml activity_ai_assistant_chat_history.xml lines + + + + + +``` + +> **Note:** In Jetpack Compose, the `CometChatAIAssistantChatHistory` composable is used directly — no XML layout needed. + +### Step 7 — Launching AI Chat + + + +```kotlin lines +fun launchAIAssistantChat(aiUser: User) { + val intent = Intent(this, AIAssistantChatActivity::class.java) + intent.putExtra(getString(R.string.app_user), aiUser.toJson().toString()) + startActivity(intent) +} +``` + + + +```kotlin lines +// In your NavHost setup: +composable("ai_chat/{userJson}") { backStackEntry -> + val userJson = backStackEntry.arguments?.getString("userJson") + val user = Gson().fromJson(userJson, User::class.java) + AIAssistantChatScreen(user = user) +} + +composable("ai_chat_history/{userJson}") { backStackEntry -> + val userJson = backStackEntry.arguments?.getString("userJson") + val user = Gson().fromJson(userJson, User::class.java) + AIAssistantChatHistoryScreen(user = user, navController = navController) +} +``` + + + +## Implementation Flow Summary + +| Step | Action | +|:-----|:-------| +| 1 | User selects AI agent from chat list | +| 2 | AI chat screen launches | +| 3 | Parse intent data and detect agent chat (Role of user must be "@agentic") | +| 4 | Initialize UI with AI-specific styling | +| 5 | Configure chat history and navigation | +| 6 | Launch chat with AI agent | + +## Customization Options + +- **Custom AI Assistant Empty Chat View:** Customize the empty state view using `setAIAssistantEmptyChatGreetingView()` (XML Views) or the `emptyView` composable slot (Compose). +- **Streaming Speed:** Adjust AI response streaming speed via `setStreamingSpeed()`. +- **AI Assistant Suggested Messages:** Create custom list of suggested messages using `setAIAssistantSuggestedMessages()`. +- **AI Assistant Tools:** Set tools for the AI agent using `setAIAssistantTools()`. + +## Feature Matrix + +| Feature | Kotlin (XML Views) | Jetpack Compose | +|:--------|:-------------------|:----------------| +| AI Chat Interface | `AIAssistantChatActivity` | `AIAssistantChatScreen` composable | +| Chat History | `CometChatAIAssistantChatHistory` XML | `CometChatAIAssistantChatHistory()` composable | +| Message List | `CometChatMessageList` XML | `CometChatMessageList()` composable | +| Message Composer | `CometChatMessageComposer` XML | `CometChatMessageComposer()` composable | + + + + Explore this feature in the CometChat AI Builder: + [GitHub → AI Builder](https://github.com/cometchat/cometchat-uikit-android/tree/v6/ai-sample-app) + + + Explore this feature in the CometChat SampleApp: + [GitHub → SampleApp](https://github.com/cometchat/cometchat-uikit-android/tree/v6/sample-app-kotlin) + + diff --git a/ui-kit/android/v6/guide-overview.mdx b/ui-kit/android/v6/guide-overview.mdx index 21ec20682..2551ff7d3 100644 --- a/ui-kit/android/v6/guide-overview.mdx +++ b/ui-kit/android/v6/guide-overview.mdx @@ -12,7 +12,7 @@ description: "Index of task-oriented feature guides for the CometChat Android UI | Purpose | Index of task-oriented feature guides for the Android UI Kit | | Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-android/tree/v6/sample-app-kotlin) | | Components | [Components Overview](/ui-kit/android/v6/components-overview) | -| Guides | [Block/Unblock](/ui-kit/android/v6/guide-block-unblock-user) · [Call Log Details](/ui-kit/android/v6/guide-call-log-details) · [Group Chat](/ui-kit/android/v6/guide-group-chat) · [Message Privately](/ui-kit/android/v6/guide-message-privately) · [New Chat](/ui-kit/android/v6/guide-new-chat) · [Search Messages](/ui-kit/android/guide-search-messages) · [Threaded Messages](/ui-kit/android/v6/guide-threaded-messages) · [AI Agent](/ui-kit/android/guide-ai-agent) · [Custom Text Formatter](/ui-kit/android/v6/custom-text-formatter-guide) · [Mentions Formatter](/ui-kit/android/v6/mentions-formatter-guide) · [ShortCut Formatter](/ui-kit/android/v6/shortcut-formatter-guide) | +| Guides | [Block/Unblock](/ui-kit/android/v6/guide-block-unblock-user) · [Call Log Details](/ui-kit/android/v6/guide-call-log-details) · [Group Chat](/ui-kit/android/v6/guide-group-chat) · [Message Privately](/ui-kit/android/v6/guide-message-privately) · [New Chat](/ui-kit/android/v6/guide-new-chat) · [Search Messages](/ui-kit/android/v6/guide-search-messages) · [Threaded Messages](/ui-kit/android/v6/guide-threaded-messages) · [AI Agent](/ui-kit/android/v6/guide-ai-agent) · [Custom Text Formatter](/ui-kit/android/v6/custom-text-formatter-guide) · [Mentions Formatter](/ui-kit/android/v6/mentions-formatter-guide) · [ShortCut Formatter](/ui-kit/android/v6/shortcut-formatter-guide) | @@ -39,8 +39,8 @@ The CometChat Android UI Kit is available in two modules: | [Message Privately](/ui-kit/android/v6/guide-message-privately) | Launch a direct 1:1 chat from a profile/list; optionally send initial message to surface conversation. | | [New Chat](/ui-kit/android/v6/guide-new-chat) | Unified entry for starting new 1:1 or group chats with tabbed Users / Groups search + navigation. | | [Threaded Messages](/ui-kit/android/v6/guide-threaded-messages) | Threaded replies: open parent message context, list replies, compose with parent linkage. | -| [Search Messages](/ui-kit/android/guide-search-messages) | Full-text message search across conversations with result routing and navigation. | -| [AI Agent](/ui-kit/android/guide-ai-agent) | Build an AI-powered agent that responds to user messages using CometChat's AI features. | +| [Search Messages](/ui-kit/android/v6/guide-search-messages) | Full-text message search across conversations with result routing and navigation. | +| [AI Agent](/ui-kit/android/v6/guide-ai-agent) | Build an AI-powered agent that responds to user messages using CometChat's AI features. | | [Custom Text Formatter](/ui-kit/android/v6/custom-text-formatter-guide) | Extend `CometChatTextFormatter` to build custom inline text patterns with tracking characters and suggestion lists. | | [Mentions Formatter](/ui-kit/android/v6/mentions-formatter-guide) | Format @mentions with styled tokens, suggestion lists, and click handling. | | [ShortCut Formatter](/ui-kit/android/v6/shortcut-formatter-guide) | Add shortcut text expansion to the message composer via the message-shortcuts extension. | diff --git a/ui-kit/android/v6/guide-search-messages.mdx b/ui-kit/android/v6/guide-search-messages.mdx new file mode 100644 index 000000000..d533d4d82 --- /dev/null +++ b/ui-kit/android/v6/guide-search-messages.mdx @@ -0,0 +1,235 @@ +--- +title: "Search Messages" +sidebarTitle: "Search Messages" +description: "Add full-text message search across conversations with result routing in CometChat Android UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Packages | `com.cometchat:chatuikit-kotlin-android` · `com.cometchat:chatuikit-compose-android` | +| Key components | `CometChatSearch`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatMessageHeader` | +| Purpose | Full-text message search across conversations with result routing and navigation | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-android/tree/v6/sample-app-kotlin) | +| Related | [Search Component](/ui-kit/android/v6/search), [All Guides](/ui-kit/android/v6/guide-overview) | + + + +Search Messages lets users locate specific messages across conversations and groups using keyword search, then navigate directly to the result. + +Before starting, complete the [Getting Started](/ui-kit/android/v6/getting-started) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatSearch` | Main search interface with filter chips and result lists | +| `CometChatMessageList` | Displays messages in the selected conversation | +| `CometChatMessageComposer` | Message input for the selected conversation | +| `CometChatMessageHeader` | Header bar showing conversation context | + +--- + +## Integration Steps + +### 1. Add CometChatSearch to your layout + + + +```xml activity_search.xml lines + +``` + + + +```kotlin SearchScreen.kt lines +import com.cometchat.uikit.compose.presentation.search.ui.CometChatSearch + +@Composable +fun SearchScreen(navController: NavController) { + CometChatSearch( + modifier = Modifier.fillMaxSize(), + onConversationClick = { conversation -> + navController.navigate("messages/${Gson().toJson(conversation)}") + }, + onMessageClick = { message -> + if (message.receiverType == CometChatConstants.RECEIVER_TYPE_USER) { + navController.navigate("messages/user/${(message.receiver as User).uid}/${message.id}") + } else { + navController.navigate("messages/group/${(message.receiver as Group).guid}/${message.id}") + } + } + ) +} +``` + + + +--- + +### 2. Handle conversation result clicks + +When a user taps a conversation result, navigate to the message view for that conversation. + + + +```kotlin SearchActivity.kt lines +val search: CometChatSearch = findViewById(R.id.cometchat_search) + +search.setOnConversationClicked { view, position, conversation -> + val intent = Intent(this, ChatActivity::class.java) + intent.putExtra("conversation", conversation) + startActivity(intent) +} +``` + + + +```kotlin SearchScreen.kt lines +// Handled inline via onConversationClick lambda in the CometChatSearch composable above +``` + + + +--- + +### 3. Handle message result clicks + +When a user taps a message result, navigate to the conversation and scroll to that message. + + + +```kotlin SearchActivity.kt lines +search.setOnMessageClicked { view, position, message -> + val intent = Intent(this, ChatActivity::class.java) + if (message.receiverType == CometChatConstants.RECEIVER_TYPE_USER) { + intent.putExtra("uid", (message.receiver as User).uid) + } else { + intent.putExtra("guid", (message.receiver as Group).guid) + } + intent.putExtra("messageId", message.id) + startActivity(intent) +} +``` + + + +```kotlin SearchScreen.kt lines +// Handled inline via onMessageClick lambda in the CometChatSearch composable above +``` + + + +--- + +### 4. Scope search to a specific conversation (optional) + +Restrict search results to a single user or group conversation. + + + +```kotlin lines +// Scope to a specific user conversation +search.setUid("alice-uid") + +// Or scope to a specific group conversation +search.setGuid("group-guid") +``` + + + +```kotlin lines +// Scope to a specific user conversation +CometChatSearch( + uid = "alice-uid", + modifier = Modifier.fillMaxSize(), + onConversationClick = { /* handle click */ }, + onMessageClick = { /* handle click */ } +) + +// Or scope to a specific group conversation +CometChatSearch( + guid = "group-guid", + modifier = Modifier.fillMaxSize(), + onConversationClick = { /* handle click */ }, + onMessageClick = { /* handle click */ } +) +``` + + + +--- + +### 5. Configure search filters (optional) + +Control which filter chips appear. + + + +```kotlin lines +search.setSearchFilters( + listOf( + UIKitConstants.SearchFilter.MESSAGES, + UIKitConstants.SearchFilter.CONVERSATIONS + ) +) +search.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES) +``` + + + +```kotlin lines +import com.cometchat.uikit.core.constants.SearchFilter + +CometChatSearch( + searchFilters = listOf( + SearchFilter.UNREAD, + SearchFilter.GROUPS, + SearchFilter.PHOTOS, + SearchFilter.VIDEOS + ), + modifier = Modifier.fillMaxSize(), + onConversationClick = { /* handle click */ }, + onMessageClick = { /* handle click */ } +) +``` + + + +--- + +## Feature Matrix + +| Feature | Kotlin (XML Views) | Jetpack Compose | +|:---|:---|:---| +| Search interface | `CometChatSearch` XML element | `CometChatSearch()` composable | +| Conversation results | `setOnConversationClicked` | `onConversationClick` lambda | +| Message results | `setOnMessageClicked` | `onMessageClick` lambda | +| Scoped search | `setUid()` / `setGuid()` | `uid` / `guid` parameters | +| Filter chips | `setSearchFilters()` | `searchFilters` parameter | +| Custom views | `setEmptyView()`, `setErrorView()` | `emptyView`, `errorView` composable slots | + +--- + +## Next Steps + + + + The search component reference + + + Display messages in a conversation + + + Browse all feature and formatter guides + + + Full working sample application on GitHub + + diff --git a/ui-kit/android/v6/overview.mdx b/ui-kit/android/v6/overview.mdx index c00836192..e3ef30f66 100644 --- a/ui-kit/android/v6/overview.mdx +++ b/ui-kit/android/v6/overview.mdx @@ -4,10 +4,6 @@ sidebarTitle: "Overview" description: "Prebuilt Android Views for chat & messaging, voice & video calling. Supports Kotlin with XML Views and Jetpack Compose." --- - -This is a beta release. APIs and components may change before the stable release. Report issues on [GitHub](https://github.com/cometchat/cometchat-uikit-android/issues). - - | Field | Value | diff --git a/ui-kit/android/v6/search.mdx b/ui-kit/android/v6/search.mdx new file mode 100644 index 000000000..7aa3cd0f2 --- /dev/null +++ b/ui-kit/android/v6/search.mdx @@ -0,0 +1,1136 @@ +--- +title: "Search" +description: "Real-time search interface for finding conversations and messages with filters, scopes, and customization options." +--- + + +```json +{ + "component": "CometChatSearch", + "package": "com.cometchat.uikit.kotlin.presentation.search (XML Views) / com.cometchat.uikit.compose.presentation.search (Compose)", + "xmlElement": "", + "description": "Real-time search interface for finding conversations and messages with filters, scopes, and customization options.", + "primaryOutput": { + "conversationClicked": { + "method": "setOnConversationClicked", + "type": "OnItemClick" + }, + "messageClicked": { + "method": "setOnMessageClicked", + "type": "OnItemClick" + } + }, + "methods": { + "data": { + "setConversationsRequestBuilder": { + "type": "ConversationsRequest.ConversationsRequestBuilder", + "default": "SDK default", + "note": "Pass the builder, not the result of .build()" + }, + "setMessagesRequestBuilder": { + "type": "MessagesRequest.MessagesRequestBuilder", + "default": "SDK default", + "note": "Pass the builder, not the result of .build()" + } + }, + "callbacks": { + "setOnConversationClicked": "OnItemClick", + "setOnMessageClicked": "OnItemClick", + "setOnBackPressListener": "OnBackPress", + "setOnError": "OnError", + "setOnEmpty": "OnEmpty", + "setOnLoadMessages": "OnLoad", + "setOnLoadConversations": "OnLoad" + }, + "visibility": { + "setEmptyStateVisibility": { "type": "int (View.VISIBLE | View.GONE)", "default": "View.VISIBLE" }, + "setErrorStateVisibility": { "type": "int", "default": "View.VISIBLE" } + }, + "functionality": { + "setUid": { "type": "String", "note": "Scope search to a specific user conversation" }, + "setGuid": { "type": "String", "note": "Scope search to a specific group conversation" }, + "setSearchFilters": { "type": "List", "note": "Filters rendered as chips" }, + "setInitialSearchFilter": { "type": "UIKitConstants.SearchFilter", "note": "Default active filter on load" }, + "setSearchIn": { "type": "List", "note": "Entities to search in" }, + "setHideGroupType": { "type": "boolean", "default": "false" }, + "setHideUserStatus": { "type": "boolean", "default": "false" } + }, + "viewSlots": { + "setConversationItemView": "ConversationsSearchViewHolderListener — entire conversation item row", + "setTextMessageItemView": "MessagesSearchViewHolderListener — text message item", + "setImageMessageItemView": "MessagesSearchViewHolderListener — image message item", + "setAudioMessageItemView": "MessagesSearchViewHolderListener — audio message item", + "setVideoMessageItemView": "MessagesSearchViewHolderListener — video message item", + "setDocumentMessageItemView": "MessagesSearchViewHolderListener — document message item", + "setLinkMessageItemView": "MessagesSearchViewHolderListener — link message item", + "setInitialView": "@LayoutRes int — initial state before search", + "setEmptyView": "@LayoutRes int — empty state", + "setLoadingView": "View — loading state", + "setErrorView": "View — error state" + }, + "advanced": { + "setTextFormatters": "List — custom text formatters", + "setDateTimeFormatter": "DateTimeFormatterCallback — custom date/time formatting", + "setMentionAllLabelId": "String id, String mentionAllLabel — custom mention-all label", + "setHintText": "String — search bar hint text" + }, + "style": { + "setStyle": { + "type": "@StyleRes int", + "parent": "CometChatSearchStyle" + } + } + }, + "events": [], + "sdkListeners": [] +} +``` + + + +## Where It Fits + +`CometChatSearch` is a composite search component. It searches across conversations and messages in real time and emits the selected result via `setOnConversationClicked` or `setOnMessageClicked`. Wire it to navigation so tapping a conversation opens the message view, or tapping a message scrolls to it in context. + + + +```kotlin ChatActivity.kt lines +class ChatActivity : AppCompatActivity() { + + private lateinit var search: CometChatSearch + private lateinit var messageHeader: CometChatMessageHeader + private lateinit var messageList: CometChatMessageList + private lateinit var messageComposer: CometChatMessageComposer + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_chat) + + search = findViewById(R.id.cometchat_search) + messageHeader = findViewById(R.id.message_header) + messageList = findViewById(R.id.message_list) + messageComposer = findViewById(R.id.message_composer) + + search.setOnConversationClicked { view, position, conversation -> + val user = conversation.conversationWith as? User + user?.let { + messageHeader.setUser(it) + messageList.setUser(it) + messageComposer.setUser(it) + } + } + + search.setOnMessageClicked { view, position, baseMessage -> + // Navigate to the message in context + } + } +} +``` + + +```kotlin lines +CometChatSearch( + onMessageClick = { message -> + Log.i(TAG, "Message Clicked!") + } +) +``` + + + +## Quick Start + +Add the component to your layout XML: + +```xml activity_search.xml lines + + + + + + +``` + + + + + +Prerequisites: CometChat SDK initialized with `CometChatUIKit.init()`, a user logged in, and the `cometchat-chat-uikit-android` dependency added. + +To add programmatically in an Activity: + + + +```kotlin SearchActivity.kt lines +class SearchActivity : AppCompatActivity() { + private lateinit var binding: ActivitySearchBinding + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + binding = ActivitySearchBinding.inflate(layoutInflater) + setContentView(binding.root) + } +} +``` + + +```kotlin lines +CometChatSearch( + onMessageClick = { message -> + Log.i(TAG, "Message Clicked!") + } +) +``` + + + +## Actions and Events + +### Callback Methods + +#### `setOnConversationClicked` + +Fires when a user taps a conversation from the search results. Primary navigation hook — set the active conversation and render the message view. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setOnConversationClicked { view, position, conversation -> + Log.i(TAG, "onCreate: Conversation Clicked !") +} +``` + + +```kotlin lines +CometChatSearch( + onConversationClick = { conversation -> + Log.i(TAG, "Conversation Clicked!") + } +) +``` + + + +> **What this does:** Replaces the default conversation-click behavior. When a user taps a conversation item, your custom lambda executes. The callback receives the view, position, and `Conversation` object. + +#### `setOnMessageClicked` + +Fires when a user taps a message from the search results. Use to navigate to the message in context. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setOnMessageClicked { view, position, baseMessage -> + Log.i(TAG, "onCreate: Message Clicked !") +} +``` + + +```kotlin lines +CometChatSearch( + onMessageClick = { message -> + Log.i(TAG, "Message Clicked!") + } +) +``` + + + +> **What this does:** Registers a callback that fires when the user taps a message in the search results. The callback receives the view, position, and `BaseMessage` object. + +#### `setOnBackPressListener` + +Fires when the user presses the back button in the search bar. Default: no predefined behavior. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setOnBackPressListener { + Log.i(TAG, "onCreate: Back Pressed !") +} +``` + + +```kotlin lines +CometChatSearch( + onBackPress = { + Log.i(TAG, "Back Pressed!") + } +) +``` + + + +#### `setOnError` + +Fires on internal errors (network failure, auth issue, SDK exception). + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.onError = OnError { + Log.i(TAG, "onCreate: Error Occurred ! ${it.message}") +} +``` + + +```kotlin lines +CometChatSearch( + onError = { exception -> + Log.i(TAG, "Error: ${exception.message}") + } +) +``` + + + +#### `setOnLoadMessages` + +Fires when the message list is successfully fetched and loaded, helping track when message search results are ready. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setOnLoadMessages(OnLoad { list -> + Log.i(TAG, "Messages loaded: ${list.size}") +}) +``` + + +```kotlin lines +CometChatSearch( + onLoadMessages = { messages -> + Log.i(TAG, "Messages loaded: ${messages.size}") + } +) +``` + + + +#### `setOnLoadConversations` + +Fires when the conversation list is successfully fetched and loaded, helping track when conversation search results are ready. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setOnLoadConversations(OnLoad { list -> + Log.i(TAG, "Conversations loaded: ${list.size}") +}) +``` + + +```kotlin lines +CometChatSearch( + onLoadConversations = { conversations -> + Log.i(TAG, "Conversations loaded: ${conversations.size}") + } +) +``` + + + +#### `setOnEmpty` + +Fires when the search returns no results, enabling custom handling such as showing a placeholder. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.onEmpty = OnEmpty { + Log.i(TAG, "onCreate: No Results Found !") +} +``` + + +```kotlin lines +CometChatSearch( + onEmpty = { + Log.i(TAG, "No Results Found!") + } +) +``` + + + +- **Verify**: After setting an action callback, trigger the corresponding user interaction (tap a conversation result, tap a message result, press back, cause an error, or search for a term with no results) and confirm your custom logic executes. + +### Global UI Events + +The `CometChatSearch` component does not produce any global UI events. + +### SDK Events (Real-Time, Automatic) + +The `CometChatSearch` component does not listen to any SDK events internally. Search results are fetched on demand when the user types a query. + +## Functionality + +Small functional customizations such as toggling visibility of UI elements and configuring search scope. + +| Methods | Description | Code | +| --- | --- | --- | +| `setEmptyStateVisibility` | Hides the empty state when search returns no results | `.setEmptyStateVisibility(View.GONE);` | +| `setErrorStateVisibility` | Hides the error state on search failure | `.setErrorStateVisibility(View.GONE);` | +| `setSearchFilters` | List of filters rendered as chips in the search component | `.setSearchFilters(filters);` | +| `setInitialSearchFilter` | The filter which will be active by default on load | `.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES);` | +| `setSearchIn` | List of entities in which the search should be performed | `.setSearchIn(scopes);` | +| `setHideGroupType` | Hides the group type icon in conversation leading view | `.setHideGroupType(true);` | +| `setHideUserStatus` | Hides the user's online/offline status indicator | `.setHideUserStatus(true);` | + +- **Verify**: After calling a visibility or functionality method, confirm the corresponding UI element is shown or hidden, or the search scope is correctly applied. + +## Custom View Slots + +Each slot replaces a section of the default UI. Conversation item slots use the `ConversationsSearchViewHolderListener` pattern (`createView` + `bindView`). Message item slots use the `MessagesSearchViewHolderListener` pattern. + +| Slot | Method | Replaces | +| --- | --- | --- | +| Conversation item view | `setConversationItemView(ConversationsSearchViewHolderListener)` | Entire conversation item row | +| Text message item | `setTextMessageItemView(MessagesSearchViewHolderListener)` | Text message item | +| Image message item | `setImageMessageItemView(MessagesSearchViewHolderListener)` | Image message item | +| Audio message item | `setAudioMessageItemView(MessagesSearchViewHolderListener)` | Audio message item | +| Video message item | `setVideoMessageItemView(MessagesSearchViewHolderListener)` | Video message item | +| Document message item | `setDocumentMessageItemView(MessagesSearchViewHolderListener)` | Document message item | +| Link message item | `setLinkMessageItemView(MessagesSearchViewHolderListener)` | Link message item | +| Initial view | `setInitialView(@LayoutRes int)` | Initial state before search | +| Empty view | `setEmptyView(@LayoutRes int)` | Empty state | +| Loading view | `setLoadingView(View)` | Loading spinner | +| Error view | `setErrorView(View)` | Error state | + +### `setConversationItemView` + +Replace the entire conversation item row in search results. + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setConversationItemView(object : ConversationsSearchViewHolderListener() { + override fun createView(context: Context?, listItem: View?): View? { + return layoutInflater.inflate(R.layout.custom_conversation_search_item, null) + } + + override fun bindView( + context: Context?, + createdView: View?, + conversation: Conversation?, + holder: RecyclerView.ViewHolder?, + conversationList: List?, + position: Int + ) { + val titleTv = createdView?.findViewById(R.id.tv_title) + conversation?.let { + if (it.conversationType == CometChatConstants.CONVERSATION_TYPE_USER) { + titleTv?.text = (it.conversationWith as User).name + } else { + titleTv?.text = (it.conversationWith as Group).name + } + } + } +}) +``` + + +```kotlin lines +CometChatSearch( + conversationItemView = { conversation -> + Row(modifier = Modifier.padding(16.dp)) { + val name = when (conversation.conversationType) { + CometChatConstants.CONVERSATION_TYPE_USER -> + (conversation.conversationWith as User).name + else -> + (conversation.conversationWith as Group).name + } + Text(text = name ?: "", style = MaterialTheme.typography.bodyLarge) + } + } +) +``` + + + +> **What this does:** Registers a `ConversationsSearchViewHolderListener` for conversation items in search results. The `createView` method inflates a custom layout, and `bindView` populates it with the conversation name based on whether it's a user or group conversation. + +### `setTextMessageItemView` + +Replace the text message item view in search results. + +Define a custom layout XML: + +```xml custom_message_item_view.xml lines + + + + + + + +``` + + + +```kotlin SearchActivity.kt lines +binding.cometchatSearch.setTextMessageItemView(object : MessagesSearchViewHolderListener() { + override fun createView( + context: Context?, + listItem: View? + ): View? { + return layoutInflater.inflate(R.layout.custom_message_item_view, null) + } + + override fun bindView( + context: Context?, + createdView: View?, + message: TextMessage?, + holder: RecyclerView.ViewHolder?, + messagesList: List?, + position: Int + ) { + val titleTv = createdView?.findViewById(R.id.tv_sender_name) + val messageTv = createdView?.findViewById(R.id.tv_message) + + titleTv?.text = message?.sender?.name + messageTv?.text = message?.text + } +}) +``` + + +```kotlin lines +CometChatSearch( + textMessageItemView = { message -> + Row( + modifier = Modifier + .fillMaxWidth() + .background(Color(0xFFE8E4F3)) + .padding(16.dp) + ) { + Text( + text = "${message.sender?.name}: ", + color = Color(0xFF6B4FBB), + fontWeight = FontWeight.Bold + ) + Text( + text = message.text ?: "", + color = Color(0xFF4A4A4A), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + } +) +``` + + + +> **What this does:** Registers a `MessagesSearchViewHolderListener` for text messages. The `createView` method inflates the custom layout, and `bindView` populates the sender name and message text from the `TextMessage` object. + + + + + +### Other Message Item Views + +The following message item view methods follow the same `MessagesSearchViewHolderListener` pattern as `setTextMessageItemView`: + +| Method | Message Type | Generic Type | +| --- | --- | --- | +| `setImageMessageItemView` | Image Message | `MessagesSearchViewHolderListener` | +| `setVideoMessageItemView` | Video Message | `MessagesSearchViewHolderListener` | +| `setAudioMessageItemView` | Audio Message | `MessagesSearchViewHolderListener` | +| `setDocumentMessageItemView` | Document Message | `MessagesSearchViewHolderListener` | +| `setLinkMessageItemView` | Link Message | `MessagesSearchViewHolderListener` | + +### `setInitialView` + +Sets a custom view displayed when the search component is rendered and no search has been performed. + + + +```kotlin lines +binding.cometchatSearch.setInitialView(R.layout.your_initial_view) +``` + + +```kotlin lines +CometChatSearch( + initialView = { + // Your custom initial composable + Text("Start searching...") + } +) +``` + + + +### `setEmptyView` + +Configures a custom view displayed when the search returns no results. + + + +```kotlin lines +binding.cometchatSearch.setEmptyView(R.layout.your_empty_view) +``` + + +```kotlin lines +CometChatSearch( + emptyView = { + // Your custom empty state composable + Text("No results found") + } +) +``` + + + +### `setLoadingView` + +Sets a custom loading view displayed when search results are being fetched. + + + +```kotlin lines +binding.cometchatSearch.setLoadingView(loadingView) +``` + + +```kotlin lines +CometChatSearch( + loadingView = { + // Your custom loading composable + CircularProgressIndicator() + } +) +``` + + + +### `setErrorView` + +Defines a custom error state view that appears when an issue occurs while searching. + + + +```kotlin lines +binding.cometchatSearch.setErrorView(errorView) +``` + + +```kotlin lines +CometChatSearch( + errorView = { onRetry -> + // Your custom error composable + Column { + Text("Something went wrong") + Button(onClick = onRetry) { Text("Retry") } + } + } +) +``` + + + +- **Verify**: After setting any custom view slot, confirm the custom view renders in the correct position within the search result items, and the data binding populates correctly for each result. + +## Common Patterns + +### Messages-only search + + + +```kotlin lines +binding.cometchatSearch.setSearchFilters( + listOf(UIKitConstants.SearchFilter.MESSAGES) +) +binding.cometchatSearch.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES) +``` + + +```kotlin lines +import com.cometchat.uikit.core.constants.SearchFilter + +CometChatSearch( + searchFilters = listOf(SearchFilter.UNREAD), + modifier = Modifier.fillMaxSize() +) +``` + + + +### Filter by message type + + + +```kotlin lines +binding.cometchatSearch.setMessagesRequestBuilder( + MessagesRequest.MessagesRequestBuilder().setLimit(10) +) +``` + + +```kotlin lines +import com.cometchat.uikit.core.constants.SearchFilter + +CometChatSearch( + searchFilters = listOf(SearchFilter.UNREAD), + modifier = Modifier.fillMaxSize() +) +``` + + + +### Scope search to a specific user + + + +```kotlin lines +binding.cometchatSearch.setUid("user123") +``` + + +```kotlin lines +CometChatSearch( + uid = "user123", + modifier = Modifier.fillMaxSize() +) +``` + + + +### Scope search to a specific group + + + +```kotlin lines +binding.cometchatSearch.setGuid("group123") +``` + + +```kotlin lines +CometChatSearch( + guid = "group123", + modifier = Modifier.fillMaxSize() +) +``` + + + +## Advanced Methods + +### Search Scope + +#### `setUid` + +Scopes the search to a specific user's conversation. + + + +```kotlin lines +binding.cometchatSearch.setUid("user123") +``` + + +```kotlin lines +CometChatSearch( + uid = "user123", + modifier = Modifier.fillMaxSize() +) +``` + + + +#### `setGuid` + +Scopes the search to a specific group's conversation. + + + +```kotlin lines +binding.cometchatSearch.setGuid("group123") +``` + + +```kotlin lines +CometChatSearch( + guid = "group123", + modifier = Modifier.fillMaxSize() +) +``` + + + +### Request Builders + +#### `setConversationsRequestBuilder` + +Sets a `ConversationsRequest.ConversationsRequestBuilder` to filter conversation search results. Pass the builder instance — not the result of `.build()`. For all available builder options, refer to the [ConversationRequestBuilder](/sdk/android/retrieve-conversations) documentation. + + + +```kotlin lines +binding.cometchatSearch.setConversationsRequestBuilder( + ConversationsRequest.ConversationsRequestBuilder().setLimit(10) +) +``` + + +```kotlin lines +CometChatSearch( + guid = "group123", + modifier = Modifier.fillMaxSize() +) +``` + + + +#### `setMessagesRequestBuilder` + +Sets a `MessagesRequest.MessagesRequestBuilder` to filter message search results. For all available builder options, refer to the [MessagesRequestBuilder](/sdk/android/additional-message-filtering) documentation. + + + +```kotlin lines +binding.cometchatSearch.setMessagesRequestBuilder( + MessagesRequest.MessagesRequestBuilder().setLimit(5) +) +``` + + +```kotlin lines +CometChatSearch( + guid = "group123", + modifier = Modifier.fillMaxSize() +) +``` + + + +### Text Formatters + +#### `setTextFormatters` + +Enables developers to define and apply text formatters that dynamically modify or transform message content before rendering it in the UI. Text formatters can be used for: + +* Automatically converting URLs into clickable links +* Applying Markdown or rich text styling +* Replacing certain words or patterns with emojis or predefined text +* Censoring specific words for moderation + +For implementation details, refer to the [MentionsFormatter Guide](/ui-kit/android/v6/mentions-formatter-guide). + +### Date/Time Formatting + +#### `setDateTimeFormatter` + +Provides a custom implementation of `DateTimeFormatterCallback` to configure how time and date values are displayed in search results. + + + +```kotlin lines +import java.text.SimpleDateFormat +import java.util.* + +binding.cometchatSearch.setDateTimeFormatter(object : DateTimeFormatterCallback { + + private val fullTimeFormatter = SimpleDateFormat("hh:mm a", Locale.getDefault()) + private val dateFormatter = SimpleDateFormat("dd MMM yyyy", Locale.getDefault()) + + override fun time(timestamp: Long): String { + return fullTimeFormatter.format(Date(timestamp)) + } + + override fun today(timestamp: Long): String { + return "Today" + } + + override fun yesterday(timestamp: Long): String { + return "Yesterday" + } + + override fun lastWeek(timestamp: Long): String { + return "Last Week" + } + + override fun otherDays(timestamp: Long): String { + return dateFormatter.format(Date(timestamp)) + } + + override fun minutes(diffInMinutesFromNow: Long, timestamp: Long): String { + return "$diffInMinutesFromNow mins ago" + } + + override fun hours(diffInHourFromNow: Long, timestamp: Long): String { + return "$diffInHourFromNow hrs ago" + } +}) +``` + + +```kotlin lines +CometChatSearch( + guid = "group123", + modifier = Modifier.fillMaxSize() +) +``` + + + +> **What this does:** Provides a custom date/time formatter that displays "Today", "Yesterday", "Last Week" for recent messages, a "dd MMM yyyy" format for older messages, and relative time strings like "5 mins ago" or "2 hrs ago" for recent activity. + +### Other Advanced Methods + +| Method | Type | Description | +| --- | --- | --- | +| `setMentionAllLabelId` | `String id, String mentionAllLabel` | Sets a custom label for the "mention all" feature for a specific ID | +| `setHintText` | `String` | Sets the hint text displayed in the search bar | + +## Style + +The component uses XML theme styles. Define a custom style with parent `CometChatSearchStyle` in `themes.xml`, then apply with `setStyle()`. + + + + + +```xml themes.xml lines + + + +``` + +> **What this does:** Defines a custom search style that sets a light purple background color (`#EDEAFA`) for the search component, conversation items, and message items, and applies a Times New Roman font to all text elements including filter chips, section headers, conversation titles/subtitles, message titles/subtitles, timestamps, "see more" text, and the search bar. + + + +```kotlin lines +binding.cometchatSearch.setStyle(R.style.CustomSearchStyle) +``` + + +```kotlin lines +import com.cometchat.uikit.compose.presentation.search.style.CometChatSearchStyle + +CometChatSearch( + style = CometChatSearchStyle.default().copy( + backgroundColor = Color(0xFFEDEAFA), + searchBarBackgroundColor = Color(0xFFEDEAFA), + filterChipBackgroundColor = Color(0xFFEDEAFA) + ), + modifier = Modifier.fillMaxSize() +) +``` + + + +To view all available style attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v6/chatuikit/src/main/res/values/attr_cometchat_search.xml). + +### Programmatic Style Properties + +In addition to XML theme styles, the component exposes programmatic setters for fine-grained control: + +**Search Bar** + +| Method | Type | Description | +| --- | --- | --- | +| `setBackgroundColor` | `@ColorInt int` | Background color of the component | +| `setSearchBarBackgroundColor` | `@ColorInt int` | Background color of the search bar | +| `setSearchBarStrokeWidth` | `@Dimension int` | Stroke width of the search bar border | +| `setSearchBarStrokeColor` | `@ColorInt int` | Stroke color of the search bar border | +| `setSearchBarCornerRadius` | `@Dimension int` | Corner radius of the search bar | +| `setSearchBarTextColor` | `@ColorInt int` | Text color of the search bar input | +| `setSearchBarTextAppearance` | `@StyleRes int` | Text appearance of the search bar input | +| `setSearchBarHintTextColor` | `@ColorInt int` | Hint text color of the search bar | +| `setBackIcon` | `Drawable` | Custom back icon drawable | +| `setBackIconTint` | `@ColorInt int` | Tint color for the back icon | +| `setClearIcon` | `Drawable` | Custom clear icon drawable | +| `setClearIconTint` | `@ColorInt int` | Tint color for the clear icon | +| `setSearchIcon` | `Drawable` | Custom search icon drawable | +| `setSearchIconTint` | `@ColorInt int` | Tint color for the search icon | + +**Filter Chips** + +| Method | Type | Description | +| --- | --- | --- | +| `setFilterChipBackgroundColor` | `@ColorInt int` | Background color of filter chips | +| `setFilterChipSelectedBackgroundColor` | `@ColorInt int` | Background color of selected filter chips | +| `setFilterChipTextColor` | `@ColorInt int` | Text color of filter chips | +| `setFilterChipSelectedTextColor` | `@ColorInt int` | Text color of selected filter chips | +| `setFilterChipTextAppearance` | `@StyleRes int` | Text appearance of filter chips | +| `setFilterChipStrokeColor` | `@ColorInt int` | Stroke color of filter chips | +| `setFilterChipSelectedStrokeColor` | `@ColorInt int` | Stroke color of selected filter chips | +| `setFilterChipStrokeWidth` | `@Dimension int` | Stroke width of filter chips | +| `setFilterChipCornerRadius` | `@Dimension int` | Corner radius of filter chips | + +**Section Headers** + +| Method | Type | Description | +| --- | --- | --- | +| `setSectionHeaderTextColor` | `@ColorInt int` | Text color for section headers | +| `setSectionHeaderTextAppearance` | `@StyleRes int` | Text appearance for section headers | +| `setSectionHeaderBackgroundColor` | `@ColorInt int` | Background color for section headers | + +**Conversation Items** + +| Method | Type | Description | +| --- | --- | --- | +| `setConversationItemBackgroundColor` | `@ColorInt int` | Background color for conversation items | +| `setConversationTitleTextColor` | `@ColorInt int` | Text color for conversation titles | +| `setConversationTitleTextAppearance` | `@StyleRes int` | Text appearance for conversation titles | +| `setConversationSubtitleTextColor` | `@ColorInt int` | Text color for conversation subtitles | +| `setConversationSubtitleTextAppearance` | `@StyleRes int` | Text appearance for conversation subtitles | +| `setConversationTimestampTextColor` | `@ColorInt int` | Text color for conversation timestamps | +| `setConversationTimestampTextAppearance` | `@StyleRes int` | Text appearance for conversation timestamps | + +**Message Items** + +| Method | Type | Description | +| --- | --- | --- | +| `setMessageItemBackgroundColor` | `@ColorInt int` | Background color for message items | +| `setMessageTitleTextColor` | `@ColorInt int` | Text color for message titles | +| `setMessageTitleTextAppearance` | `@StyleRes int` | Text appearance for message titles | +| `setMessageSubtitleTextColor` | `@ColorInt int` | Text color for message subtitles | +| `setMessageSubtitleTextAppearance` | `@StyleRes int` | Text appearance for message subtitles | +| `setMessageTimestampTextColor` | `@ColorInt int` | Text color for message timestamps | +| `setMessageTimestampTextAppearance` | `@StyleRes int` | Text appearance for message timestamps | +| `setMessageLinkTextColor` | `@ColorInt int` | Text color for links in messages | +| `setMessageLinkTextAppearance` | `@StyleRes int` | Text appearance for links in messages | + +**Other Style Properties** + +| Method | Type | Description | +| --- | --- | --- | +| `setAvatarStyle` | `@StyleRes int` | Style for avatars in search results | +| `setBadgeStyle` | `@StyleRes int` | Style for badges in search results | +| `setSeeMoreTextColor` | `@ColorInt int` | Text color for "See more" links | +| `setSeeMoreTextAppearance` | `@StyleRes int` | Text appearance for "See more" links | +| `setDateSeparatorTextColor` | `@ColorInt int` | Text color for date separators | +| `setDateSeparatorBackgroundColor` | `@ColorInt int` | Background color for date separators | +| `setDateSeparatorTextAppearance` | `@StyleRes int` | Text appearance for date separators | +| `setEmptyStateTextColor` | `@ColorInt int` | Title text color for the empty state | +| `setEmptyStateTextAppearance` | `@StyleRes int` | Title text appearance for the empty state | +| `setEmptyStateSubtitleTextColor` | `@ColorInt int` | Subtitle text color for the empty state | +| `setEmptyStateSubtitleTextAppearance` | `@StyleRes int` | Subtitle text appearance for the empty state | +| `setEmptyStateIcon` | `Drawable` | Icon for the empty state | +| `setEmptyStateIconTint` | `@ColorInt int` | Tint for the empty state icon | +| `setErrorStateTextColor` | `@ColorInt int` | Title text color for the error state | +| `setErrorStateTextAppearance` | `@StyleRes int` | Title text appearance for the error state | +| `setErrorStateSubtitleTextColor` | `@ColorInt int` | Subtitle text color for the error state | +| `setErrorStateSubtitleTextAppearance` | `@StyleRes int` | Subtitle text appearance for the error state | +| `setErrorStateIcon` | `Drawable` | Icon for the error state | +| `setErrorStateIconTint` | `@ColorInt int` | Tint for the error state icon | + +## Customization Matrix + +| What to change | Where | Property/API | Example | +| --- | --- | --- | --- | +| Override behavior on conversation tap | Activity/Fragment | `setOnConversationClicked` | `setOnConversationClicked { v, pos, conv -> ... }` | +| Override behavior on message tap | Activity/Fragment | `setOnMessageClicked` | `setOnMessageClicked { v, pos, msg -> ... }` | +| Override back press behavior | Activity/Fragment | `setOnBackPressListener` | `setOnBackPressListener { ... }` | +| Scope search to a user | Activity/Fragment | `setUid(String)` | `.setUid("user123")` | +| Scope search to a group | Activity/Fragment | `setGuid(String)` | `.setGuid("group123")` | +| Hide user online status | Activity/Fragment | `setHideUserStatus(boolean)` | `.setHideUserStatus(true)` | +| Hide group type icon | Activity/Fragment | `setHideGroupType(boolean)` | `.setHideGroupType(true)` | +| Set search filters | Activity/Fragment | `setSearchFilters(List)` | `.setSearchFilters(filters)` | +| Set initial active filter | Activity/Fragment | `setInitialSearchFilter(SearchFilter)` | `.setInitialSearchFilter(UIKitConstants.SearchFilter.MESSAGES)` | +| Set search scope | Activity/Fragment | `setSearchIn(List)` | `.setSearchIn(scopes)` | +| Filter conversation results | Activity/Fragment | `setConversationsRequestBuilder` | See Request Builders code above | +| Filter message results | Activity/Fragment | `setMessagesRequestBuilder` | See Request Builders code above | +| Custom conversation item view | Activity/Fragment | `setConversationItemView(ConversationsSearchViewHolderListener)` | See `setConversationItemView` code above | +| Custom text message item view | Activity/Fragment | `setTextMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` code above | +| Custom image message item view | Activity/Fragment | `setImageMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern | +| Custom video message item view | Activity/Fragment | `setVideoMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern | +| Custom audio message item view | Activity/Fragment | `setAudioMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern | +| Custom document message item view | Activity/Fragment | `setDocumentMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern | +| Custom link message item view | Activity/Fragment | `setLinkMessageItemView(MessagesSearchViewHolderListener)` | See `setTextMessageItemView` pattern | +| Custom initial view | Activity/Fragment | `setInitialView(@LayoutRes int)` | `.setInitialView(R.layout.your_initial_view)` | +| Custom loading view | Activity/Fragment | `setLoadingView(View)` | `.setLoadingView(loadingView)` | +| Custom empty view | Activity/Fragment | `setEmptyView(@LayoutRes int)` | `.setEmptyView(R.layout.your_empty_view)` | +| Custom error view | Activity/Fragment | `setErrorView(View)` | `.setErrorView(errorView)` | +| Empty state visibility | Activity/Fragment | `setEmptyStateVisibility(int)` | `.setEmptyStateVisibility(View.GONE)` | +| Error state visibility | Activity/Fragment | `setErrorStateVisibility(int)` | `.setErrorStateVisibility(View.GONE)` | +| Change colors, fonts, spacing | `themes.xml` | `CometChatSearchStyle` | `#EDEAFA` | +| Apply a custom style | Activity/Fragment | `setStyle(int styleRes)` | `binding.cometchatSearch.setStyle(R.style.CustomSearchStyle)` | +| Search bar background | Activity/Fragment | `setSearchBarBackgroundColor` | `.setSearchBarBackgroundColor(color)` | +| Filter chip colors | Activity/Fragment | `setFilterChip*` methods | `.setFilterChipBackgroundColor(color)` | +| Section header style | Activity/Fragment | `setSectionHeader*` methods | `.setSectionHeaderTextColor(color)` | +| Conversation item style | Activity/Fragment | `setConversation*` methods | `.setConversationTitleTextColor(color)` | +| Message item style | Activity/Fragment | `setMessage*` methods | `.setMessageTitleTextColor(color)` | +| Date/time formatting | Activity/Fragment | `setDateTimeFormatter(DateTimeFormatterCallback)` | See `setDateTimeFormatter` code above | +| Text formatters | Activity/Fragment | `setTextFormatters(List)` | See Text Formatters section | +| Search bar hint text | Activity/Fragment | `setHintText(String)` | `.setHintText("Search...")` | +| Mention-all label | Activity/Fragment | `setMentionAllLabelId(String, String)` | `.setMentionAllLabelId(id, label)` | +| Callback on messages loaded | Activity/Fragment | `setOnLoadMessages(OnLoad)` | `.setOnLoadMessages { list -> ... }` | +| Callback on conversations loaded | Activity/Fragment | `setOnLoadConversations(OnLoad)` | `.setOnLoadConversations { list -> ... }` | + +## Next Steps + + + + Browse recent conversations + + + Browse and search available users + + + Browse and search available groups + + + Display messages in a conversation + + \ No newline at end of file diff --git a/ui-kit/angular/accessibility.mdx b/ui-kit/angular/accessibility.mdx new file mode 100644 index 000000000..2c004c1f5 --- /dev/null +++ b/ui-kit/angular/accessibility.mdx @@ -0,0 +1,80 @@ +--- +title: "Accessibility" +description: "Overview of accessibility support in the CometChat Angular UIKit, including WCAG compliance, keyboard navigation, and ARIA attributes." +--- + +The CometChat Angular UIKit is built with accessibility as a core principle. Components are designed targeting WCAG 2.1 Level AA guidelines, with the goal of making chat interfaces usable by everyone — including users who rely on keyboards, screen readers, or other assistive technologies. + + + Full WCAG compliance requires manual testing with assistive technologies and expert accessibility review. The UIKit implements the patterns and attributes described below, but you should validate your specific integration against your accessibility requirements. + + +Key accessibility features across the UIKit: + +- **WCAG 2.1 Level AA target** — Components are built following the Web Content Accessibility Guidelines for contrast, focus management, and semantic markup. +- **Keyboard navigation** — All interactive components support full keyboard operation using Tab, Enter, Space, Escape, and Arrow keys. Users can navigate, select, and interact without a mouse. +- **ARIA attributes** — Components use appropriate ARIA roles, labels, and states to communicate structure and behavior to screen readers. + +Each component that supports keyboard interaction documents its specific key bindings and focus behavior on its own page. The sections below link to those per-component keyboard accessibility references. + +## Components with Keyboard Accessibility + +### Conversations + +- [CometChatConversations](/ui-kit/angular/components/cometchat-conversations#keyboard-accessibility) +- [CometChatConversationItem](/ui-kit/angular/components/cometchat-conversation-item#keyboard-accessibility) + +### Users + +- [CometChatUsers](/ui-kit/angular/components/cometchat-users#keyboard-accessibility) +- [CometChatUserItem](/ui-kit/angular/components/cometchat-user-item#keyboard-accessibility) + +### Groups + +- [CometChatGroups](/ui-kit/angular/components/cometchat-groups#keyboard-accessibility) +- [CometChatGroupItem](/ui-kit/angular/components/cometchat-group-item#keyboard-accessibility) + +### Group Members + +- [CometChatGroupMembers](/ui-kit/angular/components/cometchat-group-members#keyboard-accessibility) +- [CometChatGroupMemberItem](/ui-kit/angular/components/cometchat-group-member-item#keyboard-accessibility) + +### Messages + +- [CometChatMessageHeader](/ui-kit/angular/components/cometchat-message-header#keyboard-accessibility) +- [CometChatMessageList](/ui-kit/angular/components/cometchat-message-list#keyboard-accessibility) +- [CometChatMessageComposer](/ui-kit/angular/components/cometchat-message-composer#keyboard-accessibility) +- [CometChatMessageBubble](/ui-kit/angular/components/cometchat-message-bubble#keyboard-accessibility) +- [CometChatMessageInformation](/ui-kit/angular/components/cometchat-message-information#keyboard-accessibility) +- [CometChatThreadHeader](/ui-kit/angular/components/cometchat-thread-header#keyboard-accessibility) + +### Message Bubbles + +- [CometChatTextBubble](/ui-kit/angular/components/cometchat-text-bubble#keyboard-accessibility) +- [CometChatImageBubble](/ui-kit/angular/components/cometchat-image-bubble#keyboard-accessibility) +- [CometChatVideoBubble](/ui-kit/angular/components/cometchat-video-bubble#keyboard-accessibility) +- [CometChatAudioBubble](/ui-kit/angular/components/cometchat-audio-bubble#keyboard-accessibility) +- [CometChatFileBubble](/ui-kit/angular/components/cometchat-file-bubble#keyboard-accessibility) +- [CometChatCallBubble](/ui-kit/angular/components/cometchat-call-bubble#keyboard-accessibility) +- [CometChatPollBubble](/ui-kit/angular/components/cometchat-poll-bubble#keyboard-accessibility) +- [CometChatCollaborativeDocumentBubble](/ui-kit/angular/components/cometchat-collaborative-document-bubble#keyboard-accessibility) +- [CometChatCollaborativeWhiteboardBubble](/ui-kit/angular/components/cometchat-collaborative-whiteboard-bubble#keyboard-accessibility) +- [CometChatStickersKeyboard](/ui-kit/angular/components/cometchat-stickers-keyboard#keyboard-accessibility) + +### Reactions + +- [CometChatReactions](/ui-kit/angular/components/cometchat-reactions#keyboard-accessibility) +- [CometChatReactionList](/ui-kit/angular/components/cometchat-reaction-list#keyboard-accessibility) +- [CometChatReactionInfo](/ui-kit/angular/components/cometchat-reaction-info#keyboard-accessibility) + +### Calls + +- [CometChatCallButtons](/ui-kit/angular/components/cometchat-call-buttons#keyboard-accessibility) +- [CometChatIncomingCall](/ui-kit/angular/components/cometchat-incoming-call#keyboard-accessibility) +- [CometChatOutgoingCall](/ui-kit/angular/components/cometchat-outgoing-call#keyboard-accessibility) +- [CometChatCallLogs](/ui-kit/angular/components/cometchat-call-logs#keyboard-accessibility) + +### AI Features + +- [CometChatSmartReplies](/ui-kit/angular/components/cometchat-smart-replies#keyboard-accessibility) +- [CometChatConversationStarter](/ui-kit/angular/components/cometchat-conversation-starter#keyboard-accessibility) diff --git a/ui-kit/angular/ai-features.mdx b/ui-kit/angular/ai-features.mdx index ed1f2838b..fd7f36aa2 100644 --- a/ui-kit/angular/ai-features.mdx +++ b/ui-kit/angular/ai-features.mdx @@ -1,60 +1,157 @@ --- -title: "AI" -description: "AI — CometChat documentation." +title: "AI Smart Chat Features" +description: "AI-powered features in CometChat's Angular UIKit: Conversation Starter, Smart Replies, and Conversation Summary." --- ## Overview -CometChat's AI capabilities greatly enhance user interaction and engagement in your application. Let's understand how the Angular UI Kit achieves these features. +CometChat AI Smart Chat Features enhance user interaction by providing contextual suggestions and summaries. Each feature must be enabled from the CometChat Dashboard first, then activated in your Angular components via input properties. - - - + +AI Smart Chat Features must be enabled from the [CometChat Dashboard](https://app.cometchat.com). Once activated in the dashboard, you enable them in your Angular components using the inputs described below. + -## Conversation Starters +## Smart Chat Features -When a user initiates a new chat, the UI kit displays a list of suggested opening lines that users can select, making it easier for them to start a conversation. These suggestions are powered by CometChat's AI, which predicts contextually relevant conversation starters. +### Conversation Starter -For a comprehensive understanding and guide on implementing and using the Conversation Starters, refer to our specific guide on the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter). +Displays AI-generated opening lines when a user starts a new or empty conversation. Helps break the ice by suggesting relevant topics. -Once you have successfully activated the [Conversation Starter](/fundamentals/ai-user-copilot/conversation-starter) from your CometChat Dashboard, the feature will automatically be incorporated into the [MessageList](/ui-kit/angular/message-list) Component of UI Kits. +Enable it on `cometchat-message-list`: - - - +```html + + +``` -## Smart Replies +Or using `ChatStateService` for shared state: -Smart Replies are AI-generated responses to messages. They can predict what a user might want to say next by analyzing the context of the conversation. This allows for quicker and more convenient responses, especially on mobile devices. +```typescript expandable +import { Component } from '@angular/core'; +import { ChatStateService } from '@cometchat/chat-uikit-angular'; +import { CometChatMessageListComponent } from '@cometchat/chat-uikit-angular'; -For a comprehensive understanding and guide on implementing and using the Smart Replies, refer to our specific guide on the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies). +@Component({ + selector: 'app-chat', + standalone: true, + imports: [CometChatMessageListComponent], + template: ` + + + ` +}) +export class ChatComponent { + constructor(private chatState: ChatStateService) {} -Once you have successfully activated the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/angular/message-composer) Component of UI Kits. + openChat(user: CometChat.User): void { + this.chatState.setActiveUser(user); + } +} +``` + +See [CometChatConversationStarter](/ui-kit/angular/components/cometchat-conversation-starter) for the standalone component docs. - + -## Conversation Summary +--- -The Conversation Summary feature provides concise summaries of long conversations, allowing users to catch up quickly on missed chats. This feature uses natural language processing to determine the main points in a conversation. +### Smart Replies -For a comprehensive understanding and guide on implementing and using the Conversation Summary, refer to our specific guide on the [Conversation Summary](/fundamentals/ai-user-copilot/conversation-summary). +AI-generated response suggestions based on the last received message. Users can tap a suggestion to send it instantly. -Once you have successfully activated the [Smart Replies](/fundamentals/ai-user-copilot/smart-replies) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/angular/message-composer) Component of UI Kits. +Enable it on `cometchat-message-list`: - - - +```html + + +``` -## AI Assist Bot +Smart replies appear above the message composer when a qualifying message is received. The component respects configurable trigger keywords and a delay before showing suggestions. -AI Assist Bots automate responses and prompt interaction in the chat. They can handle common queries, assist with tasks, and provide information, freeing up human resources for more complex issues. +See [CometChatSmartReplies](/ui-kit/angular/components/cometchat-smart-replies) for the standalone component docs. -For a comprehensive understanding and guide on implementing and using the AI Assist Bot, refer to our specific guide on the [AI Assist Bot](http://localhost:3000/docs-beta/ai/bots). + + + + +--- -Once you have successfully activated the [AI Assist Bot](http://localhost:3000/docs-beta/ai/bots) from your CometChat Dashboard, the feature will automatically be incorporated into the Action sheet of [MessageComposer](/ui-kit/angular/message-composer) Component of UI Kits. +### Conversation Summary + +AI-generated recap of long conversations. Useful for catching up on missed messages without scrolling through the entire thread. + +Enable it on `cometchat-message-header`: + +```html + + + +``` + +Full example combining the header with conversation starters and smart replies in the message list: + +```typescript expandable +import { Component } from '@angular/core'; +import { CometChat } from '@cometchat/chat-sdk-javascript'; +import { + CometChatMessageListComponent, + CometChatMessageHeaderComponent, + ChatStateService +} from '@cometchat/chat-uikit-angular'; + +@Component({ + selector: 'app-chat-view', + standalone: true, + imports: [CometChatMessageListComponent, CometChatMessageHeaderComponent], + template: ` + + + + + + ` +}) +export class ChatViewComponent { + constructor(private chatState: ChatStateService) {} + + openChat(user: CometChat.User): void { + this.chatState.setActiveUser(user); + } +} +``` + +See [CometChatConversationSummary](/ui-kit/angular/components/cometchat-conversation-summary) for the standalone component docs. - + + +--- + +## Next Steps + + + + Customize the message list where AI Smart Chat Features appear + + + Enable Conversation Summary in the header + + + Standalone Conversation Starter component + + + Standalone Smart Replies component + + diff --git a/ui-kit/angular/v5/angular-conversation.mdx b/ui-kit/angular/angular-conversation.mdx similarity index 95% rename from ui-kit/angular/v5/angular-conversation.mdx rename to ui-kit/angular/angular-conversation.mdx index 3a03d26a4..e28dc08fe 100644 --- a/ui-kit/angular/v5/angular-conversation.mdx +++ b/ui-kit/angular/angular-conversation.mdx @@ -12,14 +12,14 @@ description: "Build a two-panel conversation list + message view layout in Angul | Framework | Angular | | Components | `CometChatConversationsComponent`, `CometChatMessageHeaderComponent`, `CometChatMessageListComponent`, `CometChatMessageComposerComponent` | | Layout | Two-panel — conversation list (left) + message view (right) | -| Prerequisite | Complete [Angular Integration](/ui-kit/angular/v5/integration) Steps 1–5 first | +| Prerequisite | Complete [Angular Integration](/ui-kit/angular/integration) Steps 1–5 first | | Pattern | WhatsApp Web, Slack, Microsoft Teams | This guide builds a two-panel chat layout — conversation list on the left, messages on the right. Users tap a conversation to open it. -This assumes you've already completed [Angular Integration](/ui-kit/angular/v5/integration) (project created, UI Kit installed, init + login working, CSS imported). +This assumes you've already completed [Angular Integration](/ui-kit/angular/integration) (project created, UI Kit installed, init + login working, CSS imported). @@ -143,7 +143,7 @@ How it works: This is the recommended approach for most applications. For advanced use cases like multi-panel layouts where each panel needs independent state, you can pass `[user]` or `[group]` via `@Input()` bindings - to override the service. See the [State Management guide](/ui-kit/angular/v5/guides/state-management) for details. + to override the service. See the [State Management guide](/ui-kit/angular/guides/state-management) for details. --- @@ -161,16 +161,16 @@ You should see the conversation list on the left. Tap any conversation to load m ## Next Steps - + Customize colors, fonts, and styles to match your brand - + Browse all prebuilt UI components - + Back to the main setup guide - + Chat features included out of the box diff --git a/ui-kit/angular/v5/angular-one-to-one-chat.mdx b/ui-kit/angular/angular-one-to-one-chat.mdx similarity index 96% rename from ui-kit/angular/v5/angular-one-to-one-chat.mdx rename to ui-kit/angular/angular-one-to-one-chat.mdx index e3e1c225c..78b75bf8b 100644 --- a/ui-kit/angular/v5/angular-one-to-one-chat.mdx +++ b/ui-kit/angular/angular-one-to-one-chat.mdx @@ -12,14 +12,14 @@ description: "Build a focused one-to-one or group chat experience in Angular wit | Framework | Angular | | Components | `CometChatMessageHeaderComponent`, `CometChatMessageListComponent`, `CometChatMessageComposerComponent` | | Layout | Single chat window — no sidebar, no conversation list | -| Prerequisite | Complete [Angular Integration](/ui-kit/angular/v5/integration) Steps 1–5 first | +| Prerequisite | Complete [Angular Integration](/ui-kit/angular/integration) Steps 1–5 first | | Pattern | Support chat, embedded widgets, focused messaging |
This guide builds a single chat window — no sidebar, no conversation list. Users go directly into a one-to-one or group chat. Good for support chat, embedded widgets, or any focused messaging experience. -This assumes you've already completed [Angular Integration](/ui-kit/angular/v5/integration) (project created, UI Kit installed, init + login working, CSS imported). +This assumes you've already completed [Angular Integration](/ui-kit/angular/integration) (project created, UI Kit installed, init + login working, CSS imported). @@ -180,16 +180,16 @@ You should see the chat window load with the conversation for the UID you set. ## Next Steps - + Customize colors, fonts, and styles to match your brand - + Browse all prebuilt UI components - + Back to the main setup guide - + Chat features included out of the box diff --git a/ui-kit/angular/v5/angular-tab-based-chat.mdx b/ui-kit/angular/angular-tab-based-chat.mdx similarity index 96% rename from ui-kit/angular/v5/angular-tab-based-chat.mdx rename to ui-kit/angular/angular-tab-based-chat.mdx index 9ce3db465..cb1d10a8b 100644 --- a/ui-kit/angular/v5/angular-tab-based-chat.mdx +++ b/ui-kit/angular/angular-tab-based-chat.mdx @@ -12,14 +12,14 @@ description: "Build a tab-based messaging UI with chats, calls, users, and group | Framework | Angular | | Components | `CometChatConversationsComponent`, `CometChatCallLogsComponent`, `CometChatUsersComponent`, `CometChatMessageHeaderComponent`, `CometChatMessageListComponent`, `CometChatMessageComposerComponent` | | Layout | Tabbed sidebar (Chats, Calls, Users) + message view | -| Prerequisite | Complete [Angular Integration](/ui-kit/angular/v5/integration) Steps 1–5 first | +| Prerequisite | Complete [Angular Integration](/ui-kit/angular/integration) Steps 1–5 first | | Pattern | Full-featured messaging app with multiple sections | This guide builds a tabbed messaging UI — Chats, Calls, and Users tabs, with a message view. Good for full-featured apps that need more than just conversations. -This assumes you've already completed [Angular Integration](/ui-kit/angular/v5/integration) (project created, UI Kit installed, init + login working, CSS imported). +This assumes you've already completed [Angular Integration](/ui-kit/angular/integration) (project created, UI Kit installed, init + login working, CSS imported). @@ -218,16 +218,16 @@ You should see the tab bar at the top of the sidebar. Switch between Chats, Call ## Next Steps - + Customize colors, fonts, and styles to match your brand - + Browse all prebuilt UI components - + Back to the main setup guide - + Chat features included out of the box diff --git a/ui-kit/angular/v5/api-reference/chat-state-service.mdx b/ui-kit/angular/api-reference/chat-state-service.mdx similarity index 87% rename from ui-kit/angular/v5/api-reference/chat-state-service.mdx rename to ui-kit/angular/api-reference/chat-state-service.mdx index 97e219b0a..36681ba60 100644 --- a/ui-kit/angular/v5/api-reference/chat-state-service.mdx +++ b/ui-kit/angular/api-reference/chat-state-service.mdx @@ -300,18 +300,18 @@ The following Chat-Aware Components integrate with `ChatStateService`. Each supp | Component | Key Inputs | Service Integration | |-----------|-----------|---------------------| -| [CometChatConversations](/ui-kit/angular/v5/components/cometchat-conversations) | — | Calls `setActiveConversation()` when a conversation is selected | -| [CometChatMessageHeader](/ui-kit/angular/v5/components/cometchat-message-header) | `[user]`, `[group]` | Subscribes to `activeUser` / `activeGroup` | -| [CometChatMessageList](/ui-kit/angular/v5/components/cometchat-message-list) | `[user]`, `[group]` | Subscribes to `activeUser` / `activeGroup` | -| [CometChatMessageComposer](/ui-kit/angular/v5/components/cometchat-message-composer) | `[user]`, `[group]` | Subscribes to `activeUser` / `activeGroup` | -| [CometChatUsers](/ui-kit/angular/v5/components/cometchat-users) | — | Calls `setActiveUser()` when a user is selected | -| [CometChatGroups](/ui-kit/angular/v5/components/cometchat-groups) | — | Calls `setActiveGroup()` when a group is selected | -| [CometChatGroupMembers](/ui-kit/angular/v5/components/cometchat-group-members) | `[group]` | Subscribes to `activeGroup` | -| [CometChatThreadHeader](/ui-kit/angular/v5/components/cometchat-thread-header) | `[parentMessage]` | Receives parent message context from ChatStateService | +| [CometChatConversations](/ui-kit/angular/components/cometchat-conversations) | — | Calls `setActiveConversation()` when a conversation is selected | +| [CometChatMessageHeader](/ui-kit/angular/components/cometchat-message-header) | `[user]`, `[group]` | Subscribes to `activeUser` / `activeGroup` | +| [CometChatMessageList](/ui-kit/angular/components/cometchat-message-list) | `[user]`, `[group]` | Subscribes to `activeUser` / `activeGroup` | +| [CometChatMessageComposer](/ui-kit/angular/components/cometchat-message-composer) | `[user]`, `[group]` | Subscribes to `activeUser` / `activeGroup` | +| [CometChatUsers](/ui-kit/angular/components/cometchat-users) | — | Calls `setActiveUser()` when a user is selected | +| [CometChatGroups](/ui-kit/angular/components/cometchat-groups) | — | Calls `setActiveGroup()` when a group is selected | +| [CometChatGroupMembers](/ui-kit/angular/components/cometchat-group-members) | `[group]` | Subscribes to `activeGroup` | +| [CometChatThreadHeader](/ui-kit/angular/components/cometchat-thread-header) | `[parentMessage]` | Receives parent message context from ChatStateService | ## See Also -- [State Management Guide](/ui-kit/angular/v5/guides/state-management) — Hybrid Approach architecture and decision matrix -- [Service Reference](/ui-kit/angular/v5/api-reference/introduction) — Overview of all documented services -- [FormatterConfigService](/ui-kit/angular/v5/api-reference/formatter-config-service) — Text formatter configuration service -- [RichTextEditorService](/ui-kit/angular/v5/api-reference/rich-text-editor-service) — Rich text editor configuration service +- [State Management Guide](/ui-kit/angular/guides/state-management) — Hybrid Approach architecture and decision matrix +- [Service Reference](/ui-kit/angular/api-reference/introduction) — Overview of all documented services +- [FormatterConfigService](/ui-kit/angular/api-reference/formatter-config-service) — Text formatter configuration service +- [RichTextEditorService](/ui-kit/angular/api-reference/rich-text-editor-service) — Rich text editor configuration service diff --git a/ui-kit/angular/v5/api-reference/formatter-config-service.mdx b/ui-kit/angular/api-reference/formatter-config-service.mdx similarity index 98% rename from ui-kit/angular/v5/api-reference/formatter-config-service.mdx rename to ui-kit/angular/api-reference/formatter-config-service.mdx index 89582e4cf..a2cdc3eb6 100644 --- a/ui-kit/angular/v5/api-reference/formatter-config-service.mdx +++ b/ui-kit/angular/api-reference/formatter-config-service.mdx @@ -809,11 +809,11 @@ export class ThreadPanelComponent implements OnInit { Angular's hierarchical DI ensures the message list inside the wrapper resolves the local `FormatterConfigService` instance. The main chat panel continues to use the root singleton. -See [CometChatMessageList — Multiple Message Lists with Different Configurations](/ui-kit/angular/v5/components/cometchat-message-list#multiple-message-lists-with-different-configurations) for a complete multi-panel example. +See [CometChatMessageList — Multiple Message Lists with Different Configurations](/ui-kit/angular/components/cometchat-message-list#multiple-message-lists-with-different-configurations) for a complete multi-panel example. ## See Also - [CometChatTextBubble Component](../components/cometchat-text-bubble.mdx) - [CometChatMessageList Component](../components/cometchat-message-list.mdx) - [CometChatConversations Component](../components/cometchat-conversations.mdx) -- [Rich Text Formatting Guide](/ui-kit/angular/v5/guides/custom-text-formatter) +- [Rich Text Formatting Guide](/ui-kit/angular/guides/custom-text-formatter) diff --git a/ui-kit/angular/v5/api-reference/introduction.mdx b/ui-kit/angular/api-reference/introduction.mdx similarity index 88% rename from ui-kit/angular/v5/api-reference/introduction.mdx rename to ui-kit/angular/api-reference/introduction.mdx index 0614d66fe..4c1b21f41 100644 --- a/ui-kit/angular/v5/api-reference/introduction.mdx +++ b/ui-kit/angular/api-reference/introduction.mdx @@ -76,12 +76,12 @@ const uiKitSettings = new UIKitSettingsBuilder() | Service | Description | Reference | |---------|-------------|-----------| -| ChatStateService | Centralized chat state management service — tracks active user, group, and conversation across components | [ChatStateService](/ui-kit/angular/v5/api-reference/chat-state-service) | -| MessageBubbleConfigService | Centralized message bubble view configuration — customize bubble parts globally or per message type | [MessageBubbleConfigService](/ui-kit/angular/v5/api-reference/message-bubble-config-service) | -| CometChatTemplatesService | SDK-wide template customization service — shared and component-specific templates for all list components | [CometChatTemplatesService](/ui-kit/angular/v5/api-reference/templates-service) | -| FormatterConfigService | Text formatter configuration service — manages text formatting rules and custom formatters | [FormatterConfigService](/ui-kit/angular/v5/api-reference/formatter-config-service) | -| RichTextEditorService | Rich text editor configuration service — controls editor behavior, toolbar options, and input modes | [RichTextEditorService](/ui-kit/angular/v5/api-reference/rich-text-editor-service) | -| GlobalConfig | Centralized configuration via `COMETCHAT_GLOBAL_CONFIG` injection token — sets defaults for display, sound, calls, and more across all components | [GlobalConfig](/ui-kit/angular/v5/customization/global-config) | +| ChatStateService | Centralized chat state management service — tracks active user, group, and conversation across components | [ChatStateService](/ui-kit/angular/api-reference/chat-state-service) | +| MessageBubbleConfigService | Centralized message bubble view configuration — customize bubble parts globally or per message type | [MessageBubbleConfigService](/ui-kit/angular/api-reference/message-bubble-config-service) | +| CometChatTemplatesService | SDK-wide template customization service — shared and component-specific templates for all list components | [CometChatTemplatesService](/ui-kit/angular/api-reference/templates-service) | +| FormatterConfigService | Text formatter configuration service — manages text formatting rules and custom formatters | [FormatterConfigService](/ui-kit/angular/api-reference/formatter-config-service) | +| RichTextEditorService | Rich text editor configuration service — controls editor behavior, toolbar options, and input modes | [RichTextEditorService](/ui-kit/angular/api-reference/rich-text-editor-service) | +| GlobalConfig | Centralized configuration via `COMETCHAT_GLOBAL_CONFIG` injection token — sets defaults for display, sound, calls, and more across all components | [GlobalConfig](/ui-kit/angular/customization/global-config) | ### Service Scoping (Multiple Instances) @@ -98,7 +98,7 @@ If you need different configurations for different component instances (e.g., a export class ThreadPanelComponent { } ``` -See the [State Management Guide — Scoping Customization Services](/ui-kit/angular/v5/guides/state-management#scoping-customization-services-for-multiple-instances) and [CometChatMessageList — Multiple Message Lists](/ui-kit/angular/v5/components/cometchat-message-list#multiple-message-lists-with-different-configurations) for complete examples. +See the [State Management Guide — Scoping Customization Services](/ui-kit/angular/guides/state-management#scoping-customization-services-for-multiple-instances) and [CometChatMessageList — Multiple Message Lists](/ui-kit/angular/components/cometchat-message-list#multiple-message-lists-with-different-configurations) for complete examples. Do not scope `ChatStateService` — it is intentionally a singleton that tracks the app-wide active conversation. Use the props-based pattern (`[user]`, `[group]`) for independent panels instead. @@ -132,7 +132,7 @@ CometChatUserEvents.ccUserUnblocked.subscribe((user) => { }); ``` -See the full [Events reference](/ui-kit/angular/v5/events) for all available event names. +See the full [Events reference](/ui-kit/angular/events) for all available event names. ## Type Definitions diff --git a/ui-kit/angular/v5/api-reference/message-bubble-config-service.mdx b/ui-kit/angular/api-reference/message-bubble-config-service.mdx similarity index 93% rename from ui-kit/angular/v5/api-reference/message-bubble-config-service.mdx rename to ui-kit/angular/api-reference/message-bubble-config-service.mdx index be7fe2204..79111b0b7 100644 --- a/ui-kit/angular/v5/api-reference/message-bubble-config-service.mdx +++ b/ui-kit/angular/api-reference/message-bubble-config-service.mdx @@ -303,8 +303,8 @@ The main chat panel continues to use the root singleton, unaffected by the threa ## See Also -- [CometChatMessageList](/ui-kit/angular/v5/components/cometchat-message-list) — The primary consumer of this service -- [CometChatMessageBubble](/ui-kit/angular/v5/components/cometchat-message-bubble) — Individual bubble component -- [Custom Message Types](/ui-kit/angular/v5/components/cometchat-message-bubble) — Register templates for custom message types -- [State Management Guide — Scoping](/ui-kit/angular/v5/guides/state-management#scoping-customization-services-for-multiple-instances) — DI scoping patterns -- [API Reference Introduction](/ui-kit/angular/v5/api-reference/introduction) — Overview of all services +- [CometChatMessageList](/ui-kit/angular/components/cometchat-message-list) — The primary consumer of this service +- [CometChatMessageBubble](/ui-kit/angular/components/cometchat-message-bubble) — Individual bubble component +- [Custom Message Types](/ui-kit/angular/components/cometchat-message-bubble) — Register templates for custom message types +- [State Management Guide — Scoping](/ui-kit/angular/guides/state-management#scoping-customization-services-for-multiple-instances) — DI scoping patterns +- [API Reference Introduction](/ui-kit/angular/api-reference/introduction) — Overview of all services diff --git a/ui-kit/angular/v5/api-reference/rich-text-editor-service.mdx b/ui-kit/angular/api-reference/rich-text-editor-service.mdx similarity index 97% rename from ui-kit/angular/v5/api-reference/rich-text-editor-service.mdx rename to ui-kit/angular/api-reference/rich-text-editor-service.mdx index c803ca969..ebcb49dc5 100644 --- a/ui-kit/angular/v5/api-reference/rich-text-editor-service.mdx +++ b/ui-kit/angular/api-reference/rich-text-editor-service.mdx @@ -532,9 +532,9 @@ export class ThreadComposerComponent { } ``` -See [CometChatMessageList — Multiple Message Lists with Different Configurations](/ui-kit/angular/v5/components/cometchat-message-list#multiple-message-lists-with-different-configurations) for a complete multi-panel example. +See [CometChatMessageList — Multiple Message Lists with Different Configurations](/ui-kit/angular/components/cometchat-message-list#multiple-message-lists-with-different-configurations) for a complete multi-panel example. ## See Also -- [MessageComposer Component](/ui-kit/angular/v5/components/cometchat-message-composer) -- [Rich Text Formatting Guide](/ui-kit/angular/v5/guides/custom-text-formatter) +- [MessageComposer Component](/ui-kit/angular/components/cometchat-message-composer) +- [Rich Text Formatting Guide](/ui-kit/angular/guides/custom-text-formatter) diff --git a/ui-kit/angular/api-reference/search-conversations-service.mdx b/ui-kit/angular/api-reference/search-conversations-service.mdx new file mode 100644 index 000000000..540718d81 --- /dev/null +++ b/ui-kit/angular/api-reference/search-conversations-service.mdx @@ -0,0 +1,142 @@ +--- +title: Search Conversations Service +description: Signal-based service for conversation search state, SDK queries, pagination, and real-time listener management. +--- + +The `SearchConversationsService` manages conversation search state using Angular signals. It handles SDK query building, pagination, and attaches real-time listeners for message, user status, group, call, typing, and receipt events to keep results up to date. + +## Import + +```typescript +import { SearchConversationsService } from '@cometchat/chat-uikit-angular'; +``` + +## Signals (Reactive State) + +All state is exposed as Angular `WritableSignal` values. Components read these in templates or computed signals for automatic change detection. + +| Signal | Type | Default | Description | +|--------|------|---------|-------------| +| `conversations` | `WritableSignal` | `[]` | Current conversation search results | +| `fetchState` | `WritableSignal` | `States.loaded` | Current fetch state: `loading`, `loaded`, `empty`, or `error` | +| `hasMoreResults` | `WritableSignal` | `false` | Whether more pages of results are available | +| `typingIndicatorMap` | `WritableSignal>` | `new Map()` | Active typing indicators keyed by user UID or group GUID | + +## Methods + +### search() + +Initiates a conversation search. Resets state, validates criteria, builds the SDK request, and fetches the first page. + +```typescript +async search( + keyword: string, + filters: CometChatSearchFilter[], + customBuilder?: CometChat.ConversationsRequestBuilder +): Promise +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `keyword` | `string` | Search keyword. Empty string with no conversation filters results in `States.empty` | +| `filters` | `CometChatSearchFilter[]` | Active filters. `Unread` sets unread-only, `Groups` sets group conversation type | +| `customBuilder` | `ConversationsRequestBuilder` | Optional custom builder that overrides the default | + +The method sets `fetchState` to `loading` immediately, then to `loaded` (with results), `empty` (no results), or `error` (SDK failure). + +### loadMore() + +Fetches the next page of results and appends to the existing list. Deduplicates by conversation ID. + +```typescript +async loadMore(): Promise +``` + +### attachListeners() + +Attaches all real-time SDK listeners (message, user, group, call, typing, receipt). Call this after obtaining the logged-in user. + +```typescript +attachListeners(loggedInUser: CometChat.User): void +``` + +Listeners attached: +- **Message listener**: new text/media/custom messages, edits, deletes +- **User listener**: online/offline status changes +- **Group listener**: member joined/left/kicked/banned/added, scope changes +- **Call listener**: incoming/outgoing/accepted/rejected/cancelled calls +- **Typing listener**: typing started/ended indicators +- **Receipt listener**: delivered/read receipts (via `CometChatMessageEvents`) + +### detachListeners() + +Removes all SDK listeners and unsubscribes from receipt observables. + +```typescript +detachListeners(): void +``` + +### reset() + +Detaches listeners and resets all signals to their default values. + +```typescript +reset(): void +``` + +## Request Building + +The service builds a `CometChat.ConversationsRequest` based on the keyword and active filters: + +- Sets `setSearchKeyword()` when keyword is non-empty +- Sets `setUnread(true)` when the `Unread` filter is active +- Sets `setConversationType('group')` when the `Groups` filter is active +- Limit is 3 when no filters are active (preview mode), 30 when filters are active (full list mode) +- Custom builder overrides the default when provided + +## Real-Time Event Handling + +| Event | Behavior | +|-------|----------| +| New message received | Updates last message, increments unread count (if not from logged-in user), moves conversation to top | +| Message edited/deleted | Updates last message in the matching conversation | +| User online/offline | Updates the `conversationWith` user status | +| Typing started | Adds entry to `typingIndicatorMap` | +| Typing ended | Removes entry from `typingIndicatorMap` | +| Message delivered | Updates `deliveredAt` on the last message | +| Message read | Updates `readAt` on the last message, resets unread count to 0 | +| Group member left/kicked/banned (self) | Removes the conversation from results | +| Group member left/kicked/banned (other) | Treats as a new message (action message) | + +## Usage + +The service is typically used internally by `CometChatSearchConversationsListComponent`, but can be injected directly for custom implementations: + +```typescript expandable +import { Component, inject, effect } from '@angular/core'; +import { SearchConversationsService } from '@cometchat/chat-uikit-angular'; +import { CometChatSearchFilter, States } from '@cometchat/chat-uikit-angular'; + +@Component({ + selector: 'app-custom-search', + template: ` + @switch (service.fetchState()) { + @case (States.loading) {

Searching...

} + @case (States.empty) {

No conversations found

} + @case (States.loaded) { + @for (conv of service.conversations(); track conv.getConversationId()) { +
{{ conv.getConversationWith().getName() }}
+ } + } + } + ` +}) +export class CustomSearchComponent { + readonly service = inject(SearchConversationsService); + readonly States = States; + + search(keyword: string): void { + this.service.search(keyword, [CometChatSearchFilter.Unread]); + } +} +``` diff --git a/ui-kit/angular/api-reference/search-messages-service.mdx b/ui-kit/angular/api-reference/search-messages-service.mdx new file mode 100644 index 000000000..e87577f10 --- /dev/null +++ b/ui-kit/angular/api-reference/search-messages-service.mdx @@ -0,0 +1,131 @@ +--- +title: Search Messages Service +description: Signal-based service for message search state, SDK queries, attachment-type filtering, and pagination. +--- + +The `SearchMessagesService` manages message search state using Angular signals. It handles SDK query building with keyword, attachment-type, and user/group scoping, plus pagination for loading more results. + +## Import + +```typescript +import { SearchMessagesService } from '@cometchat/chat-uikit-angular'; +``` + +## Signals (Reactive State) + +| Signal | Type | Default | Description | +|--------|------|---------|-------------| +| `messages` | `WritableSignal` | `[]` | Current message search results (newest first after reversal) | +| `fetchState` | `WritableSignal` | `States.loaded` | Current fetch state: `loading`, `loaded`, `empty`, or `error` | +| `hasMoreResults` | `WritableSignal` | `false` | Whether more pages of results are available | + +## Methods + +### search() + +Initiates a message search. Resets state, validates criteria, builds the SDK request, and fetches the first page. + +```typescript +async search( + keyword: string, + filters: CometChatSearchFilter[], + uid?: string, + guid?: string, + customBuilder?: CometChat.MessagesRequestBuilder, + alwaysShowSeeMore?: boolean +): Promise +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `keyword` | `string` | Search keyword | +| `filters` | `CometChatSearchFilter[]` | Active filters that determine attachment type filtering | +| `uid` | `string` | Optional user UID to scope search to a specific user's messages | +| `guid` | `string` | Optional group GUID to scope search to a specific group's messages | +| `customBuilder` | `MessagesRequestBuilder` | Optional custom builder that overrides the default | +| `alwaysShowSeeMore` | `boolean` | When true, limits initial results to 3 (preview mode with "See more" button) | + +Validation: search requires at least one of: non-empty keyword, active message filter, uid, or guid. Otherwise `fetchState` is set to `States.empty`. + +### loadMore() + +Fetches the next page of results and appends to the existing list. + +```typescript +async loadMore(): Promise +``` + +### reset() + +Resets all signals to their default values and clears the internal request reference. + +```typescript +reset(): void +``` + +## Request Building + +The service builds a `CometChat.MessagesRequest` based on the search criteria: + +- `hideDeletedMessages(true)` — always excludes deleted messages +- `setSearchKeyword()` — when keyword is non-empty +- `setUID()` — when uid is provided (scoped to user) +- `setGUID()` — when guid is provided (scoped to group) +- `hasLinks(true)` — when the `Links` filter is active +- `setAttachmentTypes()` — maps filters to SDK attachment types: + +| Filter | SDK Attachment Type | +|--------|-------------------| +| `Photos` | `CometChat.AttachmentType.IMAGE` | +| `Videos` | `CometChat.AttachmentType.VIDEO` | +| `Documents` | `CometChat.AttachmentType.FILE` | +| `Audio` | `CometChat.AttachmentType.AUDIO` | + +- Limit is 3 when `alwaysShowSeeMore` is true (preview mode), 30 otherwise +- Results are reversed after fetch to show newest first + +## Usage + +The service is typically used internally by `CometChatSearchMessagesListComponent`, but can be injected directly: + +```typescript expandable +import { Component, inject } from '@angular/core'; +import { SearchMessagesService } from '@cometchat/chat-uikit-angular'; +import { CometChatSearchFilter, States } from '@cometchat/chat-uikit-angular'; + +@Component({ + selector: 'app-message-search', + template: ` + @if (service.fetchState() === States.loaded) { + @for (msg of service.messages(); track msg.getId()) { +
{{ msg.getSender()?.getName() }}: {{ msg.getType() }}
+ } + @if (service.hasMoreResults()) { + + } + } + ` +}) +export class MessageSearchComponent { + readonly service = inject(SearchMessagesService); + readonly States = States; + + searchPhotos(keyword: string): void { + this.service.search(keyword, [CometChatSearchFilter.Photos]); + } + + searchInGroup(keyword: string, guid: string): void { + this.service.search(keyword, [], undefined, guid); + } +} +``` + +## Differences from SearchConversationsService + +| Aspect | SearchConversationsService | SearchMessagesService | +|--------|--------------------------|---------------------| +| Real-time listeners | Yes (message, user, group, call, typing, receipt) | No | +| Scoping | Keyword + filters only | Keyword + filters + uid/guid | +| Attachment filtering | N/A | Photos, Videos, Documents, Audio, Links | +| Typing indicators | Yes (`typingIndicatorMap` signal) | No | +| Preview mode | 3 results when no filters | 3 results when `alwaysShowSeeMore` is true | diff --git a/ui-kit/angular/v5/api-reference/templates-service.mdx b/ui-kit/angular/api-reference/templates-service.mdx similarity index 100% rename from ui-kit/angular/v5/api-reference/templates-service.mdx rename to ui-kit/angular/api-reference/templates-service.mdx diff --git a/ui-kit/angular/call-features.mdx b/ui-kit/angular/call-features.mdx index 4c2cfe4e5..07c2b4f96 100644 --- a/ui-kit/angular/call-features.mdx +++ b/ui-kit/angular/call-features.mdx @@ -1,66 +1,109 @@ --- -title: "Call" -description: "Call — CometChat documentation." +title: "Call Features" +description: "Overview of CometChat's audio and video calling features including incoming calls, outgoing calls, and call logs — with the Angular UIKit components that power each feature." --- ## Overview -CometChat's Calls feature is an advanced functionality that allows you to seamlessly integrate one-on-one as well as group audio and video calling capabilities into your application. This document provides a technical overview of these features, as implemented in the Angular UI Kit. +CometChat Calls integrates 1:1 and group audio/video calling into the Angular UIKit. Install the Calls SDK and the UIKit auto-detects it, enabling call components. + + +Ensure `CometChatUIKit.init()` has completed and the user is logged in before using call features. + ## Integration -First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to our [Getting Started](/ui-kit/angular/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your Angular project. +Install the Calls SDK: -Once you've successfully integrated the UI Kit, the next step is to add the CometChat Calls SDK to your project. This is necessary to enable the calling features in the UI Kit. Here's how you do it: +```bash +npm install @cometchat/calls-sdk-javascript +``` -Add the SDK files to your project's dependencies or libraries: +Then enable calling in your `UIKitSettingsBuilder`: -```java -npm install @cometchat/calls-sdk-javascript +```typescript +const settings = new UIKitSettingsBuilder() + .setAppId('APP_ID') + .setRegion('REGION') + .setAuthKey('AUTH_KEY') + .setCallingEnabled(true) + .build(); ``` -After adding this dependency, the Angular UI Kit will automatically detect it and activate the calling features. Now, your application supports both audio and video calling. You will see [CallButtons](/ui-kit/angular/call-buttons) component rendered in [MessageHeader](/ui-kit/angular/message-header) Component. + + Both steps are required. Installing the Calls SDK alone is not enough — you must also call `.setCallingEnabled(true)` on the builder. Without it, call buttons remain hidden and the Calls SDK is not initialized. + - - - +When enabled, [cometchat-call-buttons](/ui-kit/angular/components/cometchat-call-buttons) renders in [cometchat-message-header](/ui-kit/angular/components/cometchat-message-header) and the trailing call button appears in [cometchat-call-logs](/ui-kit/angular/components/cometchat-call-logs). -## Features +### Custom Call App Settings -### Incoming Call +By default the UIKit builds `CallAppSettings` from your `appId` and `region`. If you need custom configuration (e.g. a different region for the Calls SDK or additional settings), pass your own `CallAppSettings`: -The [Incoming Call](/ui-kit/angular/incoming-call) component of the CometChat UI Kit provides the functionality that lets users receive real-time audio and video calls in the app. +```typescript +import { CometChatUIKitCalls } from '@cometchat/calls-sdk-javascript'; -When a call is made to a user, the Incoming Call component triggers and displays a call screen. This call screen typically displays the caller information and provides the user with options to either accept or reject the incoming call. +const callAppSettings = new CometChatUIKitCalls.CallAppSettingsBuilder() + .setAppId('APP_ID') + .setRegion('REGION') + .build(); + +const settings = new UIKitSettingsBuilder() + .setAppId('APP_ID') + .setRegion('REGION') + .setAuthKey('AUTH_KEY') + .setCallingEnabled(true) + .setCallAppSettings(callAppSettings) + .build(); +``` + + + `setCallAppSettings` is optional. When omitted, the UIKit automatically creates settings from the `appId` and `region` you already provided. + - + -### Outgoing Call +## Features -The [Outgoing Call](/ui-kit/angular/outgoing-call) component of the CometChat UI Kit is designed to manage the outgoing call process within your application. When a user initiates an audio or video call to another user or group, this component displays an outgoing call screen, showcasing information about the recipient and the call status. +### Incoming Call -Importantly, the Outgoing Call component is smartly designed to transition automatically into the ongoing call screen once the receiver accepts the call. This ensures a smooth flow from initiating the call to engaging in a conversation, without any additional steps required from the user. +The [cometchat-incoming-call](/ui-kit/angular/components/cometchat-incoming-call) component displays a call screen when a call is received, showing caller info with accept/reject options. - + -### Ongoing Call - -The [OngoingCall](/ui-kit/angular/ongoing-call) component is the user interface that displays during an ongoing call. For an audio call, this screen displays the participant's name, call duration, and buttons to mute the audio, enable or disable video, switch the camera, and end the call. +### Outgoing Call -For a video call, the Call Screen might additionally display the video footage from both the user's camera and the recipient's camera. +The [cometchat-outgoing-call](/ui-kit/angular/components/cometchat-outgoing-call) component displays an outgoing call screen with recipient info and call status. Transitions to the ongoing call screen when the receiver accepts. - + ### Call Logs -[Call Logs](/ui-kit/angular/call-logs) component provides you with the records call events such as who called who, the time of the call, and the duration of the call. This information can be fetched from the CometChat server and displayed in a structured format for users to view their past call activities. +The [cometchat-call-logs](/ui-kit/angular/components/cometchat-call-logs) component displays call history — caller, time, and duration. - + + +## Next Steps + + + + Audio and video call buttons + + + Incoming call notifications and UI + + + Call history and details + + + Core chat features + + diff --git a/ui-kit/angular/v5/components/cometchat-action-bubble.mdx b/ui-kit/angular/components/cometchat-action-bubble.mdx similarity index 100% rename from ui-kit/angular/v5/components/cometchat-action-bubble.mdx rename to ui-kit/angular/components/cometchat-action-bubble.mdx diff --git a/ui-kit/angular/components/cometchat-ai-assistant-chat.mdx b/ui-kit/angular/components/cometchat-ai-assistant-chat.mdx new file mode 100644 index 000000000..6eabdfe0a --- /dev/null +++ b/ui-kit/angular/components/cometchat-ai-assistant-chat.mdx @@ -0,0 +1,290 @@ +--- +title: "CometChatAIAssistantChat" +description: "Top-level orchestrator component for the AI assistant chat experience with real-time streaming, tool call dispatch, chat history, and suggestion pills." +--- + +## Overview + +`CometChatAIAssistantChat` is the top-level orchestrator for the AI assistant chat experience. It wires together `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer`, and the `CometChatAIAssistantChatHistory` sidebar into a single cohesive interface. + +Key capabilities: + +- **Real-time streaming** — integrates with `CometChatAIStreamingService` to display live AI responses token-by-token +- **Tool call dispatch** — registers `CometChatAIAssistantTools` handlers that the streaming service invokes automatically +- **Chat history sidebar** — browse and resume past AI conversations without losing context +- **Suggestion pills** — configurable quick-reply prompts sourced from explicit input or user metadata +- **Concurrent run support** — multiple AI responses can stream simultaneously without state corruption +- **Keyboard accessible** — full focus management including sidebar open/close focus trapping and restoration + + + + **Live Preview** — default AI assistant chat preview. + [Open in Storybook ↗](https://storybook.cometchat.io/angular/?path=/docs/components-ai-ai-assistant-chat--docs) + + + + +## Basic Usage + +```typescript +import { Component, OnInit } from '@angular/core'; +import { CometChat } from '@cometchat/chat-sdk-javascript'; +import { + CometChatAIAssistantChat, + CometChatAIStreamingService, +} from '@cometchat/chat-uikit-angular'; + +@Component({ + selector: 'app-ai-chat', + standalone: true, + imports: [CometChatAIAssistantChat], + template: ` + @if (agentUser) { + + } + `, +}) +export class AiChatComponent implements OnInit { + agentUser: CometChat.User | null = null; + + constructor(private streamingService: CometChatAIStreamingService) {} + + ngOnInit(): void { + CometChat.getUser('ai-agent-uid').then((user) => { + this.agentUser = user; + }); + + // Wire the CometChat SDK WebSocket to the streaming service + CometChat.addMessageListener( + 'ai-listener', + new CometChat.MessageListener({ + onAIAssistantMessageReceived: (event: CometChat.AIAssistantBaseEvent) => { + this.streamingService.handleWebsocketMessage(event, 'ai-agent-uid'); + }, + }) + ); + } +} +``` + +## Inputs + +| Input | Type | Default | Description | +|-------|------|---------|-------------| +| `user` | `CometChat.User` | required | The AI agent user to chat with | +| `streamingSpeed` | `number` | `30` | Per-token delay in milliseconds for the streaming animation | +| `aiAssistantTools` | `CometChatAIAssistantTools` | `undefined` | Tool handlers the AI can invoke during a conversation | +| `loadLastAgentConversation` | `boolean` | `false` | When `true`, automatically resumes the most recent conversation on load | +| `showSuggestedMessages` | `boolean` | `true` | Whether to show suggestion pills above the composer | +| `suggestedMessages` | `string[]` | `[]` | Explicit suggestion pill labels; falls back to `user.getMetadata().suggestedMessages` | +| `greetingTemplate` | `TemplateRef<{ $implicit: CometChat.User }>` | `undefined` | Custom greeting template rendered before the first message | + +## Events + +This component does not emit outputs directly — it manages all state internally and communicates with child components via signals and the `CometChatAIStreamingService`. + +## Advanced Usage + +### Registering Tool Handlers + +Use `CometChatAIAssistantTools` to register client-side functions the AI can call during a conversation. The streaming service dispatches them automatically when a `tool_call_end` event is received. + +```typescript +import { Component, OnInit } from '@angular/core'; +import { CometChat } from '@cometchat/chat-sdk-javascript'; +import { + CometChatAIAssistantChat, + CometChatAIAssistantTools, + CometChatAIStreamingService, +} from '@cometchat/chat-uikit-angular'; + +@Component({ + selector: 'app-ai-chat-with-tools', + standalone: true, + imports: [CometChatAIAssistantChat], + template: ` + @if (agentUser) { + + } + `, +}) +export class AiChatWithToolsComponent implements OnInit { + agentUser: CometChat.User | null = null; + + tools = new CometChatAIAssistantTools({ + get_weather: async (args: { city: string }) => { + const response = await fetch(`/api/weather?city=${args.city}`); + return response.json(); + }, + search_products: async (args: { query: string; limit?: number }) => { + const response = await fetch(`/api/products?q=${args.query}&limit=${args.limit ?? 5}`); + return response.json(); + }, + }); + + constructor(private streamingService: CometChatAIStreamingService) {} + + ngOnInit(): void { + CometChat.getUser('ai-agent-uid').then((user) => { + this.agentUser = user; + }); + + CometChat.addMessageListener( + 'ai-listener', + new CometChat.MessageListener({ + onAIAssistantMessageReceived: (event: CometChat.AIAssistantBaseEvent) => { + this.streamingService.handleWebsocketMessage(event, 'ai-agent-uid'); + }, + }) + ); + } +} +``` + +### Suggestion Pills + +Provide quick-reply prompts to guide users. If `suggestedMessages` is empty, the component falls back to `user.getMetadata().suggestedMessages`. + +```typescript +@Component({ + template: ` + @if (agentUser) { + + } + `, +}) +export class AiChatSuggestionsComponent { + agentUser: CometChat.User | null = null; + + suggestions = [ + 'What can you help me with?', + 'Show me recent orders', + 'How do I reset my password?', + ]; +} +``` + +### Custom Greeting Template + +Render a personalized greeting before the first message using the `greetingTemplate` input. The template context exposes the agent user as `$implicit`. + +```typescript +@Component({ + standalone: true, + imports: [CometChatAIAssistantChat], + template: ` + @if (agentUser) { + + } + + +
+

Hi, I'm {{ user.getName() }}

+

Ask me anything about your account or our products.

+
+
+ `, +}) +export class AiChatGreetingComponent { + agentUser: CometChat.User | null = null; +} +``` + +### Concurrent Runs + +The component supports multiple simultaneous AI responses. Each run streams independently — a slow tool call in one run does not block text streaming in another. This is handled automatically by `CometChatAIStreamingService` using per-run `concatMap` pipelines merged via `mergeMap`. + +```typescript +// Wire multiple agent users — each gets its own isolated streaming state +CometChat.addMessageListener( + 'ai-listener', + new CometChat.MessageListener({ + onAIAssistantMessageReceived: (event: CometChat.AIAssistantBaseEvent) => { + // chatId scopes the streaming state — use the agent's UID + const chatId = event.getReceiverId(); + this.streamingService.handleWebsocketMessage(event, chatId); + }, + }) +); +``` + +### Controlling Streaming Speed + +Adjust the per-token animation delay at runtime. The `streamingSpeed` input is synced to the service via an `effect()` — changes take effect immediately for all active and future runs. + +```typescript +@Component({ + template: ` + @if (agentUser) { + + } + + `, +}) +export class AiChatSpeedComponent { + agentUser: CometChat.User | null = null; + speedMs = 30; +} +``` + +## Customization + +### CSS Variables + +All visual properties are controlled via CSS variables. Override them in your global stylesheet or a scoped component style: + +```css +cometchat-ai-assistant-chat { + --cometchat-primary-color: #7c3aed; + --cometchat-background-color-01: #f9fafb; + --cometchat-text-color-primary: #111827; + --cometchat-radius-2: 12px; +} +``` + +### Localization Keys + +| Key | Default (en-us) | +|-----|-----------------| +| `ai_assistant_chat_intro_message` | "How can I help you today?" | +| `ai_assistant_chat_composer_placeholder` | "Ask me anything..." | +| `ai_assistant_chat_new_chat` | "New Chat" | +| `ai_assistant_chat_history_title` | "AI Assistant" | +| `ai_assistant_chat_thinking` | "Thinking..." | +| `ai_assistant_chat_executing_tool` | "Executing..." | +| `ai_assistant_chat_no_internet` | "No internet connection" | + +Override any key via `CometChatLocalize.updateKeys()`: + +```typescript +import { CometChatLocalize } from '@cometchat/chat-uikit-angular'; + +CometChatLocalize.updateKeys('en', { + ai_assistant_chat_intro_message: 'Hello! How can I assist you today?', + ai_assistant_chat_composer_placeholder: 'Type your question...', +}); +``` diff --git a/ui-kit/angular/v5/components/cometchat-audio-bubble.mdx b/ui-kit/angular/components/cometchat-audio-bubble.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-audio-bubble.mdx rename to ui-kit/angular/components/cometchat-audio-bubble.mdx index 1251e189a..54346bdd9 100644 --- a/ui-kit/angular/v5/components/cometchat-audio-bubble.mdx +++ b/ui-kit/angular/components/cometchat-audio-bubble.mdx @@ -668,6 +668,6 @@ Screen readers announce the audio bubble with: -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchataudiobubble). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchataudiobubble). diff --git a/ui-kit/angular/v5/components/cometchat-call-bubble.mdx b/ui-kit/angular/components/cometchat-call-bubble.mdx similarity index 100% rename from ui-kit/angular/v5/components/cometchat-call-bubble.mdx rename to ui-kit/angular/components/cometchat-call-bubble.mdx diff --git a/ui-kit/angular/v5/components/cometchat-call-buttons.mdx b/ui-kit/angular/components/cometchat-call-buttons.mdx similarity index 94% rename from ui-kit/angular/v5/components/cometchat-call-buttons.mdx rename to ui-kit/angular/components/cometchat-call-buttons.mdx index e3a6ffc16..a7d0f41fc 100644 --- a/ui-kit/angular/v5/components/cometchat-call-buttons.mdx +++ b/ui-kit/angular/components/cometchat-call-buttons.mdx @@ -73,7 +73,7 @@ export class CallButtonsDemoComponent { | `onError` | `((error: CometChat.CometChatException) => void) \| null` | `null` | Error callback invoked for any error during call operations. | | `outgoingCallDisableSoundForCalls` | `boolean` | `false` | Disables sound for the outgoing call overlay. Supports global config override. | | `outgoingCallCustomSoundForCalls` | `string` | `''` | Custom sound URL for the outgoing call overlay. Supports global config override. | -| `callSettingsBuilder` | `CallSettingsBuilder` | `undefined` | Custom `CallSettingsBuilder` to override the default call settings used in the ongoing call screen. Follows the three-tier priority: @Input > [GlobalConfig](/ui-kit/angular/v5/customization/global-config) > default. | +| `callSettingsBuilder` | `CallSettingsBuilder` | `undefined` | Custom `CallSettingsBuilder` to override the default call settings used in the ongoing call screen. Follows the three-tier priority: @Input > [GlobalConfig](/ui-kit/angular/customization/global-config) > default. | | `voiceCallButtonView` | `TemplateRef \| null` | `null` | Replaces the default voice call button with a custom template. | | `videoCallButtonView` | `TemplateRef \| null` | `null` | Replaces the default video call button with a custom template. | @@ -147,7 +147,7 @@ export class CustomCallSettingsComponent implements OnInit { ``` - You can also set `callSettingsBuilder` globally via [GlobalConfig](/ui-kit/angular/v5/customization/global-config) so all call components use the same settings without passing the input to each one. + You can also set `callSettingsBuilder` globally via [GlobalConfig](/ui-kit/angular/customization/global-config) so all call components use the same settings without passing the input to each one. ## Accessibility @@ -168,5 +168,5 @@ export class CustomCallSettingsComponent implements OnInit { ## Related Components - [CometChatOutgoingCall](./cometchat-outgoing-call.mdx) — Displayed automatically when a call is initiated -- [CometChatOngoingCall](/ui-kit/angular/v5/components/cometchat-outgoing-call) — Displayed automatically when a call is accepted +- [CometChatOngoingCall](/ui-kit/angular/components/cometchat-outgoing-call) — Displayed automatically when a call is accepted - [CometChatMessageHeader](./cometchat-message-header.mdx) — Typically hosts the call buttons diff --git a/ui-kit/angular/v5/components/cometchat-call-logs.mdx b/ui-kit/angular/components/cometchat-call-logs.mdx similarity index 98% rename from ui-kit/angular/v5/components/cometchat-call-logs.mdx rename to ui-kit/angular/components/cometchat-call-logs.mdx index a1db56c8b..822588078 100644 --- a/ui-kit/angular/v5/components/cometchat-call-logs.mdx +++ b/ui-kit/angular/components/cometchat-call-logs.mdx @@ -132,7 +132,7 @@ When `callButtonClicked` has no observers, clicking the trailing call button aut | `callLogRequestBuilder` | `any` | `null` | Custom `CallLogRequestBuilder` from `CometChatCalls`. When provided, overrides the default builder (limit 30, category "call"). | | `callInitiatedDateTimeFormat` | `CalendarObject \| null` | `null` | Custom date format for the call initiation timestamp. Merged with global and default `CalendarObject` formats (component-level wins). | | `showScrollbar` | `boolean` | `false` | Whether to show the scrollbar on the call logs list. | -| `callSettingsBuilder` | `CallSettingsBuilder` | `undefined` | Custom `CallSettingsBuilder` to override the default call settings used in the ongoing call overlay. Follows the three-tier priority: @Input > [GlobalConfig](/ui-kit/angular/v5/customization/global-config) > default. | +| `callSettingsBuilder` | `CallSettingsBuilder` | `undefined` | Custom `CallSettingsBuilder` to override the default call settings used in the ongoing call overlay. Follows the three-tier priority: @Input > [GlobalConfig](/ui-kit/angular/customization/global-config) > default. | | `onError` | `((error: CometChat.CometChatException) => void) \| null` | `null` | Error callback invoked when any error occurs during operations such as fetching call logs or initiating calls. | ### Template Properties @@ -333,7 +333,7 @@ export class CustomCallSettingsLogsComponent implements OnInit { ``` - You can also set `callSettingsBuilder` globally via [GlobalConfig](/ui-kit/angular/v5/customization/global-config) so all call components use the same settings without passing the input to each one. + You can also set `callSettingsBuilder` globally via [GlobalConfig](/ui-kit/angular/customization/global-config) so all call components use the same settings without passing the input to each one. ## Customization with Templates @@ -678,7 +678,7 @@ Errors are handled at two levels: When a fetch error occurs and no call logs have been loaded yet, the component transitions to the error state and displays the built-in error view (or your custom `errorView` template). -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatcalllogs). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatcalllogs). ## Related Components diff --git a/ui-kit/angular/v5/components/cometchat-collaborative-document-bubble.mdx b/ui-kit/angular/components/cometchat-collaborative-document-bubble.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-collaborative-document-bubble.mdx rename to ui-kit/angular/components/cometchat-collaborative-document-bubble.mdx index 405986c0a..5156c302e 100644 --- a/ui-kit/angular/v5/components/cometchat-collaborative-document-bubble.mdx +++ b/ui-kit/angular/components/cometchat-collaborative-document-bubble.mdx @@ -462,7 +462,7 @@ Screen readers announce the component with:
-For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatcollaborativedocumentbubble). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatcollaborativedocumentbubble). ## Related Components diff --git a/ui-kit/angular/v5/components/cometchat-collaborative-whiteboard-bubble.mdx b/ui-kit/angular/components/cometchat-collaborative-whiteboard-bubble.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-collaborative-whiteboard-bubble.mdx rename to ui-kit/angular/components/cometchat-collaborative-whiteboard-bubble.mdx index b39c7f278..b472ed46f 100644 --- a/ui-kit/angular/v5/components/cometchat-collaborative-whiteboard-bubble.mdx +++ b/ui-kit/angular/components/cometchat-collaborative-whiteboard-bubble.mdx @@ -462,7 +462,7 @@ Screen readers announce the component with:
-For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatcollaborativewhiteboardbubble). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatcollaborativewhiteboardbubble). ## Related Components diff --git a/ui-kit/angular/v5/components/cometchat-conversation-item.mdx b/ui-kit/angular/components/cometchat-conversation-item.mdx similarity index 100% rename from ui-kit/angular/v5/components/cometchat-conversation-item.mdx rename to ui-kit/angular/components/cometchat-conversation-item.mdx diff --git a/ui-kit/angular/v5/components/cometchat-conversation-starter.mdx b/ui-kit/angular/components/cometchat-conversation-starter.mdx similarity index 94% rename from ui-kit/angular/v5/components/cometchat-conversation-starter.mdx rename to ui-kit/angular/components/cometchat-conversation-starter.mdx index 9fdae5330..b2fb4ceda 100644 --- a/ui-kit/angular/v5/components/cometchat-conversation-starter.mdx +++ b/ui-kit/angular/components/cometchat-conversation-starter.mdx @@ -143,5 +143,5 @@ The Conversation Starter component uses BEM-style CSS classes that can be custom ## Related Components -- [CometChatSmartReplies](/ui-kit/angular/v5/components/cometchat-smart-replies) - AI-generated smart reply suggestions for received messages -- [CometChatMessageList](/ui-kit/angular/v5/components/cometchat-message-list) - Message list that hosts the conversation starter component +- [CometChatSmartReplies](/ui-kit/angular/components/cometchat-smart-replies) - AI-generated smart reply suggestions for received messages +- [CometChatMessageList](/ui-kit/angular/components/cometchat-message-list) - Message list that hosts the conversation starter component diff --git a/ui-kit/angular/v5/components/cometchat-conversation-summary.mdx b/ui-kit/angular/components/cometchat-conversation-summary.mdx similarity index 100% rename from ui-kit/angular/v5/components/cometchat-conversation-summary.mdx rename to ui-kit/angular/components/cometchat-conversation-summary.mdx diff --git a/ui-kit/angular/v5/components/cometchat-conversations.mdx b/ui-kit/angular/components/cometchat-conversations.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-conversations.mdx rename to ui-kit/angular/components/cometchat-conversations.mdx index 9aefd3879..b37a2775a 100644 --- a/ui-kit/angular/v5/components/cometchat-conversations.mdx +++ b/ui-kit/angular/components/cometchat-conversations.mdx @@ -1381,7 +1381,7 @@ Provide a custom error view with retry functionality: ``` -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatconversations). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatconversations). ## Best Practices diff --git a/ui-kit/angular/v5/components/cometchat-delete-bubble.mdx b/ui-kit/angular/components/cometchat-delete-bubble.mdx similarity index 100% rename from ui-kit/angular/v5/components/cometchat-delete-bubble.mdx rename to ui-kit/angular/components/cometchat-delete-bubble.mdx diff --git a/ui-kit/angular/v5/components/cometchat-file-bubble.mdx b/ui-kit/angular/components/cometchat-file-bubble.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-file-bubble.mdx rename to ui-kit/angular/components/cometchat-file-bubble.mdx index ad730fd8a..ea6881cee 100644 --- a/ui-kit/angular/v5/components/cometchat-file-bubble.mdx +++ b/ui-kit/angular/components/cometchat-file-bubble.mdx @@ -499,5 +499,5 @@ Screen readers announce the file bubble with: -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatfilebubble). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatfilebubble). diff --git a/ui-kit/angular/v5/components/cometchat-group-item.mdx b/ui-kit/angular/components/cometchat-group-item.mdx similarity index 96% rename from ui-kit/angular/v5/components/cometchat-group-item.mdx rename to ui-kit/angular/components/cometchat-group-item.mdx index 59ce61f32..567bc8c1d 100644 --- a/ui-kit/angular/v5/components/cometchat-group-item.mdx +++ b/ui-kit/angular/components/cometchat-group-item.mdx @@ -156,5 +156,5 @@ Provide custom templates via inputs to override any visual section: ## Related Components - [CometChatGroups](./cometchat-groups.mdx) — Parent list component that renders multiple group items -- [CometChatAvatar](/ui-kit/angular/v5/components/cometchat-users) — Used internally for the group avatar -- [CometChatContextMenu](/ui-kit/angular/v5/components/cometchat-message-list) — Used internally for the context menu +- [CometChatAvatar](/ui-kit/angular/components/cometchat-users) — Used internally for the group avatar +- [CometChatContextMenu](/ui-kit/angular/components/cometchat-message-list) — Used internally for the context menu diff --git a/ui-kit/angular/v5/components/cometchat-group-member-item.mdx b/ui-kit/angular/components/cometchat-group-member-item.mdx similarity index 97% rename from ui-kit/angular/v5/components/cometchat-group-member-item.mdx rename to ui-kit/angular/components/cometchat-group-member-item.mdx index 8990c7dac..31494049c 100644 --- a/ui-kit/angular/v5/components/cometchat-group-member-item.mdx +++ b/ui-kit/angular/components/cometchat-group-member-item.mdx @@ -186,7 +186,7 @@ getContextMenuOptions(member: CometChat.GroupMember): CometChatOption[] { ## Related Components - [CometChatGroupMembers](./cometchat-group-members.mdx) — Parent list component that renders multiple group member items -- [CometChatAvatar](/ui-kit/angular/v5/components/cometchat-users) — Used internally for the member avatar -- [CometChatContextMenu](/ui-kit/angular/v5/components/cometchat-message-list) — Used internally for the context menu +- [CometChatAvatar](/ui-kit/angular/components/cometchat-users) — Used internally for the member avatar +- [CometChatContextMenu](/ui-kit/angular/components/cometchat-message-list) — Used internally for the context menu - [CometChatUserItem](./cometchat-user-item.mdx) — Similar component for rendering user items - [CometChatGroupItem](./cometchat-group-item.mdx) — Similar component for rendering group items diff --git a/ui-kit/angular/v5/components/cometchat-group-members.mdx b/ui-kit/angular/components/cometchat-group-members.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-group-members.mdx rename to ui-kit/angular/components/cometchat-group-members.mdx index 10af28ae3..cecaf4b80 100644 --- a/ui-kit/angular/v5/components/cometchat-group-members.mdx +++ b/ui-kit/angular/components/cometchat-group-members.mdx @@ -175,7 +175,7 @@ export class GroupMembersServiceComponent { } ``` -See the [ChatStateService API reference](/ui-kit/angular/v5/api-reference/chat-state-service) for the full list of signals, observables, and setter methods. +See the [ChatStateService API reference](/ui-kit/angular/api-reference/chat-state-service) for the full list of signals, observables, and setter methods. This is the recommended approach for most applications. It reduces boilerplate @@ -772,7 +772,7 @@ handleError(error: CometChat.CometChatException): void { ``` -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatgroupmembers). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatgroupmembers). ## Best Practices diff --git a/ui-kit/angular/v5/components/cometchat-groups.mdx b/ui-kit/angular/components/cometchat-groups.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-groups.mdx rename to ui-kit/angular/components/cometchat-groups.mdx index 80ae60f48..f4877830d 100644 --- a/ui-kit/angular/v5/components/cometchat-groups.mdx +++ b/ui-kit/angular/components/cometchat-groups.mdx @@ -692,7 +692,7 @@ handleError(error: CometChat.CometChatException): void { ``` -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatgroups). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatgroups). ## Best Practices diff --git a/ui-kit/angular/v5/components/cometchat-image-bubble.mdx b/ui-kit/angular/components/cometchat-image-bubble.mdx similarity index 99% rename from ui-kit/angular/v5/components/cometchat-image-bubble.mdx rename to ui-kit/angular/components/cometchat-image-bubble.mdx index 36faf6f42..cfdef4cb4 100644 --- a/ui-kit/angular/v5/components/cometchat-image-bubble.mdx +++ b/ui-kit/angular/components/cometchat-image-bubble.mdx @@ -539,6 +539,6 @@ Screen readers announce the image bubble with: -For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/v5/troubleshooting#cometchatimagebubble). +For troubleshooting tips, see the [Troubleshooting Guide](/ui-kit/angular/troubleshooting#cometchatimagebubble). diff --git a/ui-kit/angular/v5/components/cometchat-incoming-call.mdx b/ui-kit/angular/components/cometchat-incoming-call.mdx similarity index 96% rename from ui-kit/angular/v5/components/cometchat-incoming-call.mdx rename to ui-kit/angular/components/cometchat-incoming-call.mdx index b86941740..15dbc27fd 100644 --- a/ui-kit/angular/v5/components/cometchat-incoming-call.mdx +++ b/ui-kit/angular/components/cometchat-incoming-call.mdx @@ -150,6 +150,6 @@ cometchat-incoming-call { ## Related Components -- [CometChatOngoingCall](/ui-kit/angular/v5/components/cometchat-outgoing-call) — Rendered automatically after accepting a call +- [CometChatOngoingCall](/ui-kit/angular/components/cometchat-outgoing-call) — Rendered automatically after accepting a call - [CometChatCallButtons](./cometchat-call-buttons.mdx) — Initiates outgoing calls -- [CometChatListItem](/ui-kit/angular/v5/components/cometchat-user-item) — Used internally to render the caller information +- [CometChatListItem](/ui-kit/angular/components/cometchat-user-item) — Used internally to render the caller information diff --git a/ui-kit/angular/components/cometchat-markdown-renderer.mdx b/ui-kit/angular/components/cometchat-markdown-renderer.mdx new file mode 100644 index 000000000..0d202021f --- /dev/null +++ b/ui-kit/angular/components/cometchat-markdown-renderer.mdx @@ -0,0 +1,250 @@ +--- +title: "CometChatMarkdownRenderer" +description: "Zero-dependency Angular component that parses and renders markdown to HTML with streaming support, XSS sanitization, and a copy button per code block." +--- + +## Overview + +`CometChatMarkdownRenderer` converts a markdown string to sanitized HTML using a custom TypeScript parser — no third-party markdown library is required. It is used internally by `CometChatAIAssistantMessageBubble` (completed messages) and `CometChatStreamMessageBubble` (live streaming), but can be used standalone anywhere you need markdown rendering. + +Key capabilities: + +- **Zero dependencies** — custom `CometChatMarkdownParser` class; no `marked`, `remark`, or `highlight.js` +- **Streaming-safe** — when `streaming` is `true`, incomplete syntax at the end of the text is rendered as plain text rather than dropped or throwing an error +- **XSS sanitization** — all raw HTML in the input is escaped before markdown rules are applied; only the supported markdown constructs produce HTML elements +- **Code block copy** — each fenced code block gets a copy button; state is tracked per-block as an independent `WritableSignal` +- **Image click** — clicking a rendered image emits `imageClick` with the image URL +- **Extensible parser** — `CometChatMarkdownParser` is exported from the public API so you can extend it with custom node types + +## Supported Markdown Constructs + +| Syntax | Output | +|--------|--------| +| `# Heading` through `###### Heading` | `

` – `

` | +| `**bold**` | `` | +| `_italic_` | `` | +| `~~strikethrough~~` | `` | +| `` `inline code` `` | `` | +| ` ```lang\ncode\n``` ` | `
` |
+| `> blockquote` | `
` | +| `1. item` | `
  1. ` | +| `- item` or `* item` | `