PhoneWork/bot/feishu.py
Yuyao Huang (Sam) b67e2dd2db feat: 增强日志功能并添加rich依赖
- 添加rich库依赖以改进日志显示
- 在各模块添加详细调试日志,包括消息处理、命令执行和工具调用过程
- 使用RichHandler美化日志输出并抑制第三方库的噪音日志
- 在关键路径添加日志记录,便于问题排查
2026-03-28 07:57:24 +08:00

85 lines
2.1 KiB
Python

"""Feishu API client: send messages back to users."""
from __future__ import annotations
import logging
import lark_oapi as lark
from lark_oapi.api.im.v1 import (
CreateMessageRequest,
CreateMessageRequestBody,
)
from config import FEISHU_APP_ID, FEISHU_APP_SECRET
logger = logging.getLogger(__name__)
# Max Feishu text message length
MAX_TEXT_LEN = 4000
def _make_client() -> lark.Client:
return (
lark.Client.builder()
.app_id(FEISHU_APP_ID)
.app_secret(FEISHU_APP_SECRET)
.log_level(lark.LogLevel.WARNING)
.build()
)
_client = _make_client()
def _truncate(text: str) -> str:
if len(text) <= MAX_TEXT_LEN:
return text
return text[: MAX_TEXT_LEN - 20] + "\n...[truncated]"
async def send_text(receive_id: str, receive_id_type: str, text: str) -> None:
"""
Send a plain-text message to a Feishu chat or user.
Args:
receive_id: chat_id or open_id depending on receive_id_type.
receive_id_type: "chat_id" | "open_id" | "user_id" | "union_id".
text: message content.
"""
import json as _json
truncated = _truncate(text)
logger.debug(
"[feishu] send_text to=%s type=%s len=%d/%d text=%r",
receive_id, receive_id_type, len(truncated), len(text), truncated[:120],
)
content = _json.dumps({"text": truncated}, ensure_ascii=False)
request = (
CreateMessageRequest.builder()
.receive_id_type(receive_id_type)
.request_body(
CreateMessageRequestBody.builder()
.receive_id(receive_id)
.msg_type("text")
.content(content)
.build()
)
.build()
)
import asyncio
loop = asyncio.get_event_loop()
response = await loop.run_in_executor(
None,
lambda: _client.im.v1.message.create(request),
)
if not response.success():
logger.error(
"Feishu send_text failed: code=%s msg=%s",
response.code,
response.msg,
)
else:
logger.debug("Sent message to %s (%s)", receive_id, receive_id_type)