send_image.sh
2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/bin/bash
# send_image.sh - 发送图片到飞书群聊
set -e
CHAT_ID="$1"
IMAGE_PATH="$2"
if [ -z "$CHAT_ID" ] || [ -z "$IMAGE_PATH" ]; then
echo "Usage: $0 <chat_id> <image_path>"
exit 1
fi
if [ ! -f "$IMAGE_PATH" ]; then
echo "Error: Image file not found: $IMAGE_PATH"
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=$(grep "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=$(echo "$RESPONSE" | grep -o '"tenant_access_token":"[^"]*"' | cut -d'"' -f4)
if [ -z "$TOKEN" ]; then
echo "Error: Failed to get token"
echo "$RESPONSE"
exit 1
fi
# 上传图片
echo "Uploading image..."
UPLOAD_RESPONSE=$(curl -s -X POST \
"https://open.feishu.cn/open-apis/im/v1/images" \
-H "Authorization: Bearer $TOKEN" \
-F "image=@$IMAGE_PATH" \
-F "image_type=message")
# 使用 Python 解析响应
python3 -c "
import json
import urllib.request
import sys
upload_result = json.loads('$UPLOAD_RESPONSE')
if upload_result.get('code') != 0:
print(f'Upload failed: {upload_result}')
sys.exit(1)
image_key = upload_result['data']['image_key']
print(f'Image uploaded, key: {image_key}')
# 构建图片消息内容
content = json.dumps({'image_key': image_key})
# 构建请求体
request_body = {
'receive_id': '$CHAT_ID',
'msg_type': 'image',
'content': content
}
# 发送图片消息
req = urllib.request.Request(
'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id',
data=json.dumps(request_body).encode('utf-8'),
headers={
'Authorization': 'Bearer $TOKEN',
'Content-Type': 'application/json'
},
method='POST'
)
try:
with urllib.request.urlopen(req, timeout=30) as response:
result = json.loads(response.read().decode('utf-8'))
print(json.dumps(result, indent=2, ensure_ascii=False))
if result.get('code') == 0:
print('Image sent successfully!')
else:
print(f'Error: {result.get(\"msg\")}')
except Exception as e:
print(f'Error: {e}')
"