ai_member_xiaoxi/scripts/write_id_results.py
2026-05-28 08:00:01 +08:00

71 lines
2.2 KiB
Python

#!/usr/bin/env python3
"""
将手机号→ID匹配结果写回飞书表格
"""
import json
import requests
import os
import sys
SPREADSHEET_TOKEN = "RFIJsXT8FhGHhctY4RwczcOfnac"
SHEET_ID = "2DOxEI"
CRED_DIR = "/root/.openclaw/credentials/xiaoxi"
def get_token():
with open(os.path.join(CRED_DIR, "config.json")) as f:
cfg = json.load(f)
app_id = cfg['apps'][0]['appId']
app_secret = cfg['apps'][0]['appSecret']
resp = requests.post("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal",
json={"app_id": app_id, "app_secret": app_secret})
return resp.json()['tenant_access_token']
def write_values(token, range_str, values):
"""Write values to sheet using PUT /sheets/v2/spreadsheets/{token}/values"""
url = f"https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{SPREADSHEET_TOKEN}/values"
body = {
"valueRange": {
"range": f"{SHEET_ID}!{range_str}",
"values": values
}
}
resp = requests.put(url, headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}, json=body)
result = resp.json()
if result.get('code') != 0:
print(f"ERROR writing {range_str}: {result}")
return False
return True
def main():
with open('/tmp/sheet_id_results.json') as f:
data = json.load(f)
results = data['results']
results.sort(key=lambda x: x['row_idx'])
print(f"Writing {len(results)} rows to sheet...")
# Prepare values: each row is [user_id, status, update_time]
values = [[r['user_id'], r['status'], r['update_time']] for r in results]
token = get_token()
print("Token obtained")
# Write in batches of 850 at a time (API seems to support large writes)
# Range: F2:H851 (row 2 to row 1+850)
range_str = f"F2:H{1+len(values)}"
print(f"Writing range: {range_str}")
if write_values(token, range_str, values):
print(f"SUCCESS: Wrote {len(values)} rows of ID results")
print(f"Stats: matched={data['stats']['matched']}, unmatched={data['stats']['unmatched']}")
else:
print("FAILED")
sys.exit(1)
if __name__ == "__main__":
main()