用 Keyboard Maestro 快速读取新通知中的验证码

从 macOS 15 开始,系统支持在 Chrome 等浏览器中自动填充验证码,但该功能仅限于从系统自带的「信息」和「邮件」App 中提取。如果你使用 Spark、Outlook 等第三方邮件客户端,则无法享受此便利。

因此,我用做了一个小插件,快速读取新通知中的验证码。这样就能兼容几乎所有第三方邮件客户端和社交软件。其流程为:

  • 自动识别验证码弹窗区域,静默截图;
  • 将截图上传至 OpenAI gpt-4o-mini,通过多模态识别精准提取数字。
  • 自动剔除格式杂质并存入剪切板;
  • 触发 macOS 原生系统通知。

以下是完整代码,可以通过 Keyboard Maestro 或 Alfred 等软件触发。我使用KM,这是脚本下载地址:DayuGuo/Copy-OTP-from-notification

#!/bin/zsh

# --- 配置区 ---
API_KEY="你的 Api"

# --- 1. 动态获取屏幕宽度 (适配 14/16寸/外显) ---
SCREEN_INFO=$(osascript -e 'tell application "Finder" to get bounds of window of desktop')
SCREEN_W=$(echo $SCREEN_INFO | awk -F', ' '{print $3}')

# --- 2. 计算截图区域 (右侧 28% 宽度, 避开菜单栏) ---
CAPTURE_W=$((SCREEN_W * 0.28))
CAPTURE_X=$((SCREEN_W - CAPTURE_W))
CAPTURE_Y=45
CAPTURE_H=300

# 执行静默截图
/usr/sbin/screencapture -x -R "$CAPTURE_X,$CAPTURE_Y,$CAPTURE_W,$CAPTURE_H" "$TEMP_IMAGE"

# --- 3. 调用 AI 处理 ---
if [[ -f "$TEMP_IMAGE" ]]; then
    BASE64_IMAGE=$(base64 -i "$TEMP_IMAGE")

    RESPONSE=$(curl -s https://api.openai.com/v1/chat/completions \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $API_KEY" \
      -d '{
        "model": "gpt-4o-mini",
        "messages": [
          {"role": "user", "content": [
            {"type": "text", "text": "Extract the verification code. Output ONLY digits. If none, say NONE."},
            {"type": "image_url", "image_url": {"url": "data:image/png;base64,'$BASE64_IMAGE'"}}
          ]}
        ],
        "max_tokens": 10
      }' | grep -oE '"content": "[^"]+"' | cut -d'"' -f4)

    # --- 4. 结果处理 (自动复制 + 系统通知) ---
    if [[ "$RESPONSE" != "NONE" && -n "$RESPONSE" ]]; then
        # 核心:使用 printf 确保剪贴板纯净
        printf "$RESPONSE" | pbcopy
        # 使用系统原生通知显示验证码内容
        osascript -e "display notification \"$RESPONSE\" with title \"验证码已复制\""
    else
        osascript -e "display notification \"未检测到验证码\" with title \"识别失败\""
    fi

    # 清理
    rm "$TEMP_IMAGE"
else
    osascript -e "display notification \"请检查屏幕录制权限\" with title \"截图失败\""
fi

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注