---
sidebar_position: 8
---

# Message Bus API

The plugin message bus sends plugin-only P2P events. It can also include bounded latest-message snapshots for plugins that coordinate around recent chat state.

## Required Capabilities

| Method | Capability |
| --- | --- |
| `messageBus.publish(request)` | `events.p2p.publish`, plus `messages.read` if `includeLatestMessages` is true |
| `messageBus.sendLatestMessages(request?)` | `events.p2p.publish` and `messages.read` |
| `messageBus.subscribe(subscription)` | `events.p2p.subscribe`, plus `messages.read` if replaying latest messages |

## Subscribe

```js
export function activate(context) {
  context.subscriptions.push(context.api.messageBus.subscribe({
    topic: 'poll:votes',
    channelId: 'general',
    replayLatest: true,
    latestMessageLimit: 10,
    handler: (event) => {
      context.api.logger.info('Poll bus event', {
        topic: event.topic,
        choice: event.payload?.choice,
        messageCount: event.messages?.length ?? 0
      });
    }
  }));
}
```

## Publish

```js
export function activate(context) {
  const envelope = context.api.messageBus.publish({
    topic: 'poll:votes',
    channelId: 'general',
    payload: {
      pollId: 'raid-night-2026-04-29',
      choice: 'healer',
      voter: 'Alice'
    },
    includeLatestMessages: true,
    includeSelf: true,
    latestMessageLimit: 10,
    sinceTimestamp: 1777470000000
  });

  context.api.logger.info('Published poll event', { eventId: envelope.eventId });
}
```

Example envelope:

```json
{
  "eventId": "plugin-bus-1777473600000-1",
  "pluginId": "example.polls",
  "roomId": "room-7ebdde75",
  "channelId": "general",
  "topic": "poll:votes",
  "sentAt": 1777473600000,
  "payload": {
    "pollId": "raid-night-2026-04-29",
    "choice": "healer",
    "voter": "Alice"
  },
  "messages": [
    { "id": "msg-1", "content": "Raid tonight?", "channelId": "general" }
  ]
}
```

## Send Latest Messages

```js
export function activate(context) {
  context.api.messageBus.sendLatestMessages({
    topic: 'chat:snapshot',
    channelId: 'support',
    limit: 25,
    includeDeleted: false,
    sinceTimestamp: 1777460000000,
    targetPeerId: 'peer-muse-laptop'
  });
}
```

Use the message bus for plugin coordination. Do not use it for normal user chat messages; use `messages.send()` for that.