Trang chủ / Bài 8
Nâng cao ⏱ 25 phút
8

Hooks — Tự động hóa Workflow

Dùng Claude Code hooks để tự động chạy lệnh trước/sau mỗi tool call

🎯 Mục tiêu bài học

  • Hiểu cơ chế hooks trong Claude Code
  • Tạo pre/post tool hooks để tự động hóa
  • Xây dựng workflow tự động không cần can thiệp thủ công

Hooks là gì?

Hooks là các shell commands được Claude Code tự động chạy trước hoặc sau khi thực hiện một tool call cụ thể. Hooks cho phép bạn thêm logic tùy chỉnh mà không cần sửa source code Claude Code.

Các loại Hooks

HookKhi nào chạy
PreToolUseTrước khi Claude Code dùng một tool
PostToolUseSau khi tool chạy xong
StopKhi Claude Code kết thúc phiên làm việc
NotificationKhi Claude Code cần thông báo cho user
UserPromptSubmitKhi user gửi tin nhắn

Cấu hình Hooks

Thêm vào .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "npm run lint --fix"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "terminal-notifier -message 'Claude Code done!' -title 'ClaudeCode'"
          }
        ]
      }
    ]
  }
}

Ví dụ Hook thực tế

Auto-format sau khi chỉnh sửa file Python:

"PostToolUse": [{
  "matcher": "Edit|Write",
  "hooks": [{
    "type": "command",
    "command": "black . && isort ."
  }]
}]

Chạy tests sau khi commit:

"PostToolUse": [{
  "matcher": "Bash",
  "hooks": [{
    "type": "command",
    "command": "if git diff --cached --name-only | grep -q '.py'; then pytest tests/ -x -q; fi"
  }]
}]

Thông báo Slack khi hoàn thành:

"Stop": [{
  "hooks": [{
    "type": "command",
    "command": "curl -X POST $SLACK_WEBHOOK -d '{"text":"Task completed by Claude Code"}'"
  }]
}]

💡 Hook matcher

Matcher là regex khớp với tên tool. "Edit|Write" khớp cả Edit lẫn Write tool. "Bash" chỉ khớp khi Claude Code chạy lệnh bash.