如何用 Stop hook 和 ntfy 讓 Claude Code 每次回覆完成後通知手機
Making Claude Code Send Notifications to My Phone: A Stop Hook and ntfy
作者為 Claude Code 設定 Stop hook,讓每次回覆完成後都透過 ntfy 向手機發送通知。通知核心是與特定 AI 服務無關的獨立腳本,只傳送一條固定訊息;點按通知可開啟對應對話,但須啟用 Remote Control。作者在 Mac 和 iPhone 上測試,測試通知與 hook 自動通知均成功送達。
What I did
I set up Claude Code so that a notification reaches my phone every time a reply finishes. It uses a Stop hook (which runs automatically every time a reply finishes) and the ntfy notification service. The part that sends the notification is a standalone script that does not depend on a specific AI service; the only Claude Code-specific part is a thin entry point. It works while I am looking at the screen, and tapping the notification opens that conversation in the Claude mobile app.
This post covers: (1) the problem with letting the AI send it, (2) the idea (a Stop hook and the ntfy notification service), (3) the full code, and (4) how it worked out and what to watch out for.
Earlier post (the same idea, a different example): https://dev.to/sora_uzu/my-ai-skips-written-rules-so-i-turned-one-into-a-check-a-write-time-guard-hook-38ml
The problem: I let the AI send the notification
At first, the AI called a PushNotification tool (built into Claude Code) to send a notification to my phone, as a written rule. It had problems:
- If the AI does not call it, nothing is sent. Even as a written rule, it forgot on some days.
- It does not send while I am looking at the screen. That is how the tool works. What I wanted was for it to reach my phone regardless of whether I was looking at my PC screen.
- Calling a tool every time made replies slower.
I also could not find a built-in setting for "notify my phone on every reply". The common approach turned out to be sending it from a Stop hook to an external notification service [6].
The idea: don't depend on a specific AI service
The premise is that the notification mechanism should not depend on a specific AI service: if I switch AI tools, the core should keep working. Also, a rule that gets forgotten should not rely on the AI; build it into the system (the same idea as my previous post).
| Part | Role |
|---|---|
| Stop hook | Claude Code runs it automatically every time a reply finishes [1] |
| The core (a standalone script) | Sends one fixed sentence to the ntfy notification service. It does not depend on a specific AI service |
| ntfy.sh (free) | Delivers a push notification to the ntfy app on my iPhone [2][3] |
Four principles:
- The core is a standalone script. The only Claude Code-specific part is a thin entry point (the hook) that just calls it. If I switch AI tools, the core stays.
- Only one fixed sentence leaves the machine. No personal content (health, money, schedule) goes to the notification service.
- The destination name (the topic) is a secret. Anyone who knows it can receive and send, so it is a long random name in a git-ignored file.
- A failure never stops the hook. It always exits normally, so a failed notification cannot interrupt the AI.
What I built
The script that sends the notification
#!/usr/bin/env python3
import os, sys, urllib.request
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOPIC_FILE = os.environ.get("NOTIFY_TOPIC_FILE") or os.path.join(ROOT, "private", "notify-topic.txt")
DEFAULT_MESSAGE = "Replied. Please check."
TITLE = os.environ.get("NOTIFY_TITLE", "Personal AI") # heading (ASCII, to avoid garbled text)
def send(message=DEFAULT_MESSAGE, click=None):
try:
topic = open(TOPIC_FILE, encoding="utf-8").read().strip()
if not topic:
return False
headers = {"Priority": "default", "Tags": "speech_balloon", "Title": TITLE}
if click:
headers["Click"] = click # URL to open when the notification is tapped
req = urllib.request.Request("https://ntfy.sh/" + topic,
data=message.encode("utf-8"), headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=8) as r:
return 200 <= r.status < 300
except Exception:
return False # fail quietly
if __name__ == "__main__":
ok = send(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_MESSAGE,
sys.argv[2] if len(sys.argv) > 2 else None)
print("sent" if ok else "not sent")
sys.exit(0) # always exit normally
Put the topic name on one line in private/notify-topic.txt (git-ignored).
The Stop hook entry point (and how to register it)
The hook receives JSON on stdin. From its session_id, it builds a link that opens that session when the notification is tapped [1][4].
#!/usr/bin/env python3
import json, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
raw = sys.stdin.read()
data = json.loads(raw) if raw.strip() else {}
sid = str(data.get("session_id") or "").strip()
import notify
# claude://code/{session-id} opens that conversation in the Claude mobile app
notify.send(click=("claude://code/" + sid) if sid else "claude://code")
except Exception:
pass
sys.exit(0) # always exit normally
Register it in .claude/settings.json [1]:
{
"hooks": {
"Stop": [
{
"hooks": [
{ "type": "command", "command": "python3 \"${CLAUDE_PROJECT_DIR}/scripts/hooks_stop_notify.py\"" }
]
}
]
}
}
Setting up the iPhone
Install the free "ntfy" app from the App Store and subscribe to the secret topic name.
How it worked out
- A test notification and the hook's automatic notifications arrived on my iPhone.
-
Tapping the notification opened that conversation. The
session_idthe hook receives matched the session ID in the Claude mobile app. - The notification heading (
Title) worked too.
Things to watch out for
- If the topic name leaks, others can receive and send. Keep it secret and never post it in articles or social media. Only one fixed sentence is sent, so a leak would not reveal content.
- A notification arrives on every reply, even for short exchanges. I have not added any filtering.
- Tapping to open the session works when Remote Control is enabled.
- It depends on an external service (ntfy.sh). If the server is down, nothing arrives. You can also self-host (I have not tried).
- I only tried a Mac with an iPhone.
Summary
- The "forgot to call it" problem went away when I stopped asking the AI and made it a hook.
- Keep the core as a standalone script that does not depend on an AI service, and keep the hook as just an entry point.
- Send only one fixed sentence to the outside, and keep the destination name secret.
References
[1] Claude Code, Hooks reference: https://code.claude.com/docs/en/hooks
[2] ntfy, Publishing (Click, Title and other headers): https://docs.ntfy.sh/publish
[3] ntfy, Subscribe from your phone: https://docs.ntfy.sh/subscribe/phone
[4] Claude, Open the Claude mobile app with a link (claude://code/{session-id}): https://support.claude.com/en/articles/14898120-open-the-claude-mobile-app-with-a-link
[5] Claude Code, Remote Control: https://code.claude.com/docs/en/remote-control
[6] A discussion about per-reply notifications: https://github.com/anthropics/claude-code/issues/28765
Japanese version on Zenn: https://zenn.dev/uzunaru/articles/412dbf004d4fa3
來源:DEV Community · dev.to
