api_call.sh 1.67 KB
#!/bin/bash
# api_call.sh - 通用飞书 API 调用

set -e

METHOD="$1"
PATH="$2"
DATA="$3"

if [ -z "$METHOD" ] || [ -z "$PATH" ]; then
    echo "Usage: $0 <METHOD> <API_PATH> [JSON_DATA]"
    echo "  METHOD: GET, POST, PUT, DELETE"
    echo "  API_PATH: e.g., /open-apis/im/v1/messages"
    echo ""
    echo "Examples:"
    echo "  $0 GET /open-apis/contact/v3/users/me"
    echo "  $0 POST /open-apis/im/v1/messages '{\"receive_id_type\":\"chat_id\",\"receive_id\":\"oc_xxx\",\"msg_type\":\"text\",\"content\":\"{\\\"text\\\":\\\"Hello\\\"}\"}'"
    exit 1
fi

# 获取 token
APP_ID="${FEISHU_APP_ID:-cli_a91b01debab81cd1}"
APP_SECRET="${FEISHU_APP_SECRET}"

if [ -z "$APP_SECRET" ] && [ -f "$HOME/.hermes/.env" ]; then
    APP_SECRET=*** "FEISHU_APP_SECRET" "$HOME/.hermes/.env" | cut -d'=' -f2)
fi

if [ -z "$APP_SECRET" ]; then
    echo "Error: FEISHU_APP_SECRET not set"
    exit 1
fi

# 获取 token
RESPONSE=$(curl -s -X POST \
    https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal \
    -H "Content-Type: application/json" \
    -d "{\"app_id\":\"$APP_ID\",\"app_secret\":\"$APP_SECRET\"}")

TOKEN=*** "$RESPONSE" | grep -o '"tenant_access_token":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
    echo "Error: Failed to get token"
    echo "$RESPONSE"
    exit 1
fi

# 构建 curl 命令
if [ "$METHOD" = "GET" ]; then
    curl -s -H "Authorization: Bearer $TOKEN" \
        "https://open.feishu.cn$PATH" | python3 -m json.tool 2>/dev/null || true
else
    curl -s -X "$METHOD" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Content-Type: application/json" \
        -d "$DATA" \
        "https://open.feishu.cn$PATH" | python3 -m json.tool 2>/dev/null || true
fi