Files
bin-scripts/glm-quota
T
2026-04-19 21:43:13 +07:00

91 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# glm-quota — Check Zhipu AI (GLM) API quota
#
# Usage:
# glm-quota # show quota
# glm-quota -v # show raw JSON response
#
# Setup API key (Keychain):
# security add-generic-password -a "$USER" -s GLM_API_KEY -w "YOUR_API_KEY"
KEY_NAME="GLM_API_KEY"
URL="https://open.bigmodel.cn/api/monitor/usage/quota/limit"
# ===== COLORS =====
GREEN="\033[1;32m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
RED="\033[1;31m"
DIM="\033[2m"
RESET="\033[0m"
# ===== ARGS =====
VERBOSE=0
[[ "$1" == "-v" ]] && VERBOSE=1
# ===== LOAD TOKEN =====
API_TOKEN=$(security find-generic-password -a "$USER" -s "$KEY_NAME" -w 2>/dev/null | tr -d '\n')
if [ -z "$API_TOKEN" ]; then
echo -e "${RED}❌ API token not found in Keychain ($KEY_NAME)${RESET}"
exit 1
fi
# ===== CALL API =====
RESPONSE=$(curl -s -H "Authorization: $API_TOKEN" "$URL")
if [ "$VERBOSE" -eq 1 ]; then
echo -e "${YELLOW}🔧 Raw response:${RESET}"
echo "$RESPONSE" | jq .
echo ""
fi
# ===== PARSE =====
SUCCESS=$(echo "$RESPONSE" | jq -r '.success // false')
if [ "$SUCCESS" != "true" ]; then
echo -e "${RED}❌ API request failed${RESET}"
echo "$RESPONSE" | jq .
exit 1
fi
LEVEL=$(echo "$RESPONSE" | jq -r '.data.level // "unknown"')
# Extract TOKENS_LIMIT using jq in one shot
read -r T_PERCENT T_RESET T_NUM < <(echo "$RESPONSE" | jq -r '
.data.limits[] | select(.type == "TOKENS_LIMIT") |
"\(.percentage // 0) \(.nextResetTime // 0) \(.number // 5)"
')
# Extract TIME_LIMIT (web search) in one shot
read -r R_USAGE R_CURRENT R_REMAINING R_PERCENT R_RESET < <(echo "$RESPONSE" | jq -r '
.data.limits[] | select(.type == "TIME_LIMIT") |
"\(.usage // 0) \(.currentValue // 0) \(.remaining // 0) \(.percentage // 0) \(.nextResetTime // 0)"
')
# Convert millisecond timestamps to human readable
format_ms() {
local ms="$1"
if [ -n "$ms" ] && [ "$ms" -gt 0 ] 2>/dev/null; then
date -r $((ms / 1000)) "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "$ms"
else
echo "N/A"
fi
}
T_RESET_HUMAN=$(format_ms "$T_RESET")
R_RESET_HUMAN=$(format_ms "$R_RESET")
# ===== DISPLAY =====
echo -e "${GREEN}✅ GLM Quota ${DIM}(account: ${LEVEL})${RESET}"
# -- Token Limit (main) --
echo -e "\n${CYAN}[Token Limit — ${T_NUM}h rolling]${RESET}"
echo -e " Usage: ${YELLOW}${T_PERCENT}%${RESET}"
echo " Next Reset: $T_RESET_HUMAN"
# -- Web Search Limit (secondary) --
if [ -n "$R_USAGE" ] && [ "$R_USAGE" != "0" ]; then
echo -e "\n${DIM}[Web Search Limit — monthly]${RESET}"
echo -e " ${DIM}Used: ${R_CURRENT}/${R_USAGE} (${R_PERCENT}%) | Reset: ${R_RESET_HUMAN}${RESET}"
fi