Files
Lark-Snooper/larkx/media.py
thxzzzzz b9c2d50d62 feat: support Lark (larksuite.com) alongside Feishu
Add larkx/region.py with per-region endpoints, gateway app id and
locale. The region is chosen at login (lark auth qr/import --region,
default LARKX_REGION) and persisted in credentials; every request derives
its URLs from it. Credentials saved before this change are treated as
Feishu.

Fixes found while testing with real Lark and Feishu accounts:
- search: locale belongs on the request header, not searchContext
- storage: drop inline thumbnail bytes so content_data stays valid JSON
- send --root: set parentId, plus isReplyInThread for regular groups;
  topic-mode groups reject that flag, so chat modes are looked up and
  cached per chat
- topic groups (GROUP + chatMode THREAD/THREAD_V2): root messages anchor
  their own thread, except system notices; push handling and
  pull_history share decoders.resolve_scope
- show media/audio durations in seconds (they are milliseconds)
- render @mentions with the mentioned name via AtProperty
- lark send stores the server message id so the WS echo fills in the
  same row instead of inserting a duplicate

proto.proto gains isReplyInThread, AtProperty and PutMessageResponse;
proto_pb2.py is regenerated with grpcio-tools 1.71 (protoc 5.29.0).
2026-09-30 16:04:49 +08:00

58 lines
2.2 KiB
Python

import os
import requests
from loguru import logger
from .auth import LarkAuth
from .config import load_config
from .region import get_region
def message_resource_url(msg_id: str, key: str, chat_id: str, host: str=None) -> str:
"""host 为所属区域的文件主机(LarkAuth.region.file_host),不传时取 LARKX_REGION。"""
host = host or get_region(load_config()['region']).file_host
return f'{host}/download/messages/{msg_id}/keys/{key}?chat_id={chat_id}'
def extract_resource_key(msg_type: int, content_data: dict) -> str:
if not content_data:
return ''
if msg_type == 5:
v2 = content_data.get('imageV2') or {}
if v2.get('imageKey'):
return v2['imageKey']
img = (content_data.get('image') or {}).get('origin') or {}
return img.get('key') or (content_data.get('image') or {}).get('imageKey', '')
if msg_type in (3, 15, 7, 10):
return content_data.get('key', '')
return ''
def download(auth: LarkAuth, url: str, out_path: str=None, max_bytes: int=200 * 1024 * 1024):
with requests.get(url, cookies=auth.cookies, timeout=60, stream=True) as r:
r.raise_for_status()
content_type = r.headers.get('content-type', '')
if not out_path:
buf = b''
for chunk in r.iter_content(1 << 16):
buf += chunk
if len(buf) > max_bytes:
raise ValueError('文件过大')
return (buf, content_type)
n = 0
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
with open(out_path, 'wb') as f:
for chunk in r.iter_content(1 << 16):
f.write(chunk)
n += len(chunk)
if n > max_bytes:
raise ValueError('文件过大')
return (out_path, content_type, n)
def download_message_resource(auth: LarkAuth, msg: dict, out_path: str=None):
key = extract_resource_key(msg.get('msg_type', 0), msg.get('content_data') or {})
if not key:
raise ValueError('该消息没有可下载的资源')
url = message_resource_url(msg['msg_id'], key, msg['chat_id'], host=auth.region.file_host)
logger.info(f'下载资源: {url}')
return download(auth, url, out_path)