Week 7 of 12 🪝

Hooks & Automation

Hooks และระบบอัตโนมัติ

Hooks 与自动化

Hooks & Automation

1. Introduction / บทนำ / 简介

Hooks คือสคริปต์อัตโนมัติที่ทำงานตามเหตุการณ์เฉพาะใน Claude Code สามารถจัดรูปแบบโค้ดหลังแก้ไข ป้องกันคำสั่งอันตราย ส่งการแจ้งเตือน และบังคับใช้กฎโปรเจกต์ — ทั้งหมดโดยไม่ต้องทำด้วยตนเอง
Hooks 是在 Claude Code 特定生命周期事件时运行的自动化脚本。它们可以在编辑后格式化代码、拦截危险命令、发送通知并强制执行项目规则——全都无需人工干预。
Hooks are automated scripts that run at specific lifecycle events in Claude Code. They can format code after edits, block dangerous commands, send notifications, and enforce project rules — all without manual intervention.

Fun Facts / ข้อเท็จจริงที่น่าสนใจ / 趣味知识

  • Exit code 2 blocks the action and tells Claude why.
  • Hooks can be shell commands, HTTP calls, or AI prompts!
  • PostToolUse hooks are great for auto-formatting code.
A colorful chain-reaction machine with bells and rolling-ball tracks
A chain-reaction machine: one event triggers the next — exactly how hooks work. — Photo: Jeff Kubina, CC BY-SA 2.0, via Wikimedia Commons

2. Vocabulary / คำศัพท์ / 词汇

Click a card to flip it. คลิกการ์ดเพื่อพลิก 点击卡片翻面。

hook
ฮุก
钩子
A script that runs at a specific event
event
เหตุการณ์
事件
Something that happens in the system
automate
ทำอัตโนมัติ
自动化
To make something run by itself
block
บล็อก / ป้องกัน
拦截
To prevent an action from happening
format
จัดรูปแบบ
格式化
To arrange code in a standard style
validate
ตรวจสอบ
验证
To check if something is correct
notify
แจ้งเตือน
通知
To send an alert or message
matcher
ตัวจับคู่
匹配器
A pattern to match specific tool names
exit code
รหัสออก
退出码
A number showing if a command succeeded
stdin
สแตนดาร์ดอินพุต
标准输入
Standard input — data fed to a program
stdout
สแตนดาร์ดเอาต์พุต
标准输出
Standard output — data from a program
lifecycle
วงจรชีวิต
生命周期
The stages from start to end

3. Grammar Focus / ไวยากรณ์ / 语法焦点

Conditional Sentences (If... then..., When... then...) / ประโยคเงื่อนไข (If... then..., When... then...) / 条件句(If... then...、When... then...)

Thai:
ประโยคเงื่อนไขอธิบายสิ่งที่เกิดขึ้นภายใต้เงื่อนไข 'If + present, present/future' สำหรับเงื่อนไขจริง 'When + present, present' สำหรับสิ่งที่เกิดขึ้นเสมอ ตัวอย่าง: 'If you edit a file, the hook runs.' 'When Claude finishes, it sends a notification.'
中文:
条件句描述在某种条件下会发生什么。'If + 现在时,现在时/将来时' 用于真实条件。'When + 现在时,现在时' 用于总会发生的事。例如:'If you edit a file, the hook runs.'(如果你编辑文件,hook 就会运行。)'When Claude finishes, it sends a notification.'(当 Claude 完成时,它会发送通知。)
English:
Conditional sentences describe what happens under certain conditions. 'If + present, present/future' for real conditions. 'When + present, present' for things that always happen. Example: 'If you edit a file, the hook runs.' 'When Claude finishes, it sends a notification.'
ถ้า exit code เป็น 2 Claude จะบล็อกการดำเนินการ
如果退出码是 2,Claude 就会拦截该操作。
If the exit code is 2, Claude blocks the action.
เมื่อคุณบันทึกไฟล์ ตัวจัดรูปแบบจะทำงาน
当你保存文件时,格式化工具就会运行。
When you save a file, the formatter runs.
ถ้าโทเค็นไม่ถูกต้อง การยืนยันตัวตนจะล้มเหลว
如果令牌无效,身份验证就会失败。
If the token is invalid, authentication fails.

