OpenClaw

OpenClaw Hooks & Event-Driven Automation👨‍💻

Hooks in OpenClaw are event-driven triggers that fire agent actions in response to system events. Unlike HEARTBEAT.md (which runs on a schedule) or cron jobs (which run at fixed times), hooks react to things that happen: a new message arrives, a session starts, an agent errors, or an external service sends a webhook. Hooks are the glue between OpenClaw's internal event system and your agent logic, enabling reactive workflows like auto-moderation, error alerting, onboarding flows, and CI/CD integrations. Combined with HEARTBEAT.md for scheduled automation, hooks give you complete coverage of both time-based and event-based agent triggers.

Key Takeaways

  • 1Hooks are defined in the gateway configuration under the 'hooks' key. Each hook specifies an event type, an optional filter, and an action. When the event fires and the filter matches, the action executes. Actions can route to an agent, send a notification, or trigger an external webhook.
  • 2Message hooks (onNewMessage) are the most common. They fire when a message arrives on any channel. Filters let you match by channel, sender role, content pattern, or metadata. Use message hooks for auto-moderation, keyword alerting, or routing urgent messages to specific agents.
  • 3Session hooks (onSessionCreate, onSessionEnd) fire when sessions start or finish. Use onSessionCreate to run onboarding logic (send a welcome message, load user context). Use onSessionEnd to trigger cleanup, logging, or follow-up actions.
  • 4Error hooks (onAgentError) fire when an agent encounters an unrecoverable error. They are essential for production reliability — route errors to an ops notification channel, create incident tickets, or trigger fallback agents.
  • 5HEARTBEAT.md works alongside hooks for scheduled automation. While hooks react to events, HEARTBEAT.md defines what an agent does on a time schedule. A complete automation setup combines hooks (react to what happens) with heartbeat (act on a schedule).
  • 6Hook ordering matters. When multiple hooks match the same event, they fire in the order defined in the configuration. Earlier hooks can modify the event payload or cancel propagation to later hooks using the 'stopPropagation' flag.

Master openclaw hooks & event-driven automation

Take the OpenClaw Automation & Workflows course with hands-on lessons and challenges.

Examples

Message hooks with content filtering

json

Two message hooks in priority order. The first catches urgent messages on Slack and routes them to the incident-responder agent with high priority, also notifying the ops-alerts channel. The second catches potential spam from non-admin users and routes to the moderator agent. Because urgent-escalation is listed first, it fires before auto-moderation.

Session lifecycle hooks

json

The onSessionCreate hook detects first-time users and triggers an onboarding flow. The onSessionEnd hook runs a summarizer agent that reads the session history (passSessionHistory: true) and writes key takeaways to MEMORY.md. This ensures important decisions are preserved even after the session ends.

Error hooks for production alerting

json

Two error hooks working together. The first sends an alert to ops with error details using template variables ({{agent.id}}, {{error.message}}). The second activates a fallback agent that takes over the conversation, receiving the full session history. The filter ensures the fallback agent itself does not trigger this hook if it also errors.

HEARTBEAT.md for scheduled monitoring (works alongside hooks)

markdown

HEARTBEAT.md is complementary to hooks. Hooks react to events (something happened). Heartbeat acts on a schedule (time to check). This heartbeat runs every 4 hours, performs health checks, and reports results. Combined with onAgentError hooks, this gives full coverage: heartbeat catches gradual degradation, hooks catch sudden failures.

Combining hooks with external webhooks

json

Hook chains let you compose multi-step workflows triggered by external webhooks. When GitHub sends a push event, the webhook fires the code-review-pipeline chain. Each step runs sequentially: parse the payload, review the code, and post results back to GitHub. Template variables pass data between steps.

Common Mistakes

Mistake:

Creating hooks without filters, causing every message or event to trigger the hook and generate unnecessary API calls

Fix:

Always add filters to narrow when hooks fire. An onNewMessage hook without a content or channel filter will fire on every single message across all channels, which is expensive and noisy.

Mistake:

Not adding an error hook for production agents, leaving agent failures undetected until users complain

Fix:

Add an onAgentError hook from day one. At minimum, send a notification to an ops channel. For user-facing agents, add a fallback agent that takes over the conversation when the primary agent fails.

Mistake:

Using hooks for tasks that should be scheduled (checking status every N minutes) instead of using HEARTBEAT.md

Fix:

Hooks react to events. Heartbeat runs on a schedule. If you need to check something periodically (health checks, report generation), use HEARTBEAT.md. If you need to react to something that happened (new message, error, session end), use hooks.

Mistake:

Defining circular hook chains where hook A triggers agent B which fires hook C which triggers agent D which fires hook A again

Fix:

OpenClaw detects and breaks circular hook chains after a configurable depth limit (default: 5). But relying on this safety net is bad practice. Design hook chains as directed acyclic graphs — each step should lead forward, not back to a previous step.

Best Practices

  • Start with three essential hooks for any production deployment: onNewMessage (for routing/moderation), onAgentError (for alerting), and onSessionCreate (for onboarding). Add more as specific needs arise.
  • Combine hooks with HEARTBEAT.md for complete automation coverage. Hooks handle real-time events, heartbeat handles scheduled checks. Together they cover both reactive and proactive automation.
  • Use hook chains for multi-step workflows triggered by external events. Each step in the chain should do one thing well. Pass data between steps using template variables.
  • Log all hook executions in development. Use `openclaw logs --filter hooks` to trace which hooks fired, what filters matched, and what actions executed. This is essential for debugging complex hook configurations.
  • Set stopPropagation on hooks that should be exclusive. If an urgent-escalation hook fires, you probably do not want the auto-moderation hook to also fire on the same message.
  • Test hooks by simulating events with the CLI: `openclaw hooks test onNewMessage --payload '{...}'`. This lets you verify filter logic without waiting for real events.

Summary

Hooks in OpenClaw are event-driven triggers that fire agent actions when something happens: new messages, session lifecycle events, agent errors, or external webhooks. They complement HEARTBEAT.md (scheduled automation) by handling real-time reactions. Configure hooks with filters to control when they fire, use hook chains for multi-step workflows, and always include error hooks for production reliability. Combined with heartbeat, hooks give complete automation coverage for both scheduled and event-driven agent workflows.

Practice OpenClaw with hands-on challenges

Learn openclaw hooks & event-driven automation hands-on in your IDE

Interactive lessons and challenges on Stanza, practice in VS Code, Cursor, or the web.

Related Concepts

Related Cheatsheets

Master OpenClaw with Stanza

Interactive lessons and challenges, right in your code editor.

Check the free courses. No credit card.