微信群机器人-备份文件发送通知

#!/bin/bash

配置文件路径(与企业微信配置分离)

CONFIG_FILE="(dirname "0")/git_pull_config.env"

加载配置文件

if -f "$CONFIG_FILE" ; then

source "$CONFIG_FILE"

else

WX_ROBOT_URL="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx" # 默认不发送通知

fi

获取脚本所在目录的绝对路径

repos_path="(cd "(dirname "$0")" && pwd)"

初始化统计变量(避免子 Shell 作用域问题)

declare -i total_repos=0 success_count=0 error_count=0

declare -a error_messages=()

关键修复:使用进程替换避免子 Shell 变量丢失

while IFS= read -r gitdir; do

((total_repos++))

project_dir=(dirname "gitdir")

echo -e "\n START 同步仓库: $project_dir"

执行 git pull 并捕获输出

exec_output=(cd "project_dir" && git pull 2>&1)

exec_status=$?

记录执行结果

if $exec_status -eq 0 ; then

((success_count++))

else

((error_count++))

error_messages+=("【失败】project_dir\\n\{exec_output}</pre>")

fi

done < <(find "$repos_path" -type d -name .git) # 使用进程替换

构建企业微信通知内容

build_notification() {

local status_icon="✅"

$error_count -gt 0 && status_icon="⚠️"

cat <<EOF

**Git 同步完成通知** ${status_icon}

> **同步时间**: $(date "+%Y-%m-%d %H:%M:%S")

> **扫描目录**: \`${repos_path}\`

> **仓库总数**: ${total_repos}

> **成功数量**: ${success_count}

> **失败数量**: ${error_count}

EOF

$error_count -gt 0 && echo -e "\n**失败详情**:\n{error_messages\[@\]//'\n'/\\n}"

}

发送企业微信通知(支持 Markdown)

send_wx_notification() {

local content=$(build_notification | jq -Rs .)

local json_payload=$(cat <<EOF

{

"msgtype": "markdown",

"markdown": {

"content": ${content}

}

}

EOF

)

curl -sSL \

-H "Content-Type: application/json" \

-d "${json_payload}" \

"${WX_ROBOT_URL}" | jq -r '.errmsg // "未知错误"'

}

执行通知(当配置有效时)

if \[ -n "$WX_ROBOT_URL" \&\& "$WX_ROBOT_URL" == \*qyapi.weixin.qq.com\* ]; then

echo -e "\n🔄 正在发送企业微信通知..."

result=$(send_wx_notification)

"$result" == "ok" && echo "✅ 通知发送成功" || echo "❌ 通知发送失败: $result"

else

echo -e "\n⚠️ 未配置有效企业微信机器人,跳过通知"

fi

echo -e "\n🏁 所有操作已完成"

相关推荐
柒号华仔1 小时前
「速通Shell」聚砖成墙,Shell函数封装之道
linux·ssh·bash
ITyunwei09873 小时前
内存溢出报错,实战处理记录
运维·服务器·企业微信
互联网中的一颗神经元8 小时前
ZZ — Git 速查表
大数据·git·elasticsearch
早安试言10 小时前
git使用
git
燐妤10 小时前
梦绘片场 ProjectDream故事总纲场景剧本篇:从项目到成片的 AI 漫剧工作台
人工智能·git·ai·项目开发
JackieDYH18 小时前
Git 与 GitHub 新电脑配置指南(从零开始)
git·github·工具·使用教程
梦想的旅途221 小时前
企业微信 API 二次开发:AI 智能体与外部群业务流闭环
人工智能·microsoft·企业微信
梦想的旅途21 天前
企业微信 API 二次开发:AI 智能体接入外部群架构
人工智能·企业微信
梦想的旅途21 天前
企业微信 API 二次开发:外部群消息异步队列
企业微信
梦想的旅途21 天前
企微 API 二次开发:利用 AI Agent 实现自动化运维
运维·人工智能·企业微信