### Run Development Server
Source: https://github.com/ably/docs/blob/main/AGENTS.md
Quick start for development, including dependency installation and environment setup. Alternatively, manual setup involves installing dependencies, setting up the environment, and starting the development server.
```bash
bin/dev
```
```bash
yarn install
yarn develop:env-setup # First time only, creates .env.development
yarn develop # Dev server at localhost:8000
```
--------------------------------
### Run Pub/Sub Occupancy Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-occupancy/javascript/README.md
Start the local development server for the Pub/Sub occupancy JavaScript example.
```sh
yarn run pub-sub-occupancy-javascript
```
--------------------------------
### Quick Start: Create Client Session with Vercel
Source: https://github.com/ably/docs/blob/main/src/pages/docs/ai-transport/api/index.mdx
A minimal client session setup using the Vercel-pre-bound factory. This example demonstrates connecting to an Ably channel for AI transport.
```javascript
import * as Ably from 'ably';
import { createClientSession } from '@ably/ai-transport/vercel';
const ably = new Ably.Realtime({ authUrl: '/api/auth/token' });
const session = createClientSession({
client: ably,
channelName: 'conversation-42',
});
await session.connect();
```
--------------------------------
### Run LiveCounter JavaScript Example
Source: https://github.com/ably/docs/blob/main/examples/liveobjects-live-counter/javascript/README.md
Start the LiveCounter JavaScript example server.
```sh
yarn run liveobjects-live-counter-javascript
```
--------------------------------
### Run LiveMap JavaScript Example
Source: https://github.com/ably/docs/blob/main/examples/liveobjects-live-map/javascript/README.md
Start the LiveMap JavaScript example server using yarn.
```sh
yarn run liveobjects-live-map-javascript
```
--------------------------------
### Run React Pub/Sub Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-channel-messages/react/README.md
Start the React Pub/Sub channel messages example server. This command builds and runs the application locally.
```sh
yarn run pub-sub-channel-messages-react
```
--------------------------------
### Run Pub/Sub Connection State Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-connection-state/javascript/README.md
Run the JavaScript Pub/Sub connection state example server. This command starts the local development server.
```sh
yarn run pub-sub-connection-state-javascript
```
--------------------------------
### Run Component Locking Example
Source: https://github.com/ably/docs/blob/main/examples/spaces-component-locking/react/README.md
Start the React development server for the component locking example.
```sh
yarn run spaces-component-locking-react
```
--------------------------------
### Run Development Server
Source: https://github.com/ably/docs/blob/main/examples/spaces-member-location/react/README.md
Start the React development server for the member location example.
```sh
yarn run spaces-member-location-react
```
--------------------------------
### Run the React Pub/Sub Presence Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-presence/react/README.md
Start the development server for the React Pub/Sub Presence example.
```sh
yarn run pub-sub-presence-react
```
--------------------------------
### Run Pub/Sub History Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-history/javascript/README.md
Run the JavaScript Pub/Sub history example server. This command starts the local development server for testing.
```sh
yarn run pub-sub-history-javascript
```
--------------------------------
### Run Pub/Sub Message Annotations Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-message-annotations/javascript/README.md
Start the JavaScript Pub/Sub message annotations example server using Yarn.
```sh
yarn run pub-sub-message-annotations-javascript
```
--------------------------------
### Run Chat UI Chat Window Example
Source: https://github.com/ably/docs/blob/main/examples/chat-ui-chat-window/react/README.md
Start the development server for the Chat UI Chat Window example using Yarn. This command launches the application locally.
```sh
yarn run chat-ui-chat-window
```
--------------------------------
### Run Frontend Client
Source: https://github.com/ably/docs/blob/main/examples/auth-request-token/javascript/README.md
Start the frontend client application for the authentication example. This application will interact with the backend to obtain an Ably token.
```sh
yarn run auth-request-token-javascript
```
--------------------------------
### Run the frontend client
Source: https://github.com/ably/docs/blob/main/examples/auth-generate-jwt/react/README.md
Start the React frontend application for the JWT authentication example.
```sh
yarn run auth-generate-jwt-react
```
--------------------------------
### Run Pub/Sub Channel State Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-channel-state/javascript/README.md
Run the Pub/Sub channel state example server using yarn. This command starts the local development server to test the example.
```sh
yarn run pub-sub-channel-state-javascript
```
--------------------------------
### Run Chat Room History Example
Source: https://github.com/ably/docs/blob/main/examples/chat-room-history/javascript/README.md
Start the chat room history JavaScript example server. This command runs the application locally.
```sh
yarn run chat-room-history-javascript
```
--------------------------------
### Run AI Transport Example Server
Source: https://github.com/ably/docs/blob/main/examples/ai-transport-message-per-response/javascript/README.md
Start the local development server for the AI Transport message-per-response JavaScript example.
```sh
yarn run ai-transport-message-per-response-javascript
```
--------------------------------
### Run Live Cursors React Server
Source: https://github.com/ably/docs/blob/main/examples/spaces-live-cursors/react/README.md
Start the development server for the live cursors React example.
```sh
yarn run spaces-live-cursors-react
```
--------------------------------
### Run Pub/Sub Occupancy React Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-occupancy/react/README.md
Start the React development server for the Pub/Sub occupancy example.
```sh
yarn run pub-sub-occupancy-react
```
--------------------------------
### Run Pub/Sub Rewind Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-rewind/javascript/README.md
Start the local development server for the Pub/Sub rewind JavaScript example. This command compiles and runs the application, making it accessible in your browser.
```sh
yarn run pub-sub-rewind-javascript
```
--------------------------------
### Run the Spaces Avatar Stack Server
Source: https://github.com/ably/docs/blob/main/examples/spaces-avatar-stack/javascript/README.md
Start the development server for the Spaces Avatar Stack JavaScript example.
```sh
yarn run spaces-avatar-stack-javascript
```
--------------------------------
### Run Chat Typing Indicator Example
Source: https://github.com/ably/docs/blob/main/examples/chat-typing-indicator/javascript/README.md
Run the JavaScript chat typing indicator example server. This command starts the development server for testing the feature.
```sh
yarn run chat-typing-indicator-javascript
```
--------------------------------
### Run Chat Presence React Server
Source: https://github.com/ably/docs/blob/main/examples/chat-presence/react/README.md
Start the development server for the React chat presence example.
```sh
yarn run chat-presence-react
```
--------------------------------
### Run React Development Server
Source: https://github.com/ably/docs/blob/main/examples/ai-transport-message-per-response/react/README.md
Start the React development server for the AI transport message-per-response example.
```sh
yarn run ai-transport-message-per-response-react
```
--------------------------------
### Example Filter Configuration
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/external-storage-and-processing/data-extraction.mdx
Illustrates setting up a channel filter pattern to forward messages from specific chat rooms. This example shows how to get a room and send a message that would trigger an integration configured with the filter '^support:.*'.
```javascript
// Room name: support:ticket-123
// Filter pattern: ^support:.*
// Result: Messages from support:ticket-123 will be forwarded
const supportRoom = await chatClient.rooms.get('support:ticket-123');
await supportRoom.messages.send({ text: 'Help needed' }); // Will trigger integration
```
--------------------------------
### Run the chat room reactions server
Source: https://github.com/ably/docs/blob/main/examples/chat-room-reactions/javascript/README.md
Start the chat room reactions JavaScript server. This command builds and runs the example application.
```sh
yarn run chat-room-reactions-javascript
```
--------------------------------
### Run the Chat Typing Indicator React Server
Source: https://github.com/ably/docs/blob/main/examples/chat-typing-indicator/react/README.md
Start the development server for the React chat typing indicator example.
```sh
yarn run chat-typing-indicator-react
```
--------------------------------
### Run the React Server
Source: https://github.com/ably/docs/blob/main/examples/spaces-avatar-stack/react/README.md
Start the development server for the React avatar stack example using Yarn. This command builds and runs the application.
```sh
yarn run spaces-avatar-stack-react
```
--------------------------------
### Run Pub/Sub Connection State React Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-connection-state/react/README.md
Start the React development server for the Pub/Sub connection state example using Yarn.
```sh
yarn run pub-sub-connection-state-react
```
--------------------------------
### Run Pub/Sub History React Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-history/react/README.md
Start the local development server for the Pub/Sub history React example. This command compiles and runs the application, making it accessible in the browser.
```sh
yarn run pub-sub-history-react
```
--------------------------------
### Run Pub/Sub Rewind React Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-rewind/react/README.md
Start the React development server for the Pub/Sub rewind example. This command compiles and serves the application.
```sh
yarn run pub-sub-rewind-react
```
--------------------------------
### Change Directory to Examples
Source: https://github.com/ably/docs/blob/main/examples/ai-transport-message-per-token/javascript/README.md
Navigate into the examples directory after cloning the repository.
```sh
cd examples/
```
--------------------------------
### Install Ably Go SDK
Source: https://github.com/ably/docs/blob/main/src/pages/docs/getting-started/go.mdx
Installs the Ably Pub/Sub Go SDK and initializes a new Go project.
```shell
mkdir ably-go-quickstart
cd ably-go-quickstart
go mod init ably-go-quickstart
go get -u github.com/ably/ably-go/ably
```
--------------------------------
### Main Application Setup with ChatClientProvider
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/getting-started/react-ui-kit.mdx
Set up your main application entry point to use the React UI Kit. This involves initializing the Ably client, creating a ChatClient instance, and wrapping your application with necessary providers like ThemeProvider, AvatarProvider, ChatSettingsProvider, and ChatClientProvider.
```react
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(
);
```
--------------------------------
### Install Dependencies and Run Migrations
Source: https://github.com/ably/docs/blob/main/src/pages/docs/livesync/postgres/quickstart.mdx
Install project dependencies and run database migrations to set up tables and populate demo data.
```shell
pnpm install
pnpm run db
```
--------------------------------
### Get messages from before the subscription started
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/api/kotlin/messages.mdx
Get messages sent to the room from before the subscription was established. This is a suspend function.
```APIDOC
## subscription.historyBeforeSubscribe(start: Long? = null, end: Long? = null, limit: Int = 100): PaginatedResult
### Description
Get messages sent to the room from before the subscription was established.
This is a suspend function. It returns a [`PaginatedResult`](#PaginatedResult) containing a list of [Message](/docs/chat/api/kotlin/message) objects, or throws a [`ChatException`](/docs/chat/api/kotlin/chat-client#chatexception) on failure.
### Parameters
#### Path Parameters
None
#### Query Parameters
- **start** (Long) - Optional - Start of the time window to query, as a Unix timestamp in milliseconds.
- **end** (Long) - Optional - End of the time window to query, as a Unix timestamp in milliseconds.
- **limit** (Int) - Optional - Maximum number of messages to retrieve. Default: `100`.
#### Request Body
None
### Returns
[`PaginatedResult`](#PaginatedResult)
```
--------------------------------
### JavaScript Channel Get Example
Source: https://github.com/ably/docs/blob/main/data/onPostBuild/__fixtures__/input.mdx
Demonstrates how to get a channel instance using a template variable for the channel name.
```javascript
const channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}');
```
--------------------------------
### Basic App Setup with React UI Kit
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/react-ui-kit/components.mdx
Demonstrates the basic setup for integrating the Ably React UI Kit into a React application. Ensure you have the necessary Ably client and providers configured.
```react
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: '{{API_KEY}}',
clientId: 'user-' + Math.random().toString(36).substring(2, 15),
});
const chatClient = new ChatClient(ablyClient);
// Basic usage
function QuickChatPrototype() {
return (
);
}
// With custom dimensions
function CustomSizedChat() {
return (
);
}
```
--------------------------------
### Run AI Transport Example Server
Source: https://github.com/ably/docs/blob/main/examples/ai-transport-message-per-token/javascript/README.md
Start the JavaScript AI transport message per token streaming example server.
```sh
yarn run ai-transport-message-per-token-javascript
```
--------------------------------
### Get Room Message History Starting from Specific Time
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/rooms/messages/history.mdx
Fetches messages from a chat room starting from a specified point in time. Use the `--start` option with an ISO 8601 timestamp.
```shell
ably rooms messages history my-room --start "2025-01-01T00:00:00Z"
```
--------------------------------
### Run the Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-channel-state/react/README.md
Start the Pub/Sub channel state React development server.
```sh
yarn run pub-sub-channel-state-react
```
--------------------------------
### Install and Initialize Ably CLI
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/getting-started/javascript.mdx
Installs the Ably CLI and sets up authentication and default app configuration.
```shell
npx -p @ably/cli ably init
```
--------------------------------
### Basic ClientSessionProvider Setup
Source: https://github.com/ably/docs/blob/main/src/pages/docs/ai-transport/api/react/core/providers.mdx
Demonstrates how to wrap your application with AblyProvider and ClientSessionProvider to manage AI transport sessions. Ensure you have the necessary imports and an initialized Ably client.
```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 (
);
}
```
--------------------------------
### Run Laravel Development Servers
Source: https://github.com/ably/docs/blob/main/src/pages/docs/getting-started/laravel.mdx
Starts the PHP development server for Laravel and installs npm dependencies, then starts the Vite development server for frontend assets.
```shell
php artisan serve # http://localhost:8000
npm install
npm run dev
```
--------------------------------
### Run Live Cursors Example
Source: https://github.com/ably/docs/blob/main/examples/spaces-live-cursors/javascript/README.md
Run the live cursors JavaScript example server.
```sh
yarn run spaces-live-cursors-javascript
```
--------------------------------
### Full Chat Demo with Connection Management (Kotlin)
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/getting-started/jvm.mdx
This comprehensive example demonstrates initializing the Ably Chat client, setting up listeners for connection status changes, subscribing to messages, presence, reactions, and typing events. It includes sending messages, reactions, and demonstrating typing indicators. Crucially, it shows how to properly close the connection and detach the room in a finally block for resource management.
```kotlin
suspend fun fullChatDemo() {
val realtimeClient = AblyRealtime(
ClientOptions().apply {
key = ABLY_KEY
clientId = "demo-client"
}
)
val chatClient = ChatClient(realtimeClient) { logLevel = LogLevel.Info }
val room = chatClient.rooms.get("my-first-room")
try {
// Connection monitoring
chatClient.connection.onStatusChange { change ->
println("Connection status changed to: ${change.current}")
}
// Attach the room
room.attach()
println("=== Full Chat Demo Started ===")
// Subscribe to all events
room.messages.subscribe { messageEvent ->
val message = messageEvent.message
val timestamp = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date(message.timestamp))
val eventType = if (messageEvent.type == ChatMessageEventType.Created) "NEW" else "EDIT"
println("[$timestamp] $eventType: ${message.clientId}: ${message.text}")
}
room.presence.subscribe { presenceEvent ->
println("PRESENCE: ${presenceEvent.member.clientId} ${presenceEvent.type}")
}
room.reactions.subscribe { event ->
println("${event.reaction.clientId} reacted with: ${event.reaction.name}")
}
room.typing.subscribe { typingEvent ->
val typingUsers = typingEvent.currentlyTyping.joinToString(", ")
if (typingUsers.isNotEmpty()) {
println("TYPING: $typingUsers is typing...")
}
}
// Enter presence
room.presence.enter(
jsonObject {
put("status", "Online")
}
)
// Send a message
room.messages.send("Hello everyone! This is a JVM chat client.")
// Send a reaction
room.reactions.send("🎉")
// Demonstrate typing
room.typing.keystroke()
delay(2000)
room.typing.stop()
println("Demo running... Send messages via CLI or wait for auto-close")
delay(30000) // Run for 30 seconds
} catch (e: Exception) {
println("Error: ${e.message}")
} finally {
// Always close the connection
println("=== Closing connection ===")
realtimeClient.close()
room.detach()
println("Connection closed")
}
}
suspend fun main() {
fullChatDemo()
}
```
--------------------------------
### Full member location implementation example
Source: https://github.com/ably/docs/blob/main/src/pages/docs/spaces/locations.mdx
Demonstrates the complete process of initializing Ably Spaces, entering a space, subscribing to location updates, and publishing a member's location. Requires Ably client setup and custom UI logic.
```javascript
import Spaces from '@ably/spaces';
import { Realtime } from 'ably';
// Import your custom logic for handling member location updates
import updateLocations 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: 'Amelie' });
// Listen to member location updates
space.locations.subscribe('update', ({ member, currentLocation, previousLocation }) => {
// Update the UI to reflect member locations when receiving an update by adding a highlight to their currentLocation and removing the one from their previousLocation
updateLocations(member, currentLocation, previousLocation);
});
// Publish the member's location
await space.locations.set({ slide: 0, elementId: 'title' });
```
--------------------------------
### Run Pub/Sub Presence Example
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-presence/javascript/README.md
Run the JavaScript Pub/Sub presence example application.
```sh
yarn run pub-sub-presence-javascript
```
--------------------------------
### Full Occupancy Example
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/api/javascript/occupancy.mdx
Demonstrates setting up occupancy event listeners, fetching initial occupancy data, and accessing cached occupancy. Ensure `enableEvents` is true for event subscriptions and accessing `current` property. The room must be attached to receive events.
```javascript
const room = await chatClient.rooms.get('my-room', {
occupancy: {
enableEvents: true // Required for subscribe() and current property
}
});
await room.attach();
// Subscribe to occupancy changes
const { unsubscribe } = room.occupancy.subscribe((event) => {
const { connections, presenceMembers } = event.occupancy;
console.log(`Room has ${connections} connections and ${presenceMembers} presence members`);
// Update UI with viewer count
document.getElementById('viewer-count').textContent = connections;
});
// Fetch occupancy on-demand (works even without enableEvents)
const occupancy = await room.occupancy.get();
console.log(`Initial occupancy: ${occupancy.connections} connections`);
// Access cached occupancy (requires enableEvents)
const cached = room.occupancy.current;
if (cached) {
console.log('Cached occupancy:', cached.connections);
}
// Clean up
unsubscribe();
```
--------------------------------
### Implement Live Cursors
Source: https://github.com/ably/docs/blob/main/src/pages/docs/spaces/cursors.mdx
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 custom logic for rendering cursors.
```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 } });
});
```
--------------------------------
### Build and Serve Production Site
Source: https://github.com/ably/docs/blob/main/AGENTS.md
Builds the production-ready static site and serves it locally for testing.
```bash
yarn build # Production build with prefix paths
yarn serve # Serve production build
```
--------------------------------
### Copy Environment File
Source: https://github.com/ably/docs/blob/main/src/pages/docs/livesync/postgres/quickstart.mdx
Copy the example environment file to a local configuration file.
```shell
cp env.example env.local
```
--------------------------------
### Start Development Server
Source: https://github.com/ably/docs/blob/main/src/pages/docs/getting-started/nextjs.mdx
Run this command to start the Next.js development server. After starting, navigate to http://localhost:3000 in your browser to view the application.
```shell
npm run dev
```
--------------------------------
### Run Frontend Client
Source: https://github.com/ably/docs/blob/main/examples/auth-generate-jwt/javascript/README.md
Start the frontend client application. This command assumes you are in the correct directory within the cloned repository.
```sh
yarn run auth-generate-jwt-javascript
```
--------------------------------
### Run AI Transport React Example
Source: https://github.com/ably/docs/blob/main/examples/ai-transport-message-per-token/react/README.md
Start the AI Transport message per token streaming React server.
```sh
yarn run ai-transport-message-per-token-react
```
--------------------------------
### Create JWT with Capabilities (Go)
Source: https://github.com/ably/docs/blob/main/src/pages/docs/auth/capabilities.mdx
Server-side example of creating a JWT with specific capabilities. This snippet shows the setup for signing the JWT.
```go
// Server-side: Create JWT with capabilities using any JWT library
header := map[string]string{
"typ": "JWT",
"alg": "HS256",
"kid": keyName,
}
currentTime := time.Now().Unix()
claims := map[string]interface{}{
"iat": currentTime,
"exp": currentTime + 3600,
"x-ably-capability": `{"your-namespace:*":["publish","subscribe","presence"],"notifications":["subscribe"]}`,
"x-ably-clientId": userId,
}
// Sign using HS256 with your API key secret
```
--------------------------------
### Create Room, Send, and Subscribe to Messages (JVM)
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/getting-started/jvm.mdx
This snippet demonstrates how to initialize the Ably Realtime client, create a chat client, get and attach to a room, subscribe to incoming messages, send a message, and then clean up resources. Use this for basic chat functionality.
```kotlin
suspend fun demonstrateMessages() {
val realtimeClient = AblyRealtime(
ClientOptions().apply {
key = ABLY_KEY
clientId = "my-first-client"
}
)
val chatClient = ChatClient(realtimeClient) { logLevel = LogLevel.Info }
// Monitor connection status
chatClient.connection.onStatusChange { change ->
println("Connection status: ${change.current}")
}
// Get and attach to a room
val room = chatClient.rooms.get("my-first-room")
room.attach()
println("Room '${room.name}' status: ${room.status}")
// Subscribe to messages
val (unsubscribe) = room.messages.subscribe { messageEvent ->
val message = messageEvent.message
val timestamp = SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(Date(message.timestamp))
println("[$timestamp] ${message.clientId}: ${message.text}")
}
// Send a message
val myMessage = room.messages.send("Hello from JVM!")
println("Sent message with serial: ${myMessage.serial}")
// Keep listening for messages
println("Listening for messages... (press Ctrl+C to exit)")
delay(30000) // Keep running for 30 seconds
// Clean up
unsubscribe()
room.detach()
realtimeClient.close()
}
```
--------------------------------
### Install Ably SDK and Initialize Project
Source: https://github.com/ably/docs/blob/main/src/pages/docs/getting-started/node.mdx
Installs the Ably Pub/Sub JavaScript SDK and initializes a new Node.js project. This is a foundational step for using Ably in your Node.js application.
```shell
npm init -y && npm pkg set type=module
npm install ably
```
--------------------------------
### Install Ably Flutter SDK dependencies
Source: https://github.com/ably/docs/blob/main/src/pages/docs/getting-started/flutter.mdx
Run 'flutter pub get' to fetch the Ably Flutter SDK and its dependencies after adding it to pubspec.yaml.
```shell
flutter pub get
```
--------------------------------
### Get Chat Room and Send Message
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/external-storage-and-processing/data-extraction.mdx
Demonstrates how to get a chat room using the Chat SDK and send a message. The underlying Ably channel name includes a '::$chat' suffix. This example shows how a channel filter pattern can be used to trigger integrations.
```javascript
const supportRoom = await chatClient.rooms.get('chat:support');
// Underlying channel: chat:support::$chat
// Messages sent to these rooms will trigger an integration
// if your channel filter is: ^chat:support.*
await supportRoom.messages.send({ text: 'Need help' });
// Messages sent to other channel patterns will NOT trigger the integration
const generalRoom = await chatClient.rooms.get('chat:general');
// Underlying channel: chat:general::$chat
await generalRoom.messages.send({ text: 'Hi' }); // Won't trigger if filter is ^chat:support.*
```
--------------------------------
### Display Autocomplete Setup Instructions
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/autocomplete.mdx
Use this command to show instructions for setting up shell autocompletion for the Ably CLI. If no shell is specified, it defaults to your current shell.
```shell
ably autocomplete
```
--------------------------------
### Get the current state of a space
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/spaces/get.mdx
Use this command to retrieve the current state of a specified Ably space. Ensure you have the Ably CLI installed and configured.
```shell
ably spaces get my-space
```
--------------------------------
### Subscribe to occupancy events on a space
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/spaces/occupancy/subscribe.mdx
Use this command to start receiving real-time occupancy events for a specified space. Ensure you have the Ably CLI installed and configured.
```shell
ably spaces occupancy subscribe my-space
```
--------------------------------
### Set up SpacesProvider
Source: https://github.com/ably/docs/blob/main/src/pages/docs/spaces/react.mdx
Wrap your application with SpacesProvider and SpaceProvider to connect to Ably and specify the space name. Ensure your Ably client and Spaces instance are initialized.
```react
import { Realtime } from "ably";
import Spaces from "@ably/spaces";
import { SpacesProvider, SpaceProvider } from "@ably/spaces/react";
const ably = new Realtime({ key: "{{API_KEY}}", clientId: 'clemons' });
const spaces = new Spaces(ably);
root.render(
)
```
--------------------------------
### Run Pub/Sub Message Encryption React Server
Source: https://github.com/ably/docs/blob/main/examples/pub-sub-message-encryption/react/README.md
Start the development server for the Pub/Sub message encryption React example. This command compiles and runs the application.
```sh
yarn run pub-sub-message-encryption-react
```
--------------------------------
### React Chat Client Provider Setup
Source: https://github.com/ably/docs/blob/main/src/pages/docs/chat/api/react/providers.mdx
Demonstrates how to set up the ChatClientProvider and ChatRoomProvider in a React application. It includes initializing Ably and Chat clients and configuring room options.
```react
import * as Ably from 'ably';
import { ChatClient } from '@ably/chat';
import { ChatClientProvider, ChatRoomProvider } from '@ably/chat/react';
import { useMemo } from 'react';
// Create clients outside of components
// Use JWT token authentication in production
const realtimeClient = new Ably.Realtime({
key: '{{API_KEY}}',
clientId: 'user-123'
});
const chatClient = new ChatClient(realtimeClient);
function App() {
// Memoize room options to prevent unnecessary recreations
const roomOptions = useMemo(() => ({
typing: { heartbeatThrottleMs: 5000 },
occupancy: { enableEvents: true },
}), []);
return (
);
}
function ChatRoom() {
// All chat hooks can be used here
return Chat room content
;
}
```
--------------------------------
### Create an application using an access token environment variable
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/apps/create.mdx
Create a new application by providing your Ably access token via the `ABLY_ACCESS_TOKEN` environment variable.
```shell
ABLY_ACCESS_TOKEN="YOUR_ACCESS_TOKEN" ably apps create "My New App"
```
--------------------------------
### Get Room Message History Using Relative Time
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/rooms/messages/history.mdx
Retrieves messages from the last hour using a relative time format for the `--start` option.
```shell
ably rooms messages history my-room --start 1h
```
--------------------------------
### Get annotations with a limit
Source: https://github.com/ably/docs/blob/main/src/pages/docs/cli/channels/annotations/get.mdx
Use the `--limit` option to control the maximum number of annotations returned. This example retrieves up to 10 annotations for the specified message.
```shell
ably channels annotations get my-channel "msg-serial" --limit 10
```
--------------------------------
### Get Message Versions in Python
Source: https://github.com/ably/docs/blob/main/src/pages/docs/messages/updates-deletes.mdx
Retrieves all historical versions of a message from a channel using its serial. Requires the history capability. This example uses a hardcoded serial for demonstration.
```python
rest = AblyRest("{{API_KEY}}")
channel = rest.channels.get("updates:example")
# Example serial; for example from the `serial` property of a `Message` you previously received
serial = "0123456789-001@abcdefghij:001"
page = await channel.getMessageVersions(serial)
print("Found " + len(page.items) + " versions");
```
--------------------------------
### Run Member Location Example Server
Source: https://github.com/ably/docs/blob/main/examples/spaces-member-location/javascript/README.md
Run the JavaScript member location example server.
```sh
yarn run spaces-member-location-javascript
```