Section Check 1

What exit code blocks an action?

Exit code อะไรบล็อกการดำเนินการ?

哪个退出码会拦截操作?

Section Check 2

Where are hooks configured?

Hooks ตั้งค่าที่ไหน?

Hooks 在哪里配置?

Section Check 3

Complete: ___ you save, the hook runs.

เติม: ___ you save, the hook runs.

填空:___ you save, the hook runs.

4. Tutorial Steps / ขั้นตอนการเรียนรู้ / 教程步骤

1
View existing hooks / ดู hooks ที่มีอยู่ / 查看现有的 hooks
Type /hooks to see all configured hooks and their events.

How to do it

  • Type /hooks to list every configured hook and the event it fires on.
  • Events include PreToolUse (before a tool runs) and PostToolUse (after).
  • Empty list? Normal — hooks are optional power tools.
2
Add a hook in settings / เพิ่ม hook ในการตั้งค่า / 在设置中添加 hook
Open ~/.claude/settings.json and add a hook under the 'hooks' key.

How to do it

  • Hooks live in ~/.claude/settings.json under the "hooks" key.
  • Each hook says: on this event, for these tools, run this command.
  • Easiest path: ask Claude — Add a hook that logs every file edit — it knows the exact format.
3
Create a PreToolUse hook / สร้าง PreToolUse hook / 创建 PreToolUse hook
Block dangerous commands by checking stdin before Bash runs.

How to do it

  • A PreToolUse hook runs before the tool. Your script receives the tool call as JSON on stdin.
  • If the script exits with code 2, the tool call is blocked.
  • Classic use: refuse dangerous commands like rm -rf before they ever run.
4
Create a PostToolUse hook / สร้าง PostToolUse hook / 创建 PostToolUse hook
Auto-format files after Edit or Write operations.

How to do it

  • A PostToolUse hook runs after the tool finishes.
  • Classic use: run a code formatter on every file Claude edits, so style is always consistent.
  • The hook gets the file path from the tool call JSON.
5
Test your hooks / ทดสอบ hooks / 测试你的 hooks
Trigger the event and check if your hook runs correctly.

How to do it

  • Trigger the event on purpose: ask Claude to edit a harmless file.
  • Then check the effect — did the log line appear? Was the file formatted?
  • Debugging tip: make the hook write to a file (echo ... >> hook.log) so you can see each run.

5. How a hook actually runs / hook ทำงานยังไงกันแน่ / Hook 的真实运行过程

A hook is a normal program that Claude Code runs at a fixed moment. The whole mechanism is four steps:

1
Claude asks to run a tool (say, Edit on app.py).
2
Claude Code checks your settings: is there a hook for this event whose matcher matches this tool? ("Edit|Write" is a regex — it matches both tools.)
3
Your command runs and receives the tool call as JSON on stdin:
{ "tool_name": "Edit", "tool_input": { "file_path": "C:/projects/demo/app.py" } }
4
Your command's exit code decides what happens next:
Exit codePreToolUsePostToolUse
0allow the toolall good
2block the tool — it never runssend feedback to Claude
otherhook failed — shown to you, but the tool continues

A hook to try today

This one appends every edited file's path to changes.log — a diary of what Claude touched. Add it to ~/.claude/settings.json:

{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "python -c \"import json,sys; d=json.load(sys.stdin); open('changes.log','a').write(d['tool_input'].get('file_path','?')+'\\n')\"" } ] } ] } }

Reading the command: python loads the JSON from stdin (json.load(sys.stdin)), pulls out tool_input.file_path, and appends it to the log file. Ask Claude to edit anything, then Read changes.log — your hook wrote a line. When it works, try the next level: change the event to PreToolUse and exit with code 2 to build a command-blocker.

