Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions sdk/javascript/additional-message-filtering.mdx
Original file line number Diff line number Diff line change
@@ -1,8 +1,42 @@
---
title: "Additional Message Filtering"
description: "Advanced filtering options for fetching messages using MessagesRequestBuilder in the CometChat JavaScript SDK."
---

{/* TL;DR for Agents and Quick Reference */}
<Info>
**Quick Reference for AI Agents & Developers**

```javascript
// Filter by category and type
let messagesRequest = new CometChat.MessagesRequestBuilder()
.setUID("UID")
.setCategories(["message"])
.setTypes(["image", "video", "audio", "file"])
.setLimit(50)
.build();

// Unread messages only
let messagesRequest = new CometChat.MessagesRequestBuilder()
.setUID("UID")
.setUnread(true)
.setLimit(50)
.build();

// Threaded messages
let messagesRequest = new CometChat.MessagesRequestBuilder()
.setUID("UID")
.setParentMessageId(parentId)
.setLimit(50)
.build();

// Fetch with pagination
messagesRequest.fetchPrevious().then(messages => { });
messagesRequest.fetchNext().then(messages => { });
```

**Key methods:** `setUID()`, `setGUID()`, `setLimit()`, `setCategories()`, `setTypes()`, `setTags()`, `setUnread()`, `setParentMessageId()`, `setMessageId()`, `setTimestamp()`, `hideReplies()`, `hideDeletedMessages()`
</Info>

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.

Expand Down Expand Up @@ -1474,3 +1508,39 @@ let GUID: string = "GUID",
</Tab>

</Tabs>

<Accordion title="Best Practices">
- **Combine filters strategically**: Use `setCategories()` with `setTypes()` for precise filtering
- **Set reasonable limits**: Use 30-50 messages per fetch for optimal performance
- **Use timestamps for sync**: `setUpdatedAfter()` helps sync local cache with server
- **Hide deleted messages in UI**: Use `hideDeletedMessages(true)` for cleaner message lists
- **Filter blocked users**: Use `hideMessagesFromBlockedUsers(true)` to respect user preferences
- **Reuse MessagesRequest**: Call `fetchPrevious()`/`fetchNext()` on the same object for pagination
</Accordion>

<Accordion title="Troubleshooting">
- **No messages returned** — Conflicting filters may cancel each other out. Simplify filters and add them one at a time to isolate the issue.
- **Missing message types** — Ensure the category matches the type (e.g., category `"message"` for type `"text"`).
- **Pagination not working** — Reuse the same `MessagesRequest` object for `fetchPrevious()` / `fetchNext()` calls. Creating a new object resets pagination.
- **Thread replies included** — Add `.hideReplies(true)` to exclude thread messages from the main conversation.
- **Deleted messages showing** — Add `.hideDeletedMessages(true)` to filter them out. This is not enabled by default.
</Accordion>

---

## Next Steps

<CardGroup cols={2}>
<Card title="Send Messages" icon="paper-plane" href="/sdk/javascript/send-message">
Send text, media, and custom messages
</Card>
<Card title="Receive Messages" icon="inbox" href="/sdk/javascript/receive-message">
Listen for incoming messages in real-time
</Card>
<Card title="Message Structure" icon="sitemap" href="/sdk/javascript/message-structure-and-hierarchy">
Understand message categories, types, and hierarchy
</Card>
<Card title="Threaded Messages" icon="comments" href="/sdk/javascript/threaded-messages">
Work with threaded conversations
</Card>
</CardGroup>
40 changes: 40 additions & 0 deletions sdk/javascript/advanced-overview.mdx
Original file line number Diff line number Diff line change
@@ -1,8 +1,48 @@
---
title: "Advanced"
sidebarTitle: "Overview"
description: "Advanced SDK features including connection management, real-time listeners, login listeners, and WebSocket configuration."
---

{/* TL;DR for Agents and Quick Reference */}
<Info>
**Quick Reference for AI Agents & Developers**

```javascript
// Check connection status
CometChat.getConnectionStatus(); // "connected" | "connecting" | "disconnected"

// Listen for connection changes
CometChat.addConnectionListener("LISTENER_ID", new CometChat.ConnectionListener({
onConnected: () => console.log("Connected"),
onDisconnected: () => console.log("Disconnected")
}));

// Listen for login events
CometChat.addLoginListener("LISTENER_ID", new CometChat.LoginListener({
onLoginSuccess: (user) => console.log("Logged in:", user),
onLogoutSuccess: () => console.log("Logged out")
}));
```
</Info>

This section helps you to know about the Connection Listeners.

---

## Next Steps

<CardGroup cols={2}>
<Card title="Connection Status" icon="signal" href="/sdk/javascript/connection-status">
Monitor and respond to connection state changes
</Card>
<Card title="WebSocket Management" icon="plug" href="/sdk/javascript/managing-web-sockets-connections-manually">
Manually manage WebSocket connections
</Card>
<Card title="Login Listener" icon="right-to-bracket" href="/sdk/javascript/login-listener">
Listen for login and logout events
</Card>
<Card title="All Real-Time Listeners" icon="tower-broadcast" href="/sdk/javascript/all-real-time-listeners">
Complete reference for all SDK listeners
</Card>
</CardGroup>
72 changes: 71 additions & 1 deletion sdk/javascript/ai-agents.mdx
Original file line number Diff line number Diff line change
@@ -1,7 +1,37 @@
---
title: "AI Agents"
description: "Integrate AI Agents into your app to enable intelligent, automated conversations with real-time streaming events and tool invocations."
---

{/* TL;DR for Agents and Quick Reference */}
<Info>
**Quick Reference for AI Agents & Developers**

```javascript
// Listen for real-time AI Agent events (streaming)
CometChat.addAIAssistantListener("LISTENER_ID", {
onAIAssistantEventReceived: (event) => console.log("Event:", event)
});

// Listen for persisted agentic messages
CometChat.addMessageListener("LISTENER_ID", {
onAIAssistantMessageReceived: (msg) => console.log("Assistant reply:", msg),
onAIToolResultReceived: (msg) => console.log("Tool result:", msg),
onAIToolArgumentsReceived: (msg) => console.log("Tool args:", msg)
});

// Cleanup
CometChat.removeAIAssistantListener("LISTENER_ID");
CometChat.removeMessageListener("LISTENER_ID");
```

**Event flow:** Run Start → Tool Call(s) → Text Message Stream → Run Finished
</Info>

<Note>
**Available via:** SDK | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com)
</Note>

# 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).
Expand Down Expand Up @@ -131,4 +161,44 @@ These events are received via the **`MessageListener`** after the run completes.
CometChat.removeMessageListener(listnerId);
```
</Tab>
</Tabs>
</Tabs>


<Warning>
Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
</Warning>

<Accordion title="Best Practices">
- **Register both listeners** — Use `AIAssistantListener` for real-time streaming events and `MessageListener` for persisted agentic messages. Both are needed for a complete experience.
- **Handle streaming progressively** — Use `Text Message Content` events to render the assistant's reply token-by-token for a responsive UI, rather than waiting for the full reply.
- **Track run lifecycle** — Use `Run Start` and `Run Finished` events to show loading indicators and know when the agent is done processing.
- **Remove listeners on cleanup** — Always call both `removeAIAssistantListener()` and `removeMessageListener()` when the component unmounts.
- **Handle tool calls gracefully** — Tool call events may occur multiple times in a single run. Display appropriate UI feedback for each tool invocation.
</Accordion>

<Accordion title="Troubleshooting">
- **No events received** — Ensure the AI Agent is configured in the CometChat Dashboard and the user is sending text messages (agents only respond to text).
- **`onAIAssistantEventReceived` not firing** — Verify the `AIAssistantListener` is registered after successful `CometChat.init()` and `login()`.
- **Agentic messages not arriving** — These come via `MessageListener` after the run completes. Make sure you've registered `onAIAssistantMessageReceived`, `onAIToolResultReceived`, and `onAIToolArgumentsReceived`.
- **Duplicate events** — Check that you're not registering multiple listeners with different IDs. Remove old listeners before adding new ones.
- **Streaming events arrive but no final message** — The run may have failed. Check for error events in the `onAIAssistantEventReceived` callback.
</Accordion>

---

## Next Steps

<CardGroup cols={2}>
<Card title="AI Chatbots" icon="robot" href="/ai-chatbots/overview">
Set up AI-powered chatbots for automated conversations
</Card>
<Card title="AI Moderation" icon="shield-check" href="/sdk/javascript/ai-moderation">
Automatically moderate messages with AI
</Card>
<Card title="AI User Copilot" icon="wand-magic-sparkles" href="/sdk/javascript/ai-user-copilot-overview">
AI-powered features like smart replies and conversation summaries
</Card>
<Card title="Send Messages" icon="paper-plane" href="/sdk/javascript/send-message">
Send text messages that trigger AI Agent responses
</Card>
</CardGroup>
65 changes: 64 additions & 1 deletion sdk/javascript/ai-moderation.mdx
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
---
title: "AI Moderation"
description: "Automatically moderate chat messages using AI to detect and block inappropriate content in real-time."
---

{/* TL;DR for Agents and Quick Reference */}
<Info>
**Quick Reference for AI Agents & Developers**

```javascript
// Send message — check moderation status
CometChat.sendMessage(textMessage).then(message => {
const status = message.getModerationStatus();
// CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED
});

// Listen for moderation results
CometChat.addMessageListener("MOD_LISTENER", new CometChat.MessageListener({
onMessageModerated: (message) => {
const status = message.getModerationStatus();
// Handle APPROVED or DISAPPROVED
}
}));
```

**Supported types:** Text, Image, Video messages only
**Statuses:** `PENDING` → `APPROVED` or `DISAPPROVED`
</Info>

<Note>
**Available via:** SDK | [REST API](https://api-explorer.cometchat.com) | [UI Kits](/ui-kit/react/overview) | [Dashboard](https://app.cometchat.com)
</Note>

## 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.
Expand Down Expand Up @@ -300,5 +329,39 @@ Here's a complete implementation showing the full moderation flow:
</Tab>
</Tabs>

<Warning>
Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
</Warning>

<Accordion title="Best Practices">
- **Show pending state in UI** — When `getModerationStatus()` returns `PENDING`, display a visual indicator (spinner, dimmed message) so users know the message is being reviewed.
- **Handle disapproved messages gracefully** — Don't just hide blocked messages silently. Show a placeholder or notification so the sender understands what happened.
- **Register the listener early** — Add the `onMessageModerated` listener before sending messages so you don't miss any moderation results.
- **Track pending messages** — Maintain a local map of pending message IDs so you can update the UI when moderation results arrive.
- **Test with moderation rules** — Configure moderation rules in the Dashboard before testing. Without rules, messages won't be moderated.
</Accordion>

<Accordion title="Troubleshooting">
- **`onMessageModerated` never fires** — Ensure moderation is enabled in the CometChat Dashboard and rules are configured under Moderation > Rules.
- **All messages show `PENDING` but never resolve** — Check that your moderation rules are properly configured and the moderation service is active in your plan.
- **Custom messages not being moderated** — AI Moderation only supports Text, Image, and Video messages. Custom messages are not subject to moderation.
- **Moderation status is `undefined`** — You may be using an older SDK version that doesn't support moderation. Update to the latest version.
- **Disapproved messages still visible to recipients** — The SDK handles this automatically. If recipients still see blocked messages, verify your `onMessageModerated` handler is updating the UI correctly.
</Accordion>

## Next Steps
After implementing AI Moderation, consider adding a reporting feature to allow users to flag messages they find inappropriate. For more details, see the [Flag Message](/sdk/javascript/flag-message) documentation.

<CardGroup cols={2}>
<Card title="Flag Message" icon="flag" href="/sdk/javascript/flag-message">
Allow users to report inappropriate messages manually
</Card>
<Card title="AI Agents" icon="robot" href="/sdk/javascript/ai-agents">
Build intelligent automated conversations with AI Agents
</Card>
<Card title="AI User Copilot" icon="wand-magic-sparkles" href="/sdk/javascript/ai-user-copilot-overview">
Smart replies, conversation summaries, and more
</Card>
<Card title="Send Messages" icon="paper-plane" href="/sdk/javascript/send-message">
Send text, media, and custom messages
</Card>
</CardGroup>
76 changes: 74 additions & 2 deletions sdk/javascript/all-real-time-listeners.mdx
Original file line number Diff line number Diff line change
@@ -1,8 +1,44 @@
---
title: "All Real Time Listeners"
description: "Complete reference for all CometChat real-time listeners including User, Group, Message, and Call listeners."
---

{/* TL;DR for Agents and Quick Reference */}
<Info>
**Quick Reference for AI Agents & Developers**

```javascript
// User Listener — online/offline presence
CometChat.addUserListener("ID", new CometChat.UserListener({
onUserOnline: (user) => { },
onUserOffline: (user) => { }
}));

// Message Listener — messages, typing, receipts, reactions
CometChat.addMessageListener("ID", new CometChat.MessageListener({
onTextMessageReceived: (msg) => { },
onMediaMessageReceived: (msg) => { },
onTypingStarted: (indicator) => { },
onMessagesRead: (receipt) => { }
}));

// Group Listener — member join/leave/kick/ban/scope changes
CometChat.addGroupListener("ID", new CometChat.GroupListener({ ... }));

// Call Listener — incoming/outgoing call events
CometChat.addCallListener("ID", new CometChat.CallListener({ ... }));

// Always clean up
CometChat.removeUserListener("ID");
CometChat.removeMessageListener("ID");
CometChat.removeGroupListener("ID");
CometChat.removeCallListener("ID");
```
</Info>

<Warning>
Always remove listeners when they're no longer needed (e.g., on component unmount or page navigation). Failing to remove listeners can cause memory leaks and duplicate event handling.
</Warning>

CometChat provides 4 listeners viz.

Expand All @@ -25,7 +61,7 @@ To add the `UserListener`, you need to use the `addUserListener()` method provid
<Tabs>
<Tab title="JavaScript">
```js
var listenerID = "UNIQUE_LISTENER_ID";
const listenerID = "UNIQUE_LISTENER_ID";
CometChat.addUserListener(
listenerID,
new CometChat.UserListener({
Expand All @@ -43,7 +79,7 @@ CometChat.addUserListener(

<Tab title="TypeScript">
```typescript
var listenerID: string = "UNIQUE_LISTENER_ID";
const listenerID: string = "UNIQUE_LISTENER_ID";
CometChat.addUserListener(
listenerID,
new CometChat.UserListener({
Expand Down Expand Up @@ -530,3 +566,39 @@ CometChat.removeCallListener(listenerID);
</Tab>

</Tabs>


<Accordion title="Best Practices">
- **Use unique listener IDs** — Each listener must have a unique ID. Using the same ID for multiple listeners will overwrite the previous one, causing missed events.
- **Register listeners early** — Add listeners right after `CometChat.init()` and `login()` succeed so you don't miss any events.
- **Always clean up** — Remove all listeners when they're no longer needed (component unmount, page navigation, logout) to prevent memory leaks and duplicate callbacks.
- **Keep listener callbacks lightweight** — Avoid heavy processing inside listener callbacks. Dispatch events to your state management layer and process asynchronously.
- **Use specific listeners** — Only register the listener types you need. Don't register a `GroupListener` if your page only handles messages.
</Accordion>

<Accordion title="Troubleshooting">
- **Events not firing** — Ensure listeners are registered after a successful `CometChat.init()` and `login()`. Listeners registered before init have no effect.
- **Duplicate events received** — You likely have multiple listeners registered with the same or different IDs. Check that you're removing old listeners before adding new ones.
- **Missing events after page navigation** — Listeners are removed when the component unmounts. Re-register them when the new component mounts.
- **`onMessagesDelivered` / `onMessagesRead` not triggering** — Delivery and read receipts must be explicitly sent by the recipient using `markAsDelivered()` / `markAsRead()`.
- **Call events not received** — Ensure you've registered a `CallListener` and that the CometChat Calling SDK is properly initialized.
</Accordion>

---

## Next Steps

<CardGroup cols={2}>
<Card title="Receive Messages" icon="inbox" href="/sdk/javascript/receive-message">
Handle incoming messages in real-time
</Card>
<Card title="Typing Indicators" icon="keyboard" href="/sdk/javascript/typing-indicators">
Show when users are typing
</Card>
<Card title="User Presence" icon="circle-dot" href="/sdk/javascript/user-presence">
Track online/offline status of users
</Card>
<Card title="Connection Status" icon="signal" href="/sdk/javascript/connection-status">
Monitor SDK connection state changes
</Card>
</CardGroup>
Loading