> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch34-infrastructure/34.5-polls-system.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 34.5 Polls System

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~104k tokens, Output \~4k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In group chats, Agents sometimes need to initiate polls to gather user opinions—for example, "Do you prefer Plan A or Plan B?" OpenClaw's polls system (`src/polls.ts`) provides a platform-agnostic poll data model and validation layer, with specific poll creation delegated to each chat platform's SDK implementation.

## 34.5.1 Polls Implementation (`src/polls.ts`)

### Data Model

The core data structure for polls is very concise:

```typescript
// src/polls.ts
export type PollInput = {
  question: string;       // Poll question
  options: string[];      // Option list (at least 2)
  maxSelections?: number; // Maximum selectable items (default 1 = single choice)
  durationHours?: number; // Poll duration (hours)
};

export type NormalizedPollInput = {
  question: string;
  options: string[];
  maxSelections: number;  // Required (defaults filled)
  durationHours?: number;
};
```

`PollInput` is the raw format of external input, while `NormalizedPollInput` is the standard format after validation and default value filling.

### Input Validation

`normalizePollInput` implements a complete input validation chain:

```typescript
export function normalizePollInput(
  input: PollInput,
  options: { maxOptions?: number } = {},
): NormalizedPollInput {
  // 1. Question cannot be empty
  const question = input.question.trim();
  if (!question) throw new Error("Poll question is required");
  
  // 2. Option cleaning: trim whitespace → filter empty strings → at least 2
  const cleaned = input.options.map(o => o.trim()).filter(Boolean);
  if (cleaned.length < 2) throw new Error("Poll requires at least 2 options");
  
  // 3. Option limit check (platform-dependent, e.g., Discord max 10)
  if (options.maxOptions && cleaned.length > options.maxOptions) {
    throw new Error(`Poll supports at most ${options.maxOptions} options`);
  }
  
  // 4. maxSelections validation: ≥1 and ≤ option count
  const maxSelections = typeof input.maxSelections === "number"
    ? Math.floor(input.maxSelections) : 1;
  if (maxSelections < 1) throw new Error("maxSelections must be at least 1");
  if (maxSelections > cleaned.length) throw new Error("maxSelections cannot exceed option count");
  
  // 5. durationHours validation: ≥1 (if provided)
  const durationHours = typeof input.durationHours === "number"
    ? Math.floor(input.durationHours) : undefined;
  if (durationHours !== undefined && durationHours < 1) {
    throw new Error("durationHours must be at least 1");
  }
  
  return { question, options: cleaned, maxSelections, durationHours };
}
```

### Duration Normalization

`normalizePollDurationHours` constrains poll duration to the range allowed by the platform:

```typescript
export function normalizePollDurationHours(
  value: number | undefined,
  options: { defaultHours: number; maxHours: number },
): number {
  const base = typeof value === "number" && Number.isFinite(value)
    ? Math.floor(value)
    : options.defaultHours;
  return Math.min(Math.max(base, 1), options.maxHours);
  // Result guaranteed to be in [1, maxHours] range
}
```

Different platforms have different limits. For Discord, for example, polls can last up to 32 days (`32 * 24 = 768` hours) with a maximum of 10 options.

### Platform Integration

The polls module itself is a pure validation layer with no platform-specific logic. Each channel plugin is responsible for converting `NormalizedPollInput` to the platform's native poll format:

| Platform | Poll Support | Max Options | Max Duration | Corresponding File           |
| -------- | ------------ | ----------- | ------------ | ---------------------------- |
| Discord  | ✓            | 10          | 32 days      | `src/discord/send.shared.ts` |
| WhatsApp | ✓            | -           | -            | `src/whatsapp/`              |
| MS Teams | ✓            | -           | -            | `src/msteams/`               |
| Telegram | ✗            | -           | -            | -                            |
| Web      | ✓            | -           | -            | `src/web/outbound.ts`        |

**Discord Poll Example**:

Discord polls are created via the `poll` field in the REST API. OpenClaw first calls `normalizePollInput` for validation, then calls `normalizePollDurationHours` to constrain duration, and finally constructs a `RESTAPIPoll` object:

```typescript
// src/discord/send.shared.ts (concept simplified)
const normalized = normalizePollInput(pollInput, { maxOptions: 10 });
const durationHours = normalizePollDurationHours(normalized.durationHours, {
  defaultHours: 24,
  maxHours: 32 * 24,
});
const poll: RESTAPIPoll = {
  question: { text: normalized.question },
  answers: normalized.options.map(text => ({ poll_media: { text } })),
  duration: durationHours,
  allow_multiselect: normalized.maxSelections > 1,
  layout_type: PollLayoutType.Default,
};
```

### Channel Capability Declaration

Polls are an optional channel capability. When registering a channel, it declares support for `polls` in `capabilities`:

```typescript
// src/channels/dock.ts (Discord channel capability declaration example)
{
  polls: true,    // Support polls
  // ...other capabilities
}
```

The Agent tool layer checks the capability flag before executing poll actions:

```typescript
// src/agents/tools/discord-actions-messaging.ts
if (!isActionEnabled("polls")) {
  throw new Error("Discord polls are disabled.");
}
```

### Architectural Design Philosophy

The polls system design embodies a core principle of OpenClaw: **platform-agnostic semantic layer + platform-specific adaptation layer**.

```
Agent tool layer
  ↓ Generate PollInput { question, options, maxSelections, durationHours }
  ↓ 
normalizePollInput()  ← Platform-agnostic validation
  ↓
NormalizedPollInput
  ↓
Channel adaptation layer  ← Convert to native format for each platform
  ├─ Discord: RESTAPIPoll
  ├─ WhatsApp: WhatsApp Poll Message
  └─ Web: ActiveListener push
```

This layering makes adding poll support for new platforms straightforward—just implement the conversion from `NormalizedPollInput` to the native format in the channel plugin, with no need to duplicate core validation logic.

***

## Section Summary

1. **Poll Data Model** is defined by `PollInput` / `NormalizedPollInput`, containing four fields: question, option list, maximum selections, and duration.
2. **Input Validation** is uniformly performed by `normalizePollInput`—cleaning option text, verifying at least 2 options, checking `maxSelections` range, validating duration.
3. **Duration Normalization** uses `normalizePollDurationHours` to constrain values to the `[1, maxHours]` range, with different platforms having different upper limits.
4. **Platform Integration** is achieved through capability declaration (`polls: true`) and adaptation layer, with each channel converting standardized poll input to platform-native format.
5. **Architectural Philosophy** is "platform-agnostic semantic layer + platform-specific adaptation layer"—adding poll support for new platforms only requires implementing conversion, no need to modify core validation.

***

> ### 🔬 Going Deeper: 34.6 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**34.6 Source Deep Dive: The Media Candidate Chain and the Vision Short-Circuit**](https://www.openclawbook.xyz/en/ch34-infrastructure/34.6-source-deep-dive-media-candidate-chain-and-vision-skip.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
