upload_and_send.py
4.41 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#!/usr/bin/env python3
"""upload_and_send.py — Upload a file to Feishu and send to a user/chat.
Usage:
python3 upload_and_send.py <file_path> <receive_id> [receive_id_type]
python3 upload_and_send.py /tmp/report.zip ou_xxxxxx
python3 upload_and_send.py /tmp/report.zip oc_xxxxxx chat_id
Requires FEISHU_APP_ID and FEISHU_APP_SECRET in environment.
"""
import json
import os
import sys
import urllib.request
def get_token(app_id, app_secret):
data = json.dumps({"app_id": app_id, "app_secret": app_secret}).encode()
req = urllib.request.Request(
"https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=15) as r:
return json.loads(r.read())["tenant_access_token"]
def upload_file(token, file_path):
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
print(f"Uploading {file_name} ({file_size} bytes)...")
with open(file_path, "rb") as f:
file_data = f.read()
boundary = "----FormBoundary7MA4YWxkTrZu0gW"
body = (
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file_name"\r\n\r\n{file_name}\r\n'
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file_type"\r\n\r\nstream\r\n'
f"--{boundary}\r\n"
f'Content-Disposition: form-data; name="file"; filename="{file_name}"\r\n'
f"Content-Type: application/octet-stream\r\n\r\n"
).encode() + file_data + f"\r\n--{boundary}--\r\n".encode()
req = urllib.request.Request(
"https://open.feishu.cn/open-apis/im/v1/files",
data=body,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": f"multipart/form-data; boundary={boundary}",
},
method="POST",
)
with urllib.request.urlopen(req, timeout=60) as r:
result = json.loads(r.read())
if result.get("code") != 0:
print(f"Upload failed: {result}")
sys.exit(1)
file_key = result["data"]["file_key"]
print(f"Uploaded: file_key={file_key}")
return file_key
def send_file(token, file_key, receive_id, receive_id_type="open_id"):
content = json.dumps({"file_key": file_key})
msg_data = json.dumps({
"receive_id": receive_id,
"msg_type": "file",
"content": content,
}).encode()
req = urllib.request.Request(
f"https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type={receive_id_type}",
data=msg_data,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
},
method="POST",
)
with urllib.request.urlopen(req, timeout=15) as r:
result = json.loads(r.read())
if result.get("code") != 0:
print(f"Send failed: {result}")
sys.exit(1)
print(f"Sent: message_id={result['data']['message_id']}")
return result["data"]
def main():
if len(sys.argv) < 3:
print("Usage: upload_and_send.py <file_path> <receive_id> [receive_id_type]")
print(" receive_id_type: open_id (default) or chat_id")
sys.exit(1)
file_path = sys.argv[1]
receive_id = sys.argv[2]
receive_id_type = sys.argv[3] if len(sys.argv) > 3 else "open_id"
if not os.path.exists(file_path):
print(f"File not found: {file_path}")
sys.exit(1)
# Read credentials from env (set by Hermes gateway)
app_id = os.environ.get("FEISHU_APP_ID", "")
app_secret = os.environ.get("FEISHU_APP_SECRET", "")
if not app_id or not app_secret:
# Fallback: read from .env file
env_path = os.path.expanduser("~/.hermes/.env")
if os.path.exists(env_path):
with open(env_path) as f:
for line in f:
if line.startswith("FEISHU_APP_ID="):
app_id = line.split("=", 1)[1].strip()
elif line.startswith("FEISHU_APP_SECRET="):
app_secret = line.split("=", 1)[1].strip()
if not app_id or not app_secret:
print("Error: FEISHU_APP_ID and FEISHU_APP_SECRET not set")
sys.exit(1)
token = get_token(app_id, app_secret)
file_key = upload_file(token, file_path)
send_file(token, file_key, receive_id, receive_id_type)
print("Done.")
if __name__ == "__main__":
main()