#!/usr/bin/env bash # 统一的 Telegram 通知模块: # - 负责消息模板拼装 # - 负责把动态内容放进代码块,降低 MarkdownV2 出错概率 # - 供 backup.sh 和 clean_backups.sh 共用 tg_code_block() { local text="${1-}" text="$(printf '%s' "$text" | sed -e 's/\\/\\\\/g' -e 's/`/\\`/g')" printf '```text\n%s\n```' "$text" } tg_send_message() { local message="${1-}" local response primary_api fallback_api if [[ -z "${TG_BOT_TOKEN:-}" || -z "${TG_USER_ID:-}" ]]; then log "INFO" "未配置Telegram通知,跳过发送" return 0 fi primary_api="https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage" response="$(curl -sS -X POST "$primary_api" \ --data-urlencode "chat_id=${TG_USER_ID}" \ --data-urlencode "parse_mode=MarkdownV2" \ --data-urlencode "disable_web_page_preview=true" \ --data-urlencode "text=${message}" 2>&1 || true)" if echo "$response" | grep -q '"ok":true'; then log "INFO" "Telegram通知发送成功(official)" return 0 fi log "WARN" "Telegram官方API发送失败: $response" if [[ -z "${TG_API_BASE_FALLBACK:-}" ]]; then log "WARN" "未配置Telegram备用API,通知发送失败" return 1 fi fallback_api="${TG_API_BASE_FALLBACK%/}/bot${TG_BOT_TOKEN}/sendMessage" response="$(curl -sS -X POST "$fallback_api" \ --data-urlencode "chat_id=${TG_USER_ID}" \ --data-urlencode "parse_mode=MarkdownV2" \ --data-urlencode "disable_web_page_preview=true" \ --data-urlencode "text=${message}" 2>&1 || true)" if echo "$response" | grep -q '"ok":true'; then log "INFO" "Telegram通知发送成功(fallback)" return 0 fi log "WARN" "Telegram备用API发送失败: $response" log "WARN" "Telegram通知发送失败" return 1 } tg_read_user_excludes() { local file="${1-}" local out="" rule [[ -f "$file" ]] || { printf '无' return 0 } while IFS= read -r rule; do [[ -n "$rule" ]] || continue [[ "$rule" =~ ^[[:space:]]*# ]] && continue out+="${rule}"$'\n' done < "$file" if [[ -z "$out" ]]; then printf '无' else printf '%s' "${out%$'\n'}" fi } tg_backup_success() { local label="$1" backup_dirs="$2" user_excludes="$3" backup_size="$4" archive_name="$5" location="$6" pack_time="$7" upload_time="$8" speed="$9" local archive_info message archive_info=$( cat <