6. Hands-On Activity / กิจกรรมลงมือทำ / 动手练习

แบบฝึกหัด: สร้าง PostToolUse hook ที่บันทึกทุกการแก้ไขไฟล์ลงในไฟล์ changes.log ทดสอบโดยขอให้ Claude แก้ไขไฟล์
练习:创建一个 PostToolUse hook,把每次文件编辑记录到 changes.log 文件里。让 Claude 编辑一个文件来测试它。
Practice: Create a PostToolUse hook that logs every file edit to a changes.log file. Test it by asking Claude to edit a file.

Step by step

  1. Ask Claude: Add a PostToolUse hook that appends the edited file path to changes.log.
  2. Review the settings.json change it proposes, then approve.
  3. Ask Claude to edit any file (add a comment somewhere).
  4. Say: Read changes.log.

✓ You did it right if: changes.log contains the path of the file that was just edited.

📜 A complete working hook (settings.json) / ตัวอย่างคำตอบ / 示例答案
// Save as: ~/.claude/settings.json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "python -c \"import json,sys; d=json.load(sys.stdin); open('changes.log','a').write(d['tool_input'].get('file_path','?')+'\\n')\""
          }
        ]
      }
    ]
  }
}

// How it works: after every Edit or Write, Claude Code runs the
// command and sends the tool call as JSON on stdin. The file path
// is in tool_input.file_path.

# ---- Test it ----
> add a comment to the top of app.py
* Edit(app.py) ... Allow? > y     (the hook fires silently after)
> Read changes.log
  1  app.py                       <- the hook logged your edit

7. Reference Table / ตารางอ้างอิง / 参考表

Command / ToolEnglishภาษาไทย中文
PreToolUseBefore a tool runsก่อนเครื่องมือทำงาน工具运行之前
PostToolUseAfter a tool succeedsหลังเครื่องมือทำงานสำเร็จ工具成功之后
SessionStartWhen a session beginsเมื่อเซสชันเริ่มต้น会话开始时
NotificationClaude needs attentionClaude ต้องการความสนใจClaude 需要你的注意
StopClaude finishes respondingClaude ตอบเสร็จClaude 完成回复

8. Interactive Lab / ห้องทดลอง / 互动实验室

Wire up a pre-hook and a post-hook, then try to sneak a dangerous command past them. / ลองตั้ง hooks แล้วดูมันทำงาน / 配置 hooks 并观察它们工作

Configure hooks, pick an action, press Run. Watch the pipeline decide.

9. Summary / สรุป / 总结

Hooks ทำให้การดำเนินการอัตโนมัติตามเหตุการณ์ PreToolUse บล็อกการดำเนินการ PostToolUse ทำงานหลังเครื่องมือ กำหนดค่าใน settings.json ประโยคเงื่อนไข (if/when) อธิบายตรรกะ hook
Hooks 在生命周期事件时自动执行操作。PreToolUse 拦截操作,PostToolUse 在工具之后运行。在 settings.json 中配置它们。条件句(if/when)描述 hook 的逻辑。
Hooks automate actions at lifecycle events. PreToolUse blocks actions, PostToolUse runs after tools. Configure them in settings.json. Conditional sentences (if/when) describe hook logic.

Homework / การบ้าน / 作业

1. สร้าง notification hook เมื่อ Claude ทำเสร็จ
2. เขียน PreToolUse hook ที่บล็อก 'rm -rf'
3. เขียน 5 ประโยคเงื่อนไขเกี่ยวกับระบบอัตโนมัติ
1. 创建一个在 Claude 完成时发通知的 hook。
2. 写一个拦截 'rm -rf' 的 PreToolUse hook。
3. 写 5 个关于自动化的条件句。
1. Create a notification hook for when Claude finishes.
2. Write a PreToolUse hook that blocks 'rm -rf'.
3. Write 5 conditional sentences about automation.