#!/bin/bash # Telegram 通知模块 # 提供 Telegram Bot 消息发送和文件上传功能 # # ⚠️ 重要提示: # 所有配置项必须从 Jenkinsfile 的 environment 部分传入(通过 credentials) # 此脚本不包含任何硬编码配置,确保配置集中管理 # # 必需的环境变量(通过 Jenkins credentials 注入): # - TELEGRAM_BOT_TOKEN: Telegram Bot Token # - TELEGRAM_CHAT_ID: Telegram Chat ID # 验证必需的环境变量 if [ -z "${TELEGRAM_BOT_TOKEN}" ] || [ -z "${TELEGRAM_CHAT_ID}" ]; then echo "警告: Telegram 配置未设置,Telegram 通知功能将被禁用" >&2 echo "如需启用,请在 Jenkinsfile 中使用 withCredentials 注入 TELEGRAM_BOT_TOKEN 和 TELEGRAM_CHAT_ID" >&2 # 不退出,允许脚本继续运行(Telegram 是可选的) fi # 发送 Telegram 消息的函数 send_telegram_message() { local message="$1" # 检查配置是否可用 if [ -z "${TELEGRAM_BOT_TOKEN}" ] || [ -z "${TELEGRAM_CHAT_ID}" ]; then if [ "$(type -t log_message)" = "function" ]; then log_message "警告: Telegram 配置未设置,跳过通知" fi return 0 fi if [ "$(type -t log_message)" = "function" ]; then log_message "Telegram通知: $message" fi curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \ -H "Content-Type: application/json; charset=utf-8" \ -d "$(echo -n "{\"chat_id\":\"${TELEGRAM_CHAT_ID}\",\"text\":\"${message}\",\"parse_mode\":\"HTML\"}" | iconv -f UTF-8 -t UTF-8)" } # 发送文件到 Telegram 的函数 send_telegram_file() { local file="$1" local caption="$2" # 检查配置是否可用 if [ -z "${TELEGRAM_BOT_TOKEN}" ] || [ -z "${TELEGRAM_CHAT_ID}" ]; then if [ "$(type -t log_message)" = "function" ]; then log_message "警告: Telegram 配置未设置,跳过文件上传" fi return 0 fi if [ "$(type -t log_message)" = "function" ]; then log_message "发送日志文件到Telegram: $caption" fi curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendDocument" \ -H "Content-Type: multipart/form-data; charset=utf-8" \ -F "chat_id=${TELEGRAM_CHAT_ID}" \ -F "document=@$file" \ -F "caption=$caption" } # 更新进度条的函数 update_progress() { local percent=$1 local step_name="$2" local progress_bar="" local filled=$((percent / 10)) local empty=$((10 - filled)) # 构建进度条 for ((i=0; i