### Install Go SDK Source: https://getstream.io/chat/docs/go-golang.md Install the official Go SDK for Stream Chat using the go get command. ```go go get github.com/GetStream/getstream-go/v4 ``` -------------------------------- ### Start NGROK for Webhook Debugging Source: https://getstream.io/chat/docs/android/webhooks-overview.md Install and start NGROK to expose a local server to the internet, enabling inspection of incoming webhook requests. ```bash brew install ngrok ngrok http 8000 ``` -------------------------------- ### BenChat Setup Source: https://getstream.io/chat/docs/android/livestream-best-practices.md Install dependencies for BenChat, a load testing tool for Stream chat. Ensure Node.js is installed and use the specified version. ```bash # Requires Node.js (check .nvmrc for version) nvm use yarn install ``` -------------------------------- ### Get and Start Campaign Immediately (Python) Source: https://getstream.io/chat/docs/python/campaign-api.md Retrieve an existing campaign by its ID and start it immediately. Note that campaign creation and update are not yet available in the Python SDK. ```python # Get a campaign response = client.chat.get_campaign(id="") # Start a campaign immediately client.chat.start_campaign(id="") ``` -------------------------------- ### Complete Livestream Chat Setup Example Source: https://getstream.io/chat/docs/sdk/android/v6/client/guides/livestream-chat.md A comprehensive example combining message limiting, event buffering, skipping database storage, and fast event parsing for livestream channels. This configuration controls memory and disk usage for high-volume scenarios. ```kotlin // Configure state plugin with message limiting and event buffering val statePluginFactory = StreamStatePluginFactory( config = StatePluginConfig( messageLimitConfig = MessageLimitConfig( channelMessageLimits = setOf( ChannelMessageLimit(channelType = "livestream", baseLimit = 500), ), messageBufferConfig = MessageBufferConfig( channelTypes = setOf("livestream"), capacity = 100, overflow = MessageBufferOverflow.DROP_OLDEST, ), ), ), appContext = context, ) // Configure offline plugin to skip DB for livestream channels val offlinePluginFactory = StreamOfflinePluginFactory( appContext = context, ignoredChannelTypes = setOf("livestream"), ) // Build ChatClient with both plugins and fast event parsing enabled ChatClient.Builder(apiKey, context) .fastEventParsing(true) .withPlugins(statePluginFactory, offlinePluginFactory) .build() ``` -------------------------------- ### Quick Start: Single Agent Configuration Source: https://getstream.io/chat/docs/sdk/android/ai-integrations/stream-chat-ai-sdk.md Configure and start a single AI agent using the Stream Chat AI SDK. This example demonstrates setting up an agent with OpenAI, default tools, and custom client tools. ```typescript import { Agent, AgentPlatform, createDefaultTools, type ClientToolDefinition, } from "@stream-io/chat-ai-sdk"; const agent = new Agent({ userId: "ai-bot-weather", channelId: "support-room", channelType: "messaging", platform: AgentPlatform.OPENAI, model: "gpt-4o-mini", instructions: [ "Answer in a friendly, concise tone.", "Prefer Celsius unless the user specifies otherwise.", ], serverTools: createDefaultTools(), clientTools: [ { name: "openHelpCenter", description: "Open the help center in the web app", parameters: { type: "object", properties: { articleSlug: { type: "string" } }, required: ["articleSlug"], }, } satisfies ClientToolDefinition, ], mem0Context: { channelId: "support-room", appId: "stream-chat-support", }, }); await agent.start(); // Later... await agent.stop(); ``` -------------------------------- ### Manage Campaigns with Python SDK Source: https://getstream.io/chat/docs/dotnet-csharp/campaign-api.md Demonstrates how to get, start, stop, and query campaigns using the Python SDK. Campaign creation and update are noted as not yet available. ```python # Note: Campaign creation and update are not yet available in the getstream SDK. # Get a campaign response = client.chat.get_campaign(id="") # Start a campaign immediately client.chat.start_campaign(id="") # Or schedule a campaign to start at a later time import datetime client.chat.start_campaign( id="", # start campaign in 48 hours scheduled_for=datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=48), # automatically stop the campaign after 72 hours stop_at=datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=72), ) # Stop a campaign client.chat.stop_campaign(id="") # Query campaigns from getstream.models import SortParamRequest result = client.chat.query_campaigns( filter={"segments": {"$in": [""]}}, sort=[SortParamRequest(field="created_at", direction=-1)], limit=25, ) # result.data.campaigns is a list of campaigns # result.data.next is a cursor for the next page of results ``` -------------------------------- ### Install @op-engineering/op-sqlite and Pods Source: https://getstream.io/chat/docs/sdk/react-native/basics/offline-support.md Install the necessary dependency for offline support and run pod install for native module linking. ```bash yarn add @op-engineering/op-sqlite npx pod-install ``` -------------------------------- ### Initialize Stream Wrapper for Video and Chat Clients Source: https://getstream.io/chat/docs/sdk/ios/guides/video-integration.md Example of setting up the StreamWrapper to initialize and connect both the video and chat clients. Ensure you replace 'YOUR_API_KEY' and implement your token retrieval logic. ```swift let streamWrapper = StreamWrapper( apiKey: "YOUR_API_KEY", userCredentials: user, tokenProvider: { result in let token = \ Retrieve the token from your backend result(.success(token)) } ) ``` -------------------------------- ### Install React Navigation Dependencies (Expo) Source: https://getstream.io/chat/docs/sdk/react-native/basics/installation.md Install react-native-safe-area-context if you are using React Navigation and following the navigation setup guide with Expo. ```bash npx expo install react-native-safe-area-context ``` -------------------------------- ### Install React Navigation Dependencies (RN CLI) Source: https://getstream.io/chat/docs/sdk/react-native/basics/installation.md Install react-native-safe-area-context if you are using React Navigation and following the navigation setup guide with RN CLI. ```bash yarn add react-native-safe-area-context ``` -------------------------------- ### Go Example Source: https://getstream.io/chat/docs/go-golang/query-channels.md This Go example shows how to query channels using a predefined filter, suitable for production environments. It utilizes the GetStream Go SDK. ```Go // Production-ready: Use Predefined Filter resp, err := client.Chat().QueryChannels(ctx, &getstream.QueryChannelsRequest{ PredefinedFilter: getstream.PtrTo("user_messaging_channels"), FilterValues: map[string]any{ "user_id": userID, }, Sort: []getstream.SortParamRequest{{Field: getstream.PtrTo("last_message_at"), Direction: getstream.PtrTo(-1)}}, Limit: getstream.PtrTo(20), }) ``` -------------------------------- ### Campaign Started Webhook Event Source: https://getstream.io/chat/docs/unreal/campaign-api.md Example of a JSON payload received when a campaign starts. Includes campaign status and statistics. ```JSON { "type": "campaign.started", "campaign": { "status": "running", "stats": {...}, ... }, "created_at": "2024-23-02 00:00:00" } ``` -------------------------------- ### Stream CLI Example Command Source: https://getstream.io/chat/docs/android/cli-introduction.md Provides an example of how to use the Stream CLI to get a chat channel, specifying the type and ID. ```bash $ stream-cli chat get-channel -t messaging -i redteam ``` -------------------------------- ### App Initialization and Cleanup Source: https://getstream.io/chat/docs/sdk/react-native/v8/guides/push-notifications.md Initializes the application by requesting permissions, connecting the user, and registering the push token. Includes cleanup logic for disconnecting the user and unsubscribing token listeners on unmount. ```javascript const App = () => { const [isReady, setIsReady] = useState(false); const unsubscribeTokenRefreshListenerRef = useRef<() => void>(); useEffect(() => { // Register FCM token with stream chat server. const registerPushToken = async () => { if(!client) { return; } // unsubscribe any previous listener unsubscribeTokenRefreshListenerRef.current?.(); const token = await messaging().getToken(); const push_provider = 'firebase'; const push_provider_name = 'MyRNAppFirebasePush'; // name an alias for your push provider (optional) client.addDevice(token, push_provider, USER_ID, push_provider_name); await AsyncStorage.setItem('@current_push_token', token); const removeOldToken = async () => { const oldToken = await AsyncStorage.getItem('@current_push_token'); if (oldToken !== null) { await client.removeDevice(oldToken); await AsyncStorage.removeItem('@current_push_token'); } }; unsubscribeTokenRefreshListenerRef.current = messaging().onTokenRefresh(async newToken => { await Promise.all([ removeOldToken(), client.addDevice(newToken, push_provider, USER_ID, push_provider_name), AsyncStorage.setItem('@current_push_token', newToken), ]); }); }; const init = async () => { await requestPermission(); await client.connectUser({ id: USER_ID }, USER_TOKEN); await registerPushToken(); setIsReady(true); }; init(); return async () => { await client?.disconnectUser(); unsubscribeTokenRefreshListenerRef.current?.(); }; }, []); if (!isReady) { return null; } return ( {/* Child components of Chat go here */} ); }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, }); ``` -------------------------------- ### Importing Standard Library Packages Source: https://getstream.io/chat/docs/go-golang/import.md Demonstrates how to import packages from Go's standard library. Ensure the package name is correct. ```go import ( "fmt" "net/http" ) ``` -------------------------------- ### Stream CLI Help Command Examples Source: https://getstream.io/chat/docs/android/cli-introduction.md Demonstrates how to access help information for the Stream CLI at different levels: global, service-specific, and command-specific. ```bash $ stream-cli --help $ stream-cli chat --help $ stream-cli chat get-channel --help ``` -------------------------------- ### Starting a Campaign (Python) Source: https://getstream.io/chat/docs/java/campaign-api.md This snippet demonstrates how to start sending messages for an existing campaign using the Python SDK. ```APIDOC ## Starting a Campaign This section describes how to start sending messages for an existing campaign using the Python SDK. ### Method POST (Implicit, via SDK method `start_campaign()`) ### Endpoint Not directly exposed as an HTTP endpoint; managed via SDK methods. ### Parameters #### `start_campaign(id)` - **id** (string) - Required - The ID of the campaign to start. ### Request Example ```python client.chat.start_campaign(id="") ``` ### Response #### Success Response - Initiates the campaign sending process. Specific response body details are not provided in the source. #### Response Example (No specific response body examples provided in source.) ``` -------------------------------- ### Install Optional Dependencies with Expo Source: https://getstream.io/chat/docs/sdk/react-native/v8/basics/installation.md Install various optional dependencies for enhanced functionality when using Expo. Ensure you follow each dependency's specific setup instructions. ```bash npx expo install expo-av expo-video expo-file-system expo-media-library expo-sharing expo-haptics expo-clipboard expo-document-picker expo-image-picker @op-engineering/op-sqlite ``` -------------------------------- ### Setup ChatClient Singleton Source: https://getstream.io/chat/docs/sdk/ios/uikit/getting-started.md Instantiate the ChatClient using a singleton pattern for application-wide use. Ensure you replace the placeholder with your actual API Key. ```swift extension ChatClient { static let shared: ChatClient = { // You can grab your API Key from https://getstream.io/dashboard/ let config = ChatClientConfig(apiKeyString: "<# Your API Key Here #>") // Create an instance of the `ChatClient` with the given config let client = ChatClient(config: config) return client }() } ``` -------------------------------- ### Install Optional Dependencies with RN CLI Source: https://getstream.io/chat/docs/sdk/react-native/v8/basics/installation.md Install various optional dependencies for enhanced functionality when using the React Native CLI. Ensure you follow each dependency's specific setup instructions. ```bash yarn add @react-native-camera-roll/camera-roll react-native-video react-native-audio-recorder-player react-native-blob-util react-native-share react-native-haptic-feedback @react-native-clipboard/clipboard @react-native-documents/picker react-native-image-picker @op-engineering/op-sqlite ``` -------------------------------- ### v7 ChatTheme Initialization Source: https://getstream.io/chat/docs/sdk/android/migration-guides/migrating-from-v6-to-v7.md Example of initializing `ChatTheme` in v7, demonstrating the new structure with `ChatUiConfig` and other parameters. ```kotlin ChatTheme( isInDarkMode = isSystemInDarkTheme(), colors = StreamDesign.Colors.default(), typography = StreamDesign.Typography.default(), config = ChatUiConfig(), componentFactory = object : ChatComponentFactory {}, reactionResolver = ReactionResolver.defaultResolver(), ) { content() } ``` -------------------------------- ### Manage Campaign Lifecycle (JavaScript) Source: https://getstream.io/chat/docs/python/campaign-api.md Perform create, get, update, start, stop, and delete operations on a campaign. Use the start method with optional scheduledFor and stopAt parameters to control campaign timing. ```javascript await campaign.create(); // create a campaign based on data passed above await campaign.get(); // check the status of the campaign await campaign.update({ segment_ids: ["a869fc0f-2e7e-4fe0-8651-775c892c1718"], sender_id: "Updated-user-id-of-sender", // mandatory sender_mode: "include", // optional sender_visibility: "archived", // optional name: "Updated name (optional)", message_template: { text: "Updated Hello {{receiver.name}}!", }, }); // updates the campaign data // You can start a campaign immediately, which will start sending messages to the users in the segment(s) immediately. await campaign.start(); // Or you can schedule a campaign to start at a later time. await campaign.start({ // start campaign in 48 hours scheduledFor: new Date(Date.now() + 48 * 60 * 60 * 1000).toISOString(), // optional, campaign will start running after this time // automatically stop the campaign after 72 hours stopAt: new Date(Date.now() + 72 * 60 * 60 * 1000).toISOString(), // optional, campaign will stop running after this time }); await campaign.stop(); // stops the campaign await campaign.delete(); // delete the campaign ``` -------------------------------- ### Quick Start: Single Agent with Tools Source: https://getstream.io/chat/docs/sdk/android/ai-integrations/stream-chat-langchain-sdk.md Instantiate an Agent with user, channel, platform, model, instructions, and default/custom tools. Includes optional Mem0 context for memory persistence. Ensure environment variables for API keys are set. ```typescript import { Agent, AgentPlatform, createDefaultTools, type ClientToolDefinition, } from "@stream-io/chat-langchain-sdk"; const agent = new Agent({ userId: "ai-bot-weather", channelId: "support-room", channelType: "messaging", platform: AgentPlatform.OPENAI, model: "gpt-4o-mini", instructions: [ "Answer in a friendly, concise tone.", "Prefer Celsius unless the user specifies otherwise.", ], serverTools: createDefaultTools(), clientTools: [ { name: "openHelpCenter", description: "Open the help center in the web app", parameters: { type: "object", properties: { articleSlug: { type: "string" } }, required: ["articleSlug"], }, } satisfies ClientToolDefinition, ], mem0Context: { channelId: "support-room", appId: "stream-chat-support", }, }); await agent.start(); // Later... await agent.stop(); ``` -------------------------------- ### Get Replies More Source: https://getstream.io/chat/docs/java/threads.md Fetches older replies for a given parent message, starting from a specific message ID. ```APIDOC ## Get Replies More ### Description Fetches older replies for a given parent message, starting from a specific message ID. ### Method This is a client-side SDK method, not an HTTP endpoint. ### Parameters #### Path Parameters None #### Query Parameters - **messageId** (string) - Required - The ID of the parent message. - **firstId** (string) - Required - The ID of the message to fetch replies before. - **limit** (integer) - Optional - The maximum number of replies to return. ### Request Example ```kotlin // Get 20 more replies before message with ID "42" client.getRepliesMore( messageId = parentMessage.id, firstId = "42", limit = 20, ).enqueue { /* ... */ } ``` ### Response #### Success Response (200) - **replies** (array of Message objects) - A list of message objects representing the thread replies. ``` -------------------------------- ### Campaign Management Source: https://getstream.io/chat/docs/go-golang/campaign-api.md Provides methods to create, get, update, start, stop, delete, and query campaigns. ```APIDOC ## Campaign Methods ### Create Campaign - **Description**: Creates a new campaign. - **Method**: Not explicitly defined in source, implied by `campaign.create()`. - **Endpoint**: Not explicitly defined in source. ### Get Campaign - **Description**: Retrieves the status or details of a specific campaign. - **Method**: Not explicitly defined in source, implied by `campaign.get()` or `client.chat.get_campaign()`. - **Endpoint**: Not explicitly defined in source. - **Parameters**: - **Path Parameters**: - `id` (string) - Required - The unique identifier of the campaign. ### Update Campaign - **Description**: Updates an existing campaign's configuration. - **Method**: Not explicitly defined in source, implied by `campaign.update()`. - **Endpoint**: Not explicitly defined in source. - **Parameters**: - **Request Body**: - `segment_ids` (array of strings) - Required - List of segment IDs to associate with the campaign. - `sender_id` (string) - Mandatory - The user ID of the sender. - `sender_mode` (string) - Optional - Mode for sender visibility (e.g., 'include'). - `sender_visibility` (string) - Optional - Visibility setting for the sender (e.g., 'archived'). - `name` (string) - Optional - The updated name of the campaign. - `message_template` (object) - Optional - The updated message template. - `text` (string) - The text content of the message template. ### Start Campaign - **Description**: Starts a campaign, either immediately or at a scheduled time. - **Method**: Not explicitly defined in source, implied by `campaign.start()` or `client.chat.start_campaign()`. - **Endpoint**: Not explicitly defined in source. - **Parameters**: - **Request Body** (for scheduling): - `scheduledFor` (string/datetime) - Optional - The time when the campaign should start. If not provided, starts immediately. - `stopAt` (string/datetime) - Optional - The time when the campaign should automatically stop. ### Stop Campaign - **Description**: Stops an ongoing campaign. - **Method**: Not explicitly defined in source, implied by `campaign.stop()` or `client.chat.stop_campaign()`. - **Endpoint**: Not explicitly defined in source. - **Parameters**: - **Path Parameters**: - `id` (string) - Required - The unique identifier of the campaign to stop. ### Delete Campaign - **Description**: Deletes a campaign. - **Method**: Not explicitly defined in source, implied by `campaign.delete()`. - **Endpoint**: Not explicitly defined in source. ### Query Campaigns - **Description**: Queries campaigns based on specified filters, sorting, and pagination options. - **Method**: Not explicitly defined in source, implied by `client.queryCampaigns()` or `client.chat.query_campaigns()`. - **Endpoint**: Not explicitly defined in source. - **Parameters**: - **Filter Object**: - `segments` (object) - Filters campaigns by segment IDs. - `$in` (array of strings) - Array of segment IDs to filter by. - **Sort Object**: - `field` (string) - The field to sort by (e.g., 'created_at'). - `direction` (integer) - The sort direction (-1 for descending, 1 for ascending). - **Options Object**: - `limit` (integer) - The maximum number of campaigns to return. - `next` (string) - A cursor for fetching the next page of results. ``` -------------------------------- ### Create and Apply Blocklist (Python) Source: https://getstream.io/chat/docs/unity/moderation.md Use this Python example to create a blocklist with a set of words and then update a channel type to enforce this blocklist. ```python client.create_block_list(name="no-cakes", words=["fudge", "cream", "sugar"]) # use the blocklist for all channels of type messaging client.chat.update_channel_type( name="messaging", automod="disabled", automod_behavior="flag", max_message_length=5000, blocklist="no-cakes", blocklist_behavior="block", ) ``` -------------------------------- ### Set MessageComposer Setup Function Source: https://getstream.io/chat/docs/sdk/react-native/ui-components/message-composer/composer/message-composer.md Set a single MessageComposer setup function per client to manage middleware registration. This example shows conditional middleware insertion based on context type and emoji enablement. ```tsx import { defaultTextComposerMiddlewares } from "stream-chat"; const chatClient = useCreateChatClient({ apiKey, tokenOrProvider: userToken, userData: { id: userId, language: "en" }, }); const [emojisEnabled, setEmojisEnabled] = useState(false); useEffect(() => { chatClient.setMessageComposerSetupFunction(({ composer }) => { if (composer.contextType === "channel") { composer.textComposer.insert( defaultTextComposerMiddlewares.map(composer.channel), ); if (emojisEnabled) { composer.textComposer.middlewareExecutor.insert({ middleware: [ createTextComposerEmojiMiddleware( SearchIndex, ) as TextComposerMiddleware, ], position: { after: "stream-io/text-composer/mentions-middleware" }, unique: true, }); } } }); }, [chatClient, emojisEnabled]); ``` -------------------------------- ### Get, Start, Stop, and Query Campaigns (Python) Source: https://getstream.io/chat/docs/go-golang/campaign-api.md Interact with campaigns using the Python SDK. Retrieve campaign details, start campaigns immediately or with scheduling, stop active campaigns, and query campaigns based on filters and sorting. ```python # Get a campaign response = client.chat.get_campaign(id="") # Start a campaign immediately client.chat.start_campaign(id="") # Stop a campaign client.chat.stop_campaign(id="") # Query campaigns from getstream.models import SortParamRequest result = client.chat.query_campaigns( filter={"segments": {"$in": [""]}}, sort=[SortParamRequest(field="created_at", direction=-1)], limit=25, ) # result.data.campaigns is a list of campaigns # result.data.next is a cursor for the next page of results ``` -------------------------------- ### GreetClientTool Implementation Source: https://getstream.io/chat/docs/sdk/ios/ai-integrations/client-side-tools.md An example implementation of the `ClientTool` protocol. This tool displays a native greeting alert to the user when invoked. ```swift @MainActor final class GreetClientTool: ClientTool { let toolDefinition: Tool = { let schema: Value = .object([ "type": .string("object"), "properties": .object([:]), "required": .array([]), "additionalProperties": .bool(false) ]) return Tool( name: "greetUser", description: "Display a native greeting to the user", inputSchema: schema, annotations: .init(title: "Greet user") ) }() let instructions = "Use the greetUser tool when the user asks to be greeted. The tool shows a greeting alert in the iOS app." let showExternalSourcesIndicator = false func handleInvocation(_ invocation: ClientToolInvocation) -> [ClientToolAction] { [ { ClientToolActionHandler.shared.presentAlert( ClientToolAlert( title: "Greetings!", message: "👋 Hello there! The assistant asked me to greet you." ) ) } ] } } ``` -------------------------------- ### Initialize Go Client from Environment Variables Source: https://getstream.io/chat/docs/go-golang.md Initialize the Stream Chat client by loading credentials from environment variables STREAM_API_KEY and STREAM_API_SECRET. ```go client, err := getstream.NewClientFromEnvVars() ``` -------------------------------- ### Filter for Channels with Autocomplete on Name Source: https://getstream.io/chat/docs/sdk/ios/swiftui/channel-list-components/query-filters.md Example of using an autocomplete filter to find channels whose names start with a specific text. ```swift // Filter for channels where the name starts with "Group" let filter = Filter.autocomplete(.name, text: "Group") ``` -------------------------------- ### Get Campaign Stats Source: https://getstream.io/chat/docs/ios-swift/campaign-api.md Retrieves statistics associated with a campaign, including start and end times, messages sent, and user engagement. ```APIDOC ## Get Campaign Stats ### Description Retrieves statistics associated with a campaign, including start and end times, messages sent, and user engagement. ### Method GET (implied by SDK methods) ### Endpoint Not explicitly defined, SDK methods are provided. ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the campaign. ### Request Example ```javascript // await campaign.get() ``` ```python res = client.chat.get_campaign(id="") ``` ### Response #### Success Response - **stats** (object) - An object containing campaign statistics. - **started_at** (string) - The timestamp when the campaign started. - **completed_at** (string) - The timestamp when the campaign completed. - **messages_sent** (integer) - The total number of messages sent. - **channels_created** (integer) - The number of channels created for the campaign. - **stats_progress** (float) - The progress of the campaign sending. - **stats_users_sent** (integer) - The number of users the campaign message was sent to. - **stats_users_read** (integer) - The number of users who read the campaign message. #### Response Example ```json { "id": "...", "stats": { "started_at": "2021-02-01 00:00:00", "completed_at": "2024-23-02 00:00:00", "messages_sent": 1000, "channels_created": 10, "stats_progress": 0.97, "stats_users_sent": 1000, "stats_users_read": 567 } } ``` ``` -------------------------------- ### v7 ChatUiConfig Initialization with Feature Flags Source: https://getstream.io/chat/docs/sdk/android/migration-guides/migrating-from-v6-to-v7.md Demonstrates initializing `ChatUiConfig` in v7 with various feature flags for translation, message list, composer, channel list, and attachment picker. ```kotlin ChatTheme( config = ChatUiConfig( translation = TranslationConfig(enabled = true), messageList = MessageListConfig( videoThumbnailsEnabled = true, ), composer = ComposerConfig( audioRecordingEnabled = true, linkPreviewEnabled = false, ), channelList = ChannelListConfig( swipeActionsEnabled = true, muteIndicatorPosition = MuteIndicatorPosition.InlineTitle, ), attachmentPicker = AttachmentPickerConfig( useSystemPicker = true, modes = listOf( GalleryPickerMode(), FilePickerMode(), CameraPickerMode(), PollPickerMode(), CommandPickerMode, ), ), ), ) { content() } ``` -------------------------------- ### Basic StreamChannelListView Example Source: https://getstream.io/chat/docs/sdk/flutter/v9/stream-chat-flutter/channel-list/stream-channel-list-view.md Demonstrates how to set up a basic StreamChannelListView with a controller and a channel tap handler. This example displays channels the user is a part of. ```dart class ChannelListPage extends StatefulWidget { const ChannelListPage({ super.key, required this.client, }); final StreamChatClient client; @override State createState() => _ChannelListPageState(); } class _ChannelListPageState extends State { late final _controller = StreamChannelListController( client: widget.client, filter: Filter.in_( 'members', [StreamChat.of(context).currentUser!.id], ), channelStateSort: const [SortOption('last_message_at')], ); @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) => Scaffold( body: RefreshIndicator( onRefresh: _controller.refresh, child: StreamChannelListView( controller: _controller, onChannelTap: (channel) => Navigator.push( context, MaterialPageRoute( builder: (_) => StreamChannel( channel: channel, child: const ChannelPage(), ), ), ), ), ), ); } ``` -------------------------------- ### Custom PollOptionFullResultsContent Example Source: https://getstream.io/chat/docs/sdk/react-native/ui-components/poll-option-full-results.md This example demonstrates how to create a custom content component for PollOptionFullResults. It uses `usePollState` to get the poll name and `usePollOptionVotesPagination` to fetch and display the first page of votes. This custom component can be passed to the PollOptionFullResults component via the `PollOptionFullResultsContent` prop. ```tsx import { Text, FlatList } from "react-native"; import { OverlayProvider, Chat, Channel, PollOptionFullResults, usePollOptionVotesPagination, usePollState, } from "stream-chat-react-native"; // will only display the first page of votes without loading more const MyPollOptionFullResultsContent = ({ option }) => { const { name } = usePollState(); const { votes } = usePollOptionVotesPagination({ option }); return ( {name}} data={votes} renderItem={({ item }) => {item.id}} /> ); }; const App = () => { return ( ); }; ``` -------------------------------- ### Get Pinned Messages (Oldest First) Source: https://getstream.io/chat/docs/react-native/pinned-messages.md Retrieves pinned messages sorted with the oldest messages first. This example shows how to fetch the first page. ```javascript // Oldest first const ascPage = await channel.getPinnedMessages({ limit: 10 }); ``` -------------------------------- ### Install Stream CLI via Homebrew Source: https://getstream.io/chat/docs/android/cli-introduction.md Installs the Stream CLI using Homebrew by tapping the repository and then installing the package. ```bash $ brew tap GetStream/stream-cli https://github.com/GetStream/stream-cli $ brew install stream-cli ``` -------------------------------- ### Install Stream CLI via Script (Linux x86) Source: https://getstream.io/chat/docs/flutter-dart/cli-introduction.md Installs the Stream CLI on Linux x86 by downloading the latest release binary via a script. ```bash $ export URL=$(curl -s https://api.github.com/repos/GetStream/stream-cli/releases/latest | grep Linux_x86 | cut -d '"' -f 4 | sed '1d') $ curl -L $URL -o stream-cli.tar.gz $ tar -xvf stream-cli.tar.gz ``` -------------------------------- ### Get Next Page of Search Results (Java) Source: https://getstream.io/chat/docs/ios-swift/search.md Example of fetching the next page of search results using the 'next' token from a previous search. ```java // Next page var nextResult = chat.search(SearchRequest.builder() .Payload(SearchPayload.builder() .filterConditions(Map.of("cid", "messaging:my-channel")) .messageFilterConditions(Map.of("text", Map.of("$autocomplete", "supercali"))) .sort(List.of( SortParamRequest.builder().field("relevance").direction(-1).build(), SortParamRequest.builder().field("updated_at").direction(1).build())) .limit(2) .next(searchResult.getNext()) .build()) .build()).execute().getData(); ``` -------------------------------- ### Ruby Example Source: https://getstream.io/chat/docs/javascript/query-channels.md This snippet shows how to query channels using Ruby. It demonstrates the use of predefined filters for production-ready applications. ```Ruby require 'getstream_ruby' Models = GetStream::Generated::Models # Production-ready: Use Predefined Filter channels = client.chat.query_channels( predefined_filter: "user_messaging_channels", filter_values: { user_id: user_id }, sort: [Models::SortParamRequest.new(field: "last_message_at", direction: -1)], limit: 20, ) ``` -------------------------------- ### Create and Update Channel (C#) Source: https://getstream.io/chat/docs/dotnet-csharp/backend.md Use the GetStream.Chat SDK for .NET to create or get a channel and update its data. Ensure the getstream-net package is installed. ```csharp // dotnet add package getstream-net using GetStream; using GetStream.Models; var client = new StreamClient("{{ api_key }}", "{{ api_secret }}"); var chat = new ChatClient(client); var resp = await chat.GetOrCreateChannelAsync("messaging", "channel-id", new ChannelGetOrCreateRequest { Data = new ChannelInput { CreatedByID = "user1-id", Custom = new Dictionary { ["mycustomfield"] = "123" } } }); ``` -------------------------------- ### Get Reactions with Pagination Source: https://getstream.io/chat/docs/unreal/send-reaction.md Use the `limit` and `offset` parameters to control the number of reactions retrieved and their starting point. The maximum `limit` is 300 and `offset` is 1000. ```javascript // Get the first 10 reactions const response = await channel.getReactions(messageID, { limit: 10 }); ``` ```javascript // Get reactions 11-13 const response = await channel.getReactions(messageID, { limit: 3, offset: 10, }); ``` -------------------------------- ### Basic Usage of useChannelActions Source: https://getstream.io/chat/docs/sdk/react-native/hooks/channel-list/use-channel-actions.md Demonstrates how to import and use the useChannelActions hook to get imperative channel action handlers. It shows examples of muting and archiving a channel. ```tsx import { useChannelActions } from "stream-chat-react-native"; const actions = useChannelActions(channel); await actions.muteChannel(); await actions.archive(); ``` -------------------------------- ### Start a Campaign (Python) Source: https://getstream.io/chat/docs/android/campaign-api.md Start a previously created campaign immediately or schedule it for a later time. This snippet also shows how to specify a stop time for the campaign. ```python # Start the campaign immediately client.chat.start_campaign(id="") # Alternatively you can schedule the campaign to start at a later time. # Also you can stop the campaign at a specific time. E.g., client.chat.start_campaign( id="", scheduled_for=datetime.datetime(2021, 12, 31, 23, 59, 59, tzinfo=datetime.timezone.utc), stop_at=datetime.datetime(2022, 1, 1, 23, 59, 59, tzinfo=datetime.timezone.utc), ) ``` -------------------------------- ### Python Example Source: https://getstream.io/chat/docs/javascript/query-channels.md This snippet shows how to query channels using Python. It demonstrates the use of predefined filters for production-ready applications. ```Python from getstream.models import SortParamRequest # Production-ready: Use Predefined Filter channels = client.chat.query_channels( predefined_filter="user_messaging_channels", filter_values={"user_id": user_id}, sort=[SortParamRequest(field="last_message_at", direction=-1)], limit=20, ) ``` -------------------------------- ### Get Latest Cleanup Runs (JavaScript) Source: https://getstream.io/chat/docs/android/data-retention-policy.md Retrieve the most recent cleanup runs for a specific policy, such as 'old-messages'. This example demonstrates filtering, sorting, and limiting results. ```javascript // Get the latest cleanup runs for old-messages policy const response = await client.getRetentionPolicyRuns({ filter_conditions: { policy: { $eq: "old-messages" }, }, sort: [{ field: "date", direction: -1 }], limit: 10, }); console.log(response.runs); // [ // { // app_pk: 12345, // policy: "old-messages", // date: "2026-03-20", // stats: { messages_deleted: 15420, channels_deleted: 0 } // } // ] ``` -------------------------------- ### Query members in Go Source: https://getstream.io/chat/docs/android/query-members.md Examples for querying members in Go. Includes filtering by name, autocompleting names, and querying all members. Ensure the client and context are initialized. ```go // Query members by user name client.Chat().QueryMembers(ctx, &getstream.QueryMembersRequest{ Payload: &getstream.QueryMembersPayload{ Type: "messaging", ID: getstream.PtrTo("general"), FilterConditions: map[string]any{"name": "tommaso"}, Offset: getstream.PtrTo(0), Limit: getstream.PtrTo(10), Sort: []getstream.SortParamRequest{{Field: getstream.PtrTo("created_at"), Direction: getstream.PtrTo(1)}}, }, }) // Autocomplete members by user name client.Chat().QueryMembers(ctx, &getstream.QueryMembersRequest{ Payload: &getstream.QueryMembersPayload{ Type: "messaging", ID: getstream.PtrTo("general"), FilterConditions: map[string]any{"name": map[string]any{"$autocomplete": "tom"}}, }, }) // Query all members client.Client.Chat().QueryMembers(ctx, &getstream.QueryMembersRequest{ Payload: &getstream.QueryMembersPayload{ Type: "messaging", ID: getstream.PtrTo("general"), FilterConditions: map[string]any{}, }, }) ``` -------------------------------- ### Python Campaign Methods Source: https://getstream.io/chat/docs/android/campaign-api.md This snippet shows how to use the Python SDK to manage campaigns, including getting, starting, stopping, and querying them. Note that creation and update are not yet available. ```APIDOC ## Campaign SDK Methods (Python) ### Description Provides methods for managing campaigns: get, start, stop, and query. Campaign creation and update are not yet available in the SDK. ### Methods - `client.chat.get_campaign(id)` - `client.chat.start_campaign(id, scheduled_for, stop_at)` - `client.chat.stop_campaign(id)` - `client.chat.query_campaigns(filter, sort, limit)` ### Parameters for `client.chat.start_campaign()` #### Request Body - `id` (string) - Required - The ID of the campaign. - `scheduled_for` (datetime object) - Optional - The time when the campaign should start. - `stop_at` (datetime object) - Optional - The time when the campaign should stop. ### Parameters for `client.chat.query_campaigns()` #### Query Parameters - `filter` (dict) - Filter criteria for querying campaigns. - `sort` (list of SortParamRequest objects) - Sorting parameters for the results. - `field` (string) - The field to sort by (e.g., "created_at"). - `direction` (int) - Sort direction (-1 for descending, 1 for ascending). - `limit` (int) - The maximum number of results to return. ### Response for `client.chat.query_campaigns()` #### Success Response - `data.campaigns` (list of campaign objects) - A list of campaign objects. - `data.next` (string) - A cursor for the next page of results. ``` -------------------------------- ### Install Stream Ruby SDK Source: https://getstream.io/chat/docs/ruby.md Install the SDK using the gem command. ```bash gem install getstream-ruby ``` -------------------------------- ### JavaScript Campaign Methods Source: https://getstream.io/chat/docs/android/campaign-api.md This snippet demonstrates how to use the JavaScript SDK to interact with the Campaign API, including creating, getting, updating, starting, stopping, deleting, and querying campaigns. ```APIDOC ## Campaign SDK Methods (JavaScript) ### Description Provides methods for managing campaigns: create, get, update, start, stop, delete, and query. ### Methods - `campaign.create()` - `campaign.get()` - `campaign.update(options)` - `campaign.start(options)` - `campaign.stop()` - `campaign.delete()` - `client.queryCampaigns(filter, sort, options)` ### Parameters for `campaign.update()` #### Request Body - `segment_ids` (array of strings) - Required - IDs of the segments to target. - `sender_id` (string) - Required - The user ID of the sender. - `sender_mode` (string) - Optional - Mode for sender selection (e.g., "include"). - `sender_visibility` (string) - Optional - Visibility of the sender (e.g., "archived"). - `name` (string) - Optional - The updated name of the campaign. - `message_template` (object) - Optional - The updated message template. - `text` (string) - The text content of the message. ### Parameters for `campaign.start()` #### Request Body - `scheduledFor` (string) - Optional - ISO 8601 timestamp for when the campaign should start. - `stopAt` (string) - Optional - ISO 8601 timestamp for when the campaign should stop. ### Parameters for `client.queryCampaigns()` #### Query Parameters - `filter` (object) - Filter criteria for querying campaigns. - `sort` (array of objects) - Sorting parameters for the results. - `field` (string) - The field to sort by (e.g., "created_at"). - `direction` (number) - Sort direction (-1 for descending, 1 for ascending). - `options` (object) - Additional options for the query. - `limit` (number) - The maximum number of results to return. - `next` (string) - A cursor for fetching the next page of results. ### Response for `client.queryCampaigns()` #### Success Response - `campaigns` (array of objects) - A list of campaign objects. - `next` (string) - A cursor for the next page of campaigns. ``` -------------------------------- ### Initialize Chat Client (Swift) Source: https://getstream.io/chat/docs/android/init-and-users.md Create an instance of ChatClient using your API key. It is recommended to store the client as a shared instance. ```swift // API key can be found on the dashboard: https://getstream.io/dashboard/ let config = ChatClientConfig(apiKey: .init("<# Your API Key Here #>")) // Create an instance of ChatClient let chatClient = ChatClient(config: config) // Recommendation is to store it as a shared instance extension ChatClient { static var shared: ChatClient! } ChatClient.shared = chatClient ``` -------------------------------- ### C#: Partial User Update Source: https://getstream.io/chat/docs/android/update-users.md Update user properties partially in C#. This example shows how to set and unset fields for a user. Ensure the getstream-net package is installed and the client is configured. ```csharp // dotnet add package getstream-net using GetStream; using GetStream.Models; var client = new StreamClient("{{ api_key }}", "{{ api_secret }}"); await client.UpdateUsersPartialAsync(new UpdateUsersPartialRequest { Users = new List { new UpdateUserPartialRequest { ID = userId, Set = new Dictionary { ["role"] = "admin", ["field2.subfield"] = "test" }, Unset = new List { "field.unset" } } } }); ``` -------------------------------- ### Install Stream CLI via Script (Linux x86) Source: https://getstream.io/chat/docs/android/cli-introduction.md Installs the Stream CLI on Linux x86 by downloading the latest release binary and extracting it. ```bash # Linux x86 $ export URL=$(curl -s https://api.github.com/repos/GetStream/stream-cli/releases/latest | grep Linux_x86 | cut -d '"' -f 4 | sed '1d') $ curl -L $URL -o stream-cli.tar.gz $ tar -xvf stream-cli.tar.gz ``` -------------------------------- ### Ruby Example Source: https://getstream.io/chat/docs/go-golang/query-channels.md This is a Ruby example for querying channels. It requires the getstream_ruby gem. ```Ruby require 'getstream_ruby' Models = GetStream::Generated::Models # Production-ready: Use Predefined Filter channels = client.chat.query_channels( predefined_filter: "user_messaging_channels", filter_values: { user_id: user_id }, sort: [Models::SortParamRequest.new(field: "last_message_at", direction: -1)], limit: 20 ) ``` -------------------------------- ### Custom ThreadListItem Component Source: https://getstream.io/chat/docs/sdk/react-native/v8/contexts/threads-context.md Example of creating a custom ThreadListItem component to override the default UI while retaining data access. It uses hooks from `stream-chat-react-native` to get thread and channel information. ```tsx import { Text, TouchableOpacity } from "react-native"; import { OverlayProvider, Chat, ThreadList, useThreadListItemContext, useThreadsContext, } from "stream-chat-react-native"; const ThreadListItem = () => { const { parentMessage, thread, channel } = useThreadListItemContext(); const { onThreadSelect } = useThreadsContext(); return ( onThreadSelect(thread, channel)}> {parentMessage?.text || "Text not available !"} ); }; const App = () => { return ( ); }; ```