> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/ably/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Channels

Channels are the primary mechanism for organizing and routing messages in Ably. Each channel provides publish/subscribe functionality, presence, and history retrieval.

## Channels Collection

Access channels through the `channels` property:

<Code>
  ```javascript theme={null}
  const realtime = new Ably.Realtime('your-api-key');
  const channel = realtime.channels.get('my-channel');
  ```

  ```python theme={null}
  realtime = AblyRealtime('your-api-key')
  channel = realtime.channels.get('my-channel')
  ```
</Code>

### get

`channels.get(name, options?): Channel`

Get or create a channel instance.

<ParamField path="name" type="string" required>
  Channel name. Use `:` to separate namespaces (for example, `chat:room1`).
</ParamField>

<ParamField path="options" type="object">
  Channel options:

  * `params` (object): Channel parameters for filtering
  * `modes` (array): Channel modes (for example, `['PUBLISH', 'SUBSCRIBE']`)
  * `cipher` (object): Encryption configuration
</ParamField>

### release

`channels.release(name): void`

Release a channel and remove all listeners.

<Code>
  ```javascript theme={null}
  realtime.channels.release('my-channel');
  ```
</Code>

## Channel Object

A channel instance provides methods for publishing, subscribing, and managing channel state.

### Properties

<ParamField path="name" type="string">
  The channel name.
</ParamField>

<ParamField path="state" type="string">
  Current channel state: `initialized`, `attaching`, `attached`, `detaching`, `detached`, or `failed`.
</ParamField>

<ParamField path="errorReason" type="object">
  Error information if channel is in failed state.
</ParamField>

<ParamField path="presence" type="object">
  Presence object for this channel. See [Presence API](/docs/api/realtime-sdk/presence).
</ParamField>

### publish

`publish(name?, data?, callback?): Promise<void>`

Publish a message to the channel.

<Code>
  ```javascript theme={null}
  // Publish with name and data
  await channel.publish('event-name', 'message data');

  // Publish message object
  await channel.publish({
    name: 'event-name',
    data: { key: 'value' }
  });

  // Publish multiple messages
  await channel.publish([
    { name: 'event1', data: 'data1' },
    { name: 'event2', data: 'data2' }
  ]);
  ```

  ```python theme={null}
  # Publish with name and data
  await channel.publish('event-name', 'message data')

  # Publish message object
  await channel.publish({
      'name': 'event-name',
      'data': {'key': 'value'}
  })
  ```
</Code>

<ParamField path="name" type="string">
  Optional event name for the message.
</ParamField>

<ParamField path="data" type="any">
  Message payload. Supported types: string, JSON object, binary data.
</ParamField>

<ParamField path="callback" type="function">
  Optional callback function called on completion.
</ParamField>

### subscribe

`subscribe(eventName?, listener): Promise<void>`

Subscribe to messages on the channel.

<Code>
  ```javascript theme={null}
  // Subscribe to all messages
  await channel.subscribe((message) => {
    console.log('Message:', message.data);
  });

  // Subscribe to specific event
  await channel.subscribe('event-name', (message) => {
    console.log('Event:', message.data);
  });
  ```

  ```python theme={null}
  # Subscribe to all messages
  async def on_message(message):
      print('Message:', message.data)

  await channel.subscribe(on_message)

  # Subscribe to specific event
  async def on_event(message):
      print('Event:', message.data)

  await channel.subscribe('event-name', on_event)
  ```
</Code>

<ParamField path="eventName" type="string">
  Optional event name to filter messages.
</ParamField>

<ParamField path="listener" type="function" required>
  Callback function called for each message.
</ParamField>

### unsubscribe

`unsubscribe(eventName?, listener?): void`

Unsubscribe from messages.

<Code>
  ```javascript theme={null}
  // Unsubscribe specific listener
  channel.unsubscribe('event-name', myListener);

  // Unsubscribe all listeners for event
  channel.unsubscribe('event-name');

  // Unsubscribe all listeners
  channel.unsubscribe();
  ```
</Code>

### attach

`attach(callback?): Promise<void>`

Explicitly attach to the channel.

<Code>
  ```javascript theme={null}
  await channel.attach();
  console.log('Channel attached');
  ```

  ```python theme={null}
  await channel.attach()
  print('Channel attached')
  ```
</Code>

### detach

`detach(callback?): Promise<void>`

Detach from the channel.

<Code>
  ```javascript theme={null}
  await channel.detach();
  console.log('Channel detached');
  ```

  ```python theme={null}
  await channel.detach()
  print('Channel detached')
  ```
</Code>

### history

`history(options?): Promise<PaginatedResult<Message>>`

Retrieve message history for the channel.

<Code>
  ```javascript theme={null}
  const result = await channel.history({
    limit: 50,
    direction: 'backwards'
  });

  console.log('Messages:', result.items);

  // Get next page
  if (result.hasNext()) {
    const nextPage = await result.next();
  }
  ```

  ```python theme={null}
  result = await channel.history(
      limit=50,
      direction='backwards'
  )

  print('Messages:', result.items)

  # Get next page
  if result.has_next():
      next_page = await result.next()
  ```
</Code>

<ParamField query="start" type="integer">
  Start time in milliseconds since epoch.
</ParamField>

<ParamField query="end" type="integer">
  End time in milliseconds since epoch.
</ParamField>

<ParamField query="limit" type="integer" default="100">
  Maximum number of messages to return (max 1000).
</ParamField>

<ParamField query="direction" type="string" default="backwards">
  Query direction: `forwards` or `backwards`.
</ParamField>

## Channel Events

Subscribe to channel state changes:

<Code>
  ```javascript theme={null}
  channel.on('attached', () => {
    console.log('Channel attached');
  });

  channel.on('failed', (error) => {
    console.error('Channel failed:', error);
  });

  // Subscribe to all state changes
  channel.on((stateChange) => {
    console.log('State changed:', stateChange.current);
  });
  ```
</Code>

Channel states:

* `initialized` - Channel created but not attached
* `attaching` - Attachment in progress
* `attached` - Successfully attached
* `detaching` - Detachment in progress
* `detached` - Detached from channel
* `failed` - Attachment failed

## Related Resources

* [Messages API](/docs/api/realtime-sdk/messages)
* [Presence API](/docs/api/realtime-sdk/presence)
* [Channels Guide](/docs/channels)
* [Message History](/docs/storage-history/history)
