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).
This commit is contained in:
@ -1,6 +1,5 @@
|
||||
from . import proto_pb2 as P
|
||||
from .ids import generate_request_cid
|
||||
GATEWAY_URL = 'https://internal-api-lark-api.feishu.cn/im/gateway/'
|
||||
|
||||
|
||||
def wrap_packet(cmd: int, payload_msg, request_id: str) -> P.Packet:
|
||||
@ -12,7 +11,7 @@ def wrap_packet(cmd: int, payload_msg, request_id: str) -> P.Packet:
|
||||
return pkt
|
||||
|
||||
|
||||
def build_send_message_packet(text: str, chat_id: str, request_id: str, root_id: str=None) -> P.Packet:
|
||||
def build_send_message_packet(text: str, chat_id: str, request_id: str, root_id: str=None, thread_chat: bool=False) -> P.Packet:
|
||||
cid_1 = generate_request_cid()
|
||||
cid_2 = generate_request_cid()
|
||||
req = P.PutMessageRequest()
|
||||
@ -23,6 +22,10 @@ def build_send_message_packet(text: str, chat_id: str, request_id: str, root_id:
|
||||
req.version = 1
|
||||
if root_id:
|
||||
req.rootId = str(root_id)
|
||||
req.parentId = str(root_id)
|
||||
# 普通群缺 isReplyInThread 会落进主会话;话题群反而拒收它(replyInThread not support chat)
|
||||
if not thread_chat:
|
||||
req.isReplyInThread = True
|
||||
req.content.richText.elementIds.append(cid_2)
|
||||
req.content.richText.innerText = text
|
||||
req.content.richText.elements.dictionary[cid_2].tag = 1
|
||||
@ -39,7 +42,7 @@ def build_create_chat_packet(user_id: str, request_id: str) -> P.Packet:
|
||||
return wrap_packet(13, req, request_id)
|
||||
|
||||
|
||||
def build_search_packet(query: str, request_id: str) -> P.Packet:
|
||||
def build_search_packet(query: str, request_id: str, locale: str='zh_CN') -> P.Packet:
|
||||
req = P.UniversalSearchRequest()
|
||||
req.header.searchSession = generate_request_cid()
|
||||
req.header.sessionSeqId = 1
|
||||
@ -62,7 +65,7 @@ def build_search_packet(query: str, request_id: str) -> P.Packet:
|
||||
req.header.searchContext.entityItems.append(item4)
|
||||
req.header.searchContext.commonFilter.includeOuterTenant = 1
|
||||
req.header.searchContext.sourceKey = 'messenger'
|
||||
req.header.searchContext.locale = 'zh_CN'
|
||||
req.header.locale = locale
|
||||
req.header.extraParam.CopyFrom(P.SearchExtraParam())
|
||||
return wrap_packet(11021, req, request_id)
|
||||
|
||||
@ -81,6 +84,14 @@ def build_group_info_packet(chat_id: str, request_id: str) -> P.Packet:
|
||||
return wrap_packet(64, req, request_id)
|
||||
|
||||
|
||||
def decode_put_message_response(content: bytes) -> str:
|
||||
pkt = P.Packet()
|
||||
pkt.ParseFromString(content)
|
||||
resp = P.PutMessageResponse()
|
||||
resp.ParseFromString(pkt.payload)
|
||||
return resp.message.id
|
||||
|
||||
|
||||
def decode_put_chat_response(content: bytes):
|
||||
pkt = P.Packet()
|
||||
pkt.ParseFromString(content)
|
||||
@ -106,7 +117,7 @@ def decode_search_response(content: bytes):
|
||||
return results
|
||||
|
||||
|
||||
def decode_user_info_response(content: bytes):
|
||||
def decode_user_info_response(content: bytes, locale: str='zh_CN'):
|
||||
pkt = P.Packet()
|
||||
pkt.ParseFromString(content)
|
||||
if not pkt.payload:
|
||||
@ -115,9 +126,9 @@ def decode_user_info_response(content: bytes):
|
||||
info.ParseFromString(pkt.payload)
|
||||
detail = info.userInfoDetail.detail
|
||||
name = None
|
||||
for locale in detail.locales:
|
||||
if locale.key_string == 'zh_cn':
|
||||
return locale.translation
|
||||
for item in detail.locales:
|
||||
if item.key_string == locale.lower():
|
||||
return item.translation
|
||||
if detail.nickname:
|
||||
try:
|
||||
return detail.nickname.decode('utf-8')
|
||||
|
||||
@ -9,6 +9,8 @@ MSG_TYPE_NAMES = {
|
||||
22: 'COMMERCIALIZED_HONGBAO', 23: 'SHARE_USER_CARD', 24: 'TODO', 25: 'FOLDER',
|
||||
}
|
||||
CHAT_TYPE_NAMES = {0: 'UNKNOWN', 1: 'P2P', 2: 'GROUP', 3: 'TOPIC_GROUP'}
|
||||
# Chat.ChatMode 的 THREAD / THREAD_V2;新建的话题群是 GROUP + 这两种模式,旧版话题群才是 TOPIC_GROUP
|
||||
THREAD_CHAT_MODES = (2, 3)
|
||||
|
||||
|
||||
def enum_to_int(value):
|
||||
@ -25,6 +27,23 @@ def enum_to_int(value):
|
||||
return 0
|
||||
|
||||
|
||||
def is_thread_chat(chat_info: dict) -> bool:
|
||||
"""话题群里每条根消息自成一个话题。chat_info 为 chats.PullChatsByIdsRequest 返回的单个会话。"""
|
||||
return enum_to_int(chat_info.get('chatMode', 0)) in THREAD_CHAT_MODES or enum_to_int(chat_info.get('type', 0)) == 3
|
||||
|
||||
|
||||
def resolve_scope(msg_id: str, msg_type: int, chat_type: int, root_id: str, thread_id: str, thread_chat: bool=False) -> tuple:
|
||||
"""返回 (scope, anchor):anchor 是回复时的 --root,也是 agent 的会话边界。"""
|
||||
if chat_type == 1:
|
||||
return ('chat', '')
|
||||
if root_id and root_id != '0':
|
||||
return ('topic', thread_id or root_id)
|
||||
# 话题群的根消息本身就开启一个话题(建群等系统提示除外);普通群每条消息也带 threadId=自身 id,不能据此判断
|
||||
if (thread_chat or chat_type == 3) and msg_type != 6:
|
||||
return ('topic', msg_id or '')
|
||||
return ('chat', '')
|
||||
|
||||
|
||||
def extract_rich_text(rich_text_dict):
|
||||
TAG_PLACEHOLDERS = {2: '[图片]', 5: '[@]', 10: '[表情]', 18: '[视频]', 22: '[文档]'}
|
||||
text = ''
|
||||
@ -54,6 +73,15 @@ def extract_rich_text(rich_text_dict):
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
if tag == 5:
|
||||
ap = P.AtProperty()
|
||||
try:
|
||||
ap.ParseFromString(prop)
|
||||
if ap.content:
|
||||
text += ap.content
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
text += TAG_PLACEHOLDERS.get(tag, '')
|
||||
except Exception:
|
||||
pass
|
||||
@ -102,12 +130,12 @@ def decode_message_content(message_type, content_bytes):
|
||||
mc = P.MediaContent()
|
||||
mc.ParseFromString(content_bytes)
|
||||
d = protobuf_to_dict(mc)
|
||||
return (f"[视频] {d.get('name', '')} (时长{d.get('duration', 0)}s, {d.get('size', 0)}字节, key={d.get('key', '')})", d)
|
||||
return (f"[视频] {d.get('name', '')} (时长{d.get('duration', 0) / 1000:.1f}s, {d.get('size', 0)}字节, key={d.get('key', '')})", d)
|
||||
if message_type == 7:
|
||||
ac = P.AudioContent()
|
||||
ac.ParseFromString(content_bytes)
|
||||
d = protobuf_to_dict(ac)
|
||||
return (f"[语音] 时长{d.get('duration', 0)}s, key={d.get('key', '')}", d)
|
||||
return (f"[语音] 时长{d.get('duration', 0) / 1000:.1f}s, key={d.get('key', '')}", d)
|
||||
if message_type == 10:
|
||||
sc = P.StickerContent()
|
||||
sc.ParseFromString(content_bytes)
|
||||
@ -225,15 +253,7 @@ def decode_push_messages(raw: bytes):
|
||||
message_type = enum_to_int(v.get('type', 0))
|
||||
chat_type = enum_to_int(v.get('chatType', 0))
|
||||
summary, data = decode_message_content(message_type, v.get('content', b''))
|
||||
thread_id = v.get('threadId') or ''
|
||||
root_id = v.get('rootId') or ''
|
||||
if chat_type == 1:
|
||||
scope, anchor = ('chat', '')
|
||||
elif root_id and root_id != '0':
|
||||
scope, anchor = ('topic', thread_id or root_id)
|
||||
elif chat_type == 3:
|
||||
scope, anchor = ('chat', v.get('id') or '')
|
||||
else:
|
||||
scope, anchor = ('chat', '')
|
||||
scope, anchor = resolve_scope(v.get('id'), message_type, chat_type, root_id, v.get('threadId') or '')
|
||||
out.append({'msg_id': v.get('id'), 'msg_type': message_type, 'msg_type_name': MSG_TYPE_NAMES.get(message_type, str(message_type)), 'from_id': v.get('fromId'), 'chat_id': v.get('chatId') or v.get('channelId'), 'chat_type': chat_type, 'chat_type_name': CHAT_TYPE_NAMES.get(chat_type, str(chat_type)), 'scope': scope, 'anchor': anchor, 'at_me': bool(at_me_map.get(v.get('id')) or at_me_map.get(k)), 'root_id': root_id, 'parent_id': v.get('parentId') or '', 'cid': v.get('cid') or '', 'position': v.get('position'), 'create_time': v.get('createTime'), 'content': summary, 'content_data': data})
|
||||
return out
|
||||
|
||||
@ -47,9 +47,13 @@ message PutMessageRequest {
|
||||
optional int32 version = 9;
|
||||
optional bool isThreadGroupTopic = 10;
|
||||
optional bool isAnonymous = 11;
|
||||
optional bool isReplyInThread = 12;
|
||||
repeated string leftStaticResourceKeys = 101;
|
||||
optional bytes thriftMessage = 102;
|
||||
}
|
||||
message PutMessageResponse {
|
||||
optional entities.Message message = 1;
|
||||
}
|
||||
|
||||
|
||||
message PutChatRequest {
|
||||
@ -541,6 +545,10 @@ message TextProperty {
|
||||
optional string i18nKey = 2;
|
||||
optional int32 numberOfLines = 3;
|
||||
}
|
||||
message AtProperty {
|
||||
optional string userId = 1;
|
||||
optional string content = 2;
|
||||
}
|
||||
message ExtendedEntry {
|
||||
optional string key = 1;
|
||||
optional string value = 2;
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user