upload_and_send.py 4.41 KB
#!/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()