### Install and Set Up Ably SDK for Push Notifications Source: https://ably.com/docs/push/configure/web?lang=csharp This example demonstrates how to install and initialize the Ably SDK, including the push notification plugin and specifying the service worker URL. This setup is required for sending push notifications to browsers. ```javascript import Ably from "ably"; import Push from "ably/push"; // pass in the push plugin via client options, along with the URL of your service worker const client = new Ably.Realtime({ pushServiceWorkerUrl: '/service_worker.js', plugins: { Push } }) ``` -------------------------------- ### Initialize REST SDK with API Key (Swift) Source: https://ably.com/docs/api/rest-sdk?lang=swift Instantiate the REST library using a string containing your API key. This is a simple way to get started with basic authentication. ```swift let client = AblyRest(key: "your_api_key") ``` -------------------------------- ### Install Dependencies and Run Migrations Source: https://ably.com/docs/livesync/postgres/quickstart Install the project's dependencies using pnpm and then run the database migrations to set up the necessary tables and populate them with demo data. ```bash pnpm install pnpm run db ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://ably.com/docs/chat/getting-started/javascript Set up a new Node.js project and install the necessary Ably Chat and TypeScript packages. ```bash npm init -y && npm pkg set type=module ``` ```bash npm install @ably/chat typescript -D @types/node ``` -------------------------------- ### Get Channel History with Query - Objective-C Source: https://ably.com/docs/api/realtime-sdk/history?lang=objc Customize message history retrieval by creating an `ARTRealtimeHistoryQuery` object. Set properties like `start`, `end`, `direction`, `limit`, and `untilAttach` to refine your query. This example demonstrates fetching messages backwards with a specific limit. ```objc ARTRealtimeHistoryQuery *query = [[ARTRealtimeHistoryQuery alloc] init]; query.limit = 50; query.direction = ARTRealtimeHistoryDirectionBackwards; [[channel history:query] callback:^(ARTPaginatedResult * _Nullable resultPage, ARLErrorInfo * _Nullable error) { if (error) { // Handle error } else { // Process resultPage.items } }]; ``` -------------------------------- ### Retrieve Channel History (PHP Example) Source: https://ably.com/docs/storage-history/history?lang=php This example demonstrates how to retrieve the most recent message from a channel using the PHP SDK. It initializes the REST client, gets a channel, publishes a message, and then fetches the history to get the latest message. ```APIDOC ## Retrieve Channel History (PHP Example) ### Description Retrieves the latest message sent on a channel using the Ably PHP SDK. ### Method `history()` ### Parameters #### Query Parameters (options object) - **start** (integer) - Optional - Earliest time in milliseconds since the epoch for any messages retrieved. - **end** (integer) - Optional - Latest time in milliseconds since the epoch for any messages retrieved. - **direction** (string) - Optional - Order of messages to retrieve. Can be `forwards` or `backwards` (default). - **limit** (integer) - Optional - Maximum number of messages to retrieve per page, up to 1,000. - **untilAttach** (boolean) - Optional - When true, ensures message history is up until the point of the channel being attached. Requires `direction` to be `backwards`. Only available with the realtime interface. ### Request Example ```php $rest = new Ably\AblyRest('xVLyHw.b81m9g:*****'); $channel = $rest->channels->get('rat-toy-oar'); $channel->publish('example', 'message data'); $resultPage = $channel->history(); $recentMessage = $resultPage->items[0]; echo("Most recent message data: " . $recentMessage->data); ``` ### Response #### Success Response (200) - **items** (array) - An array of message objects. - **hasNext** (boolean) - Indicates if there are more pages of history. - **isFirst** (boolean) - Indicates if this is the first page of history. #### Response Example ```json { "items": [ { "id": "msg1", "timestamp": 1678886400000, "data": "message data", "encoding": "json", "clientId": "client1", "connectionId": "conn1" } ], "hasNext": false, "isFirst": true } ``` ``` -------------------------------- ### Set Up Environment Variable Source: https://ably.com/docs/chat/getting-started/javascript Create a `.env` file in your project root to store your Ably API key. ```bash echo "ABLY_API_KEY=demokey:*****" > .env ``` -------------------------------- ### Get or Create a Channel Instance Source: https://ably.com/docs/rest/channels Use the `get()` method to create or retrieve a channel instance. This is the primary way to start interacting with a channel. ```javascript const channel = realtime.channels.get('gym-ill-dye'); ``` -------------------------------- ### Install Ably Go SDK Source: https://ably.com/docs/getting-started/go Installs the Ably Pub/Sub Go SDK and initializes a new Go module. Ensure you have Go version 1.18 or greater installed. ```bash mkdir ably-go-quickstart cd ably-go-quickstart go mod init ably-go-quickstart go get -u github.com/ably/ably-go/ably ``` -------------------------------- ### Manual Ably CLI Installation and Initialization Source: https://ably.com/docs/platform/tools/cli?lang=csharp Installs the Ably CLI globally using npm and then initializes it. ```bash npm install -g @ably/cli ably init ``` -------------------------------- ### Example Link Header for Pagination Source: https://ably.com/docs/api/rest-api An example of a Link header for the 'first' page of results, including query parameters like start time, end time, and limit. ```text Link: <./stats?start=1380794880000&end=1380794881058&limit=100&unit=minute&direction=forwards &format=json&first_start=1380794880000>; rel="first" ``` -------------------------------- ### SpacesProvider Setup Source: https://ably.com/docs/spaces/react?lang=react Demonstrates how to set up the SpacesProvider and SpaceProvider to wrap your application components, enabling access to Spaces functionality. ```APIDOC ## Setting up the Spaces Provider Use the `SpacesProvider` component to connect to Ably. The `SpacesProvider` should wrap every component that needs to access Spaces. ```javascript import { Realtime } from "ably"; import Spaces from "@ably/spaces"; import { SpacesProvider, SpaceProvider } from "@ably/spaces/react"; const ably = new Realtime({ key: "xVLyHw.n_Xwcg:*****", clientId: 'clemons' }); const spaces = new Spaces(ably); root.render( ) ``` ``` -------------------------------- ### Get Statistics Source: https://ably.com/docs/sdk/ruby/v1.2/Ably/Rest/Client.html Retrieves statistics from the Ably service. Supports options for direction, unit, limit, start, and end times. The end time must be equal to or after the start time. ```ruby def stats(options = {}) options = { :direction => :backwards, :unit => :minute, :limit => 100 }.merge(options) [:start, :end].each { |option| options[option] = as_since_epoch(options[option]) if options.has_key?(option) } raise ArgumentError, ":end must be equal to or after :start" if options[:start] && options[:end] && (options[:start] > options[:end]) paginated_options = { coerce_into: 'Ably::Models::Stats' } url = '/stats' response = get(url, options) Ably::Models::PaginatedResult.new(response, url, self, paginated_options) end ``` -------------------------------- ### Full Vercel Chat Wiring Example Source: https://ably.com/docs/ai-transport/api/react/vercel/chat-transport-provider This example demonstrates the complete setup for a chat application in a Vercel environment using ChatTransportProvider, useChatTransport, and useChat from @ai-sdk/react. It includes Ably integration for real-time communication. ```javascript 'use client'; import { useEffect, useState } from 'react'; import * as Ably from 'ably'; import { AblyProvider } from 'ably/react'; import { ChatTransportProvider, useChatTransport } from '@ably/ai-transport/vercel/react'; import { useChat } from '@ai-sdk/react'; function Providers({ children }) { const [client, setClient] = useState(null); useEffect(() => { const ably = new Ably.Realtime({ authUrl: '/api/auth/token', clientId: 'user' }); setClient(ably); return () => ably.close(); }, []); if (!client) return null; return {children}; } function Chat() { const { chatTransport } = useChatTransport(); const { messages, sendMessage, status, stop } = useChat({ transport: chatTransport }); return (
{messages.map((m) => (
{m.role}: {m.parts.map((p) => p.type === 'text' ? p.text : '').join('')}
))} {status === 'streaming' ? : }
); } export default function Page() { return ( ); } ``` -------------------------------- ### Copy Environment File Source: https://ably.com/docs/livesync/postgres/quickstart Copy the example environment file to create a local configuration file for your project. ```bash cp env.example env.local ``` -------------------------------- ### Get Rule by ID Example Source: https://ably.com/docs/api/control-api?lang=objc This snippet shows the structure of a rule object returned by the API when a rule is successfully retrieved. ```json { "id": "83IzAB", "appId": "28GY6a", "version": "1.2", "status": "enabled", "created": 1602844091815, "modified": 1614679682091, "_links": { }, "ruleType": "http", "requestMode": "single", "source": { "channelFilter": "^my-channel.*", "type": "channel.message" }, "target": { "url": "https://example.com/webhooks", "headers": [ { "name": "User-Agent", "value": "user-agent-string" }, { "name": "headerName", "value": "headerValue" } ], "signingKeyId": "bw66AB", "enveloped": true, "format": "json" } } ``` -------------------------------- ### Retrieve Stats from the Last Hour Source: https://ably.com/docs/cli/stats/app Get statistics from the past hour using a relative time format for the start time. ```bash ably stats app app-id --start 1h ``` -------------------------------- ### Basic React UI Kit Provider Setup Source: https://ably.com/docs/chat/react-ui-kit/setup?lang=kotlin Set up the essential context providers for the React UI Kit in your application's entry point. This includes initializing the Ably Realtime client and the ChatClient, then wrapping your application with ThemeProvider, AvatarProvider, ChatSettingsProvider, and ChatClientProvider. ```javascript import * as Ably from 'ably'; import { ChatClient } from '@ably/chat'; import { ChatClientProvider } from '@ably/chat/react'; import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit'; import '@ably/chat-react-ui-kit/dist/style.css'; // Create Ably Realtime client const ablyClient = new Ably.Realtime({ key: 'xVLyHw.T2XtHQ:*****', // Replace with your Ably API key clientId: '', }); const chatClient = new ChatClient(ablyClient); ReactDOM.createRoot(document.getElementById('root')).render( {/* Your components will go here */} ); ``` -------------------------------- ### Typing Indicator Usage Source: https://ably.com/docs/chat/api/javascript/typing This example demonstrates how to get a room, subscribe to typing events, send typing notifications, and manage the typing status. ```APIDOC ## Typing Indicator API ### Description This section details the methods available for managing typing indicators within a chat room. ### Methods #### `room.typing.keystroke()` **Description**: Notifies the server that the user has started typing or is continuing to type. This should be called when the user inputs text. **Usage**: Call this method when the user's input field has content. #### `room.typing.stop()` **Description**: Notifies the server that the user has stopped typing. This should be called when the user's input field is empty or the user navigates away. **Usage**: Call this method when the user's input field becomes empty or when the input loses focus. #### `room.typing.subscribe(callback)` **Description**: Subscribes to typing events for the current room. The callback function will be invoked with an event object containing the current typers. **Parameters**: - `callback` (function) - A function that accepts a single argument: `event`. - `event.currentTypers` (array) - An array of objects, where each object represents a user currently typing. Each user object typically contains a `clientId`. **Returns**: An `unsubscribe` function to stop listening for typing events. #### `room.typing.currentTypers` **Description**: A property that returns an array of users currently typing in the room. **Usage**: Access this property to get a snapshot of who is currently typing. ### Configuration When getting a room, you can configure typing event behavior: ```javascript const room = await chatClient.rooms.get('my-room', { typing: { heartbeatThrottleMs: 5000 // Throttle typing events to every 5 seconds } }); ``` **`typing.heartbeatThrottleMs`** (number) - Optional. The minimum time in milliseconds between sending typing notifications to the server. ``` -------------------------------- ### Set up SpacesProvider and SpaceProvider Source: https://ably.com/docs/spaces/react Wrap your application with SpacesProvider and SpaceProvider to establish an Ably connection and define a specific space. Ensure the SpacesProvider is initialized with an Ably client instance. ```jsx import { Realtime } from "ably"; import Spaces from "@ably/spaces"; import { SpacesProvider, SpaceProvider } from "@ably/spaces/react"; const ably = new Realtime({ key: "xVLyHw.b81m9g:*****", clientId: 'clemons' }); const spaces = new Spaces(ably); root.render( ) ``` -------------------------------- ### Basic App Component Usage Source: https://ably.com/docs/chat/react-ui-kit/components Demonstrates the basic setup for the App component, including necessary providers and initial room names. Ensure all required providers are wrapped around the App component. ```jsx import { App } from '@ably/chat-react-ui-kit'; import * as Ably from 'ably'; import { ChatClient } from '@ably/chat'; import { ChatClientProvider } from '@ably/chat/react'; import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit'; import '@ably/chat-react-ui-kit/dist/style.css'; // Create Ably Realtime client const ablyClient = new Ably.Realtime({ key: 'xVLyHw.6IqAyg:*****', clientId: 'user-' + Math.random().toString(36).substring(2, 15), }); const chatClient = new ChatClient(ablyClient); // Basic usage function QuickChatPrototype() { return ( ); } ``` -------------------------------- ### Get Channel History Source: https://ably.com/docs/sdk/ruby/v1.2/Ably/Rest/Channel.html Retrieves the message history for a channel with options for direction and limit. Raises an ArgumentError if start and end times are invalid. ```ruby def history(options = {}) url = "#{base_path}/messages" options = { :direction => :backwards, :limit => 100 }.merge(options) [:start, :end].each { |option| options[option] = as_since_epoch(options[option]) if options.has_key?(option) } raise ArgumentError, ":end must be equal to or after :start" if options[:start] && options[:end] && (options[:start] > options[:end]) paginated_options = { coerce_into: 'Ably::Models::Message', async_blocking_operations: options.delete(:async_blocking_operations), } response = client.get(url, options) Ably::Models::PaginatedResult.new(response, url, client, paginated_options) do |message| message.tap do |msg| decode_message msg end end end ``` -------------------------------- ### Run Development Server Source: https://ably.com/docs/getting-started/react Start the development server to view your React application. Open the provided URL in your browser to see the Ably connection state. ```bash npm run dev ``` -------------------------------- ### Get messages from before the subscription started Source: https://ably.com/docs/chat/api/javascript/messages Retrieve messages sent to the room from before the subscription was established. This method is part of the `MessageSubscriptionResponse` object returned by `messages.subscribe()`. ```APIDOC #### Get messages from before the subscription started `historyBeforeSubscribe(params?: HistoryBeforeSubscribeParams): Promise>` Get messages sent to the room from before the subscription was established. ##### Parameters The `historyBeforeSubscribe()` method takes the following parameters: * `params` (optional): Query parameters to filter message retrieval. Messages are returned in order of most recent to oldest. (Type: `HistoryBeforeSubscribeParams`) ##### Returns * `Promise>`: Returns a promise. The promise is fulfilled with a `PaginatedResult` containing an array of Message objects, or rejected with an `ErrorInfo` object. ``` -------------------------------- ### Basic App Component Usage Source: https://ably.com/docs/chat/react-ui-kit/components?lang=android Demonstrates the basic setup for the App component, including necessary providers and an initial room. Ensure you have the Ably client and chat client initialized. ```javascript import { App } from '@ably/chat-react-ui-kit'; import * as Ably from 'ably'; import { ChatClient } from '@ably/chat'; import { ChatClientProvider } from '@ably/chat/react'; import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit'; import '@ably/chat-react-ui-kit/dist/style.css'; // Create Ably Realtime client const ablyClient = new Ably.Realtime({ key: 'xVLyHw.QkbQcA:*****', clientId: 'user-' + Math.random().toString(36).substring(2, 15), }); const chatClient = new ChatClient(ablyClient); // Basic usage function QuickChatPrototype() { return ( ); } ``` -------------------------------- ### Get and Attach to a Chat Room Source: https://ably.com/docs/chat/api/javascript/room Obtain a room instance and attach to it to start receiving events. This is the initial step for interacting with a chat room. ```javascript const room = await chatClient.rooms.get('my-room'); // Attach to start receiving events await room.attach(); // Monitor room status const { off: offStatus } = room.onStatusChange((change) => { console.log(`Room status: ${change.current}`); }); // Monitor for discontinuities const { off: offDiscontinuity } = room.onDiscontinuity((reason) => { console.log('Discontinuity detected, consider re-fetching messages'); }); // Access room features const messages = room.messages; const presence = room.presence; const typing = room.typing; // Get the room name console.log('Room name:', room.name); // When done, detach and clean up await room.detach(); offStatus(); offDiscontinuity(); ``` -------------------------------- ### Create an Ably application using an access token environment variable Source: https://ably.com/docs/cli/apps/create This example demonstrates creating an application by setting the `ABLY_ACCESS_TOKEN` environment variable. Replace "YOUR_ACCESS_TOKEN" with your actual token. ```bash ABLY_ACCESS_TOKEN="YOUR_ACCESS_TOKEN" ably apps create "My New App" ``` -------------------------------- ### Location Push Notifications Setup Source: https://ably.com/docs/api/realtime-sdk/push?lang=objc Steps to enable and handle location push notifications using the Ably SDK, starting from iOS 15. ```APIDOC ## Request location token Call `CLLocationManager.startMonitoringLocationPushes(completion:)` within the `ARTPushRegistererDelegate.didActivateAblyPush(:)` delegate method. This delegate method is the callback for `ARTRealtime.push.activate()`. ## Register with Ably Call `ARTPush.didRegisterForLocationNotifications(withDeviceToken:realtime:)` when you receive the location push token. Note the "Location" in the method name to distinguish it from regular push tokens. ## Handle result Use the `ARTPushRegistererDelegate.didUpdateAblyPush:` callback, which indicates whether the token was successfully saved. ``` -------------------------------- ### Get Interval ID Source: https://ably.com/docs/sdk/ruby/v1.2/Ably/Models/Stats.html Retrieves the UTC time string representing the start of the stats interval. The format varies based on the interval's granularity. ```ruby # File 'lib/ably/models/stats.rb', line 201 def interval_id attributes.fetch(:interval_id) end ``` -------------------------------- ### Implement Live Cursors with Ably Spaces Source: https://ably.com/docs/spaces/cursors This snippet demonstrates the complete process of setting up live cursors. It includes initializing the Ably client and Spaces SDK, entering a space, subscribing to cursor updates, and publishing the member's cursor position on mouse movement. Ensure you have your custom `renderCursor` logic and Ably authentication endpoint configured. ```javascript import Spaces from '@ably/spaces'; import { Realtime } from 'ably'; // Import your custom logic for handling live cursors import { renderCursor } from '/src/own-logic'; // Create an Ably client const client = new Realtime({ authUrl: '', clientId: '' }); // Initialize the Spaces SDK using the Ably client const spaces = new Spaces(client); // Create a new space const space = await spaces.get('board-presentation'); // Enter the space to become a member, passing a nickname await space.enter({ name: 'Helmut' }); // Listen for cursor updates from members space.cursors.subscribe('update', async (cursorUpdate) => { // Use getAll() and filter by the member that moved their cursor to only update the position of that member's cursor const members = await space.members.getAll(); const member = members.find((member) => member.connectionId === cursorUpdate.connectionId); renderCursor(cursorUpdate, member); }); // Publish the member's cursor position window.addEventListener('mousemove', ({ clientX, clientY }) => { space.cursors.set({ position: { x: clientX, y: clientY } }); }); ``` -------------------------------- ### Get LiveMap Size (Swift) Source: https://ably.com/docs/liveobjects/map?lang=swift Retrieve the number of entries currently in a LiveMap by accessing its `size` property. The example shows creating a map and then printing its size. ```swift let map = try await channel.objects.createMap(entries: ["foo": "bar", "baz": "qux"]) print(try map.size) // e.g. 2 ``` -------------------------------- ### Install Ably SDK and Initialize Project Source: https://ably.com/docs/getting-started/node Installs the Ably JavaScript SDK and initializes a new Node.js project. This command also sets the project type to module. ```bash npm init -y && npm pkg set type=module npm install ably ``` -------------------------------- ### channels.get Source: https://ably.com/docs/channels/options?lang=javascript Set channel options when obtaining a channel instance by passing a channelOptions object to the get() method. This example shows setting the cipher property for encryption. ```APIDOC ## channels.get ### Description Obtain a channel instance with specific options set, such as encryption. ### Method `channels.get(name, channelOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **name** (string) - Required - The name of the channel. * **channelOptions** (object) - Optional - An object containing channel-specific options. Example: `{ cipher: { key: '...' } }` ### Request Example ```javascript const realtime = new Ably.Realtime('xVLyHw.h2Pfow:*****'); const cipherKey = await realtime.Crypto.generateRandomKey(); const channel = realtime.channels.get('cow-fun-mad', {cipher: {key: cipherKey}}); ``` ### Response #### Success Response A channel instance with the specified options. #### Response Example ```javascript // channel instance ``` ``` -------------------------------- ### Basic App Component Usage Source: https://ably.com/docs/chat/react-ui-kit/components?lang=kotlin Demonstrates the basic setup and usage of the App component with essential providers and an initial room. This is suitable for quick prototyping. ```javascript import { App } from '@ably/chat-react-ui-kit'; import * as Ably from 'ably'; import { ChatClient } from '@ably/chat'; import { ChatClientProvider } from '@ably/chat/react'; import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit'; import '@ably/chat-react-ui-kit/dist/style.css'; // Create Ably Realtime client const ablyClient = new Ably.Realtime({ key: 'xVLyHw.S0_uUQ:*****', clientId: 'user-' + Math.random().toString(36).substring(2, 15), }); const chatClient = new ChatClient(ablyClient); // Basic usage function QuickChatPrototype() { return ( ); } ``` -------------------------------- ### Instantiate Realtime SDK with Token Details Source: https://ably.com/docs/api/realtime-sdk?lang=nodejs Instantiate the Realtime library using a tokenDetails object. This method is less common for initial setup as tokens are short-lived and typically require a mechanism for renewal. ```javascript new Ably.Realtime(tokenDetails); ``` -------------------------------- ### Hash Filter Example Source: https://ably.com/docs/messages?lang=objc Apply the hash filter to a channel name to get a stringified 32-bit fingerprint. An optional base argument can be provided, defaulting to 16 (hexadecimal). ```text #{channelName | hash} ``` ```text #{channelName | hash(10)} ``` -------------------------------- ### Install React UI Kit Packages Source: https://ably.com/docs/chat/react-ui-kit/setup Install the Ably Pub/Sub SDK, Chat SDK, and the Chat React UI Kit using NPM. ```bash npm install ably @ably/chat @ably/chat-react-ui-kit ``` -------------------------------- ### Get Application Stats Source: https://ably.com/docs/sdk/ruby/v1.2/Ably/Realtime/Client.html Queries the REST /stats API to retrieve application usage statistics. You can specify start and end times, direction, limit, and unit for the stats. ```ruby def stats(options = {}) async_wrap(callback) do rest_client.request(method, path, params, body, headers, async_blocking_operations: true) end end ``` -------------------------------- ### ClientSessionProvider Setup Source: https://ably.com/docs/ai-transport/api/react/core/providers Demonstrates how to wrap your React application with AblyProvider and ClientSessionProvider. This setup is necessary for using hooks like useClientSession, useView, etc. Ensure you have the necessary Ably client and codec configured. ```javascript import * as Ably from 'ably'; import { AblyProvider } from 'ably/react'; import { ClientSessionProvider } from '@ably/ai-transport/react'; import { UIMessageCodec } from '@ably/ai-transport/vercel'; const ably = new Ably.Realtime({ authUrl: '/api/auth/token' }); function App() { return ( ); } ``` -------------------------------- ### Create an HTTP Rule Source: https://ably.com/docs/api/control-api?lang=csharp Example of creating an HTTP rule for an application. This rule is configured to process messages from channels starting with 'my-channel.' and send them to a specified webhook URL. ```json { "status": "enabled", "ruleType": "http", "requestMode": "single", "source": { "channelFilter": "^my-channel.*", "type": "channel.message" }, "target": { "url": "https://example.com/webhooks", "headers": [ { "name": "User-Agent", "value": "user-agent-string" }, { "name": "headerName", "value": "headerValue" } ], "signingKeyId": "bw66AB", "enveloped": true, "format": "json" } } ``` -------------------------------- ### Basic React UI Kit Provider Setup Source: https://ably.com/docs/chat/react-ui-kit/setup?lang=swift Set up the essential context providers for the React UI Kit in your application's entry point. This includes initializing the Ably Chat client and wrapping your application with ThemeProvider, AvatarProvider, ChatSettingsProvider, and ChatClientProvider. ```javascript import * as Ably from 'ably'; import { ChatClient } from '@ably/chat'; import { ChatClientProvider } from '@ably/chat/react'; import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit'; import '@ably/chat-react-ui-kit/dist/style.css'; // Create Ably Realtime client const ablyClient = new Ably.Realtime({ key: 'xVLyHw.UQMaKQ:*****', // Replace with your Ably API key clientId: '', }); const chatClient = new ChatClient(ablyClient); ReactDOM.createRoot(document.getElementById('root')).render( {/* Your components will go here */} ); ``` -------------------------------- ### Fetch specific fields from Stats API Source: https://ably.com/docs/api/rest-api?lang=go Use the `fields` parameter to retrieve only specific fields from the API response. This example shows how to get the peak channels and interval ID. ```curl curl https://main.realtime.ably.net/stats?fields=channels.peak,intervalId \ -u "xVLyHw.QRUNtw:*****" ``` ```json [ { "channels": {"peak": 2}, "intervalId": "2015-11-20:15" } ] ``` -------------------------------- ### Instantiate ARTRealtime Client and Monitor Connection Source: https://ably.com/docs/getting-started/swift Create an ARTRealtime instance with your API key and clientId. The client connects to Ably upon instantiation and logs connection state changes. ```swift let clientOptions = ARTClientOptions(key: "xVLyHw.6IqAyg:*****") clientOptions.clientId = "my-first-client" let realtime = ARTRealtime(options: clientOptions) realtime.connection.on { stateChange in print("Connection state changed to: \(stateChange.current)") if stateChange.current == .connected { print("Made my first connection!") } } ``` -------------------------------- ### Response Sample for Reactions Summary Source: https://ably.com/docs/api/chat-rest?lang=android Example JSON response structure for a successful request to get the client reactions summary. It includes unique, distinct, and multiple reaction counts. ```json { "unique": { "property1": { "total": 0, "clientIds": [ "string" ], "clipped": true }, "property2": { "total": 0, "clientIds": [ "string" ], "clipped": true } }, "distinct": { "property1": { "total": 0, "clientIds": [ "string" ], "clipped": true }, "property2": { "total": 0, "clientIds": [ "string" ], "clipped": true } }, "multiple": { "property1": { "total": 0, "clientIds": { "property1": 0, "property2": 0 }, "totalUnidentified": 0, "clipped": true, "totalClientIds": 0 }, "property2": { "total": 0, "clientIds": { "property1": 0, "property2": 0 }, "totalUnidentified": 0, "clipped": true, "totalClientIds": 0 } } } ``` -------------------------------- ### Initializing with Client Options Source: https://ably.com/docs/api/rest-sdk?lang=swift Instantiate the REST library using a specified ClientOptions object. ```APIDOC ## init(options: ARTClientOptions) ### Description Instantiates the library using the specified `ClientOptions`. ### Method Signature `init(options: ARTClientOptions)` ``` -------------------------------- ### Initialize Realtime SDK with Client Options Source: https://ably.com/docs/api/realtime-sdk?lang=objc Instantiate the Ably Realtime library using a pre-configured ARTClientOptions object. Ensure ARTClientOptions is properly set up before initialization. ```objc (instancetype)initWithOptions:(ARTClientOptions *)options; ``` -------------------------------- ### Instantiate Realtime SDK with API Key Source: https://ably.com/docs/api/realtime-sdk?lang=flutter Instantiate the Ably Realtime library directly with a string containing your API key or Token ID. This is a simpler way to get started. ```dart final AblyRealtime realtime = AblyRealtime(key: 'YOUR_API_KEY'); ``` -------------------------------- ### Main Application Setup with Providers Source: https://ably.com/docs/chat/getting-started/react-ui-kit This setup renders the ChatApp component within essential providers like ThemeProvider, AvatarProvider, ChatSettingsProvider, and ChatClientProvider. It initializes the Ably and Chat clients. ```tsx // main.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import * as Ably from 'ably'; import { ChatClient } from '@ably/chat'; import { ChatClientProvider } from '@ably/chat/react'; import { ThemeProvider, AvatarProvider, ChatSettingsProvider } from '@ably/chat-react-ui-kit'; import '@ably/chat-react-ui-kit/dist/style.css'; import { ChatApp } from './App.tsx'; // Assuming your app.tsx is in the same directory const ablyClient = new Ably.Realtime({ key: process.env.ABLY_API_KEY, clientId: 'your-chat-client-id', }); const chatClient = new ChatClient(ablyClient); ReactDOM.createRoot(document.querySelector('#root') || document.createElement('div')).render( ); ``` -------------------------------- ### Subscribe to Annotation Events in Node.js Source: https://ably.com/docs/messages/annotations Subscribe to individual annotation events in a Node.js environment. Ensure the `ANNOTATION_SUBSCRIBE` mode is included when getting the channel. This example logs new or deleted annotations. ```javascript // Create an Ably Realtime client specifying the clientId that will // be associated with annotations published by this client const realtime = new Ably.Realtime({ key: 'your-api-key', clientId: 'my-client-id' }); // Create a channel in a namespace called `annotations` // which has message annotations enabled. // Specify the ANNOTATION_SUBSCRIBE mode to enable annotation subscriptions. const channel = realtime.channels.get('annotations:example', { modes: ['ANNOTATION_SUBSCRIBE'] }); await channel.annotations.subscribe((annotation) => { if (annotation.action === 'annotation.create') { console.log(`New ${annotation.type} annotation with name ${annotation.name} from ${annotation.clientId}`); } else if (annotation.action === 'annotation.delete') { console.log(`${annotation.clientId} deleted a ${annotation.type} annotation with name ${annotation.name}`); } }); ```