Lark AI Agent 🚀
This commit is contained in:
4
app/__init__.py
Normal file
4
app/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
"""
|
||||
Lark Message Recorder application package
|
||||
"""
|
||||
__author__ = "Cato"
|
||||
3
app/api/__init__.py
Normal file
3
app/api/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
API modules for Lark client interactions
|
||||
"""
|
||||
25
app/api/auth.py
Normal file
25
app/api/auth.py
Normal file
@ -0,0 +1,25 @@
|
||||
from http.cookies import SimpleCookie
|
||||
|
||||
from app.config.settings import settings
|
||||
|
||||
class LarkAuth:
|
||||
"""Authentication for Lark API"""
|
||||
|
||||
def __init__(self, cookie_str=None):
|
||||
"""Initialize LarkAuth with optional cookie string"""
|
||||
self.cookie = {}
|
||||
if cookie_str:
|
||||
self.prepare_auth(cookie_str)
|
||||
elif settings.LARK_COOKIE:
|
||||
self.prepare_auth(settings.LARK_COOKIE)
|
||||
|
||||
def prepare_auth(self, cookie_str):
|
||||
"""Process cookie string to dict format"""
|
||||
cookie = SimpleCookie()
|
||||
cookie.load(cookie_str)
|
||||
self.cookie = {k: v.value for k, v in cookie.items()}
|
||||
return self.cookie
|
||||
|
||||
def get_auth():
|
||||
"""Get LarkAuth instance with cookie from config"""
|
||||
return LarkAuth()
|
||||
170
app/api/lark_client.py
Normal file
170
app/api/lark_client.py
Normal file
@ -0,0 +1,170 @@
|
||||
import asyncio
|
||||
import threading
|
||||
import time
|
||||
|
||||
import requests
|
||||
import websockets
|
||||
import static.proto_pb2 as FLY_BOOK_PROTO
|
||||
from loguru import logger
|
||||
from urllib.parse import urlencode
|
||||
from app.api.auth import get_auth
|
||||
from builder.header import HeaderBuilder
|
||||
from builder.proto import ProtoBuilder
|
||||
from app.config.settings import settings
|
||||
|
||||
|
||||
|
||||
class LarkClient:
|
||||
loop = asyncio.new_event_loop()
|
||||
"""Client for interacting with Lark APIs"""
|
||||
|
||||
def __init__(self, auth):
|
||||
self.auth = auth
|
||||
self.base_url = settings.LARK_BASE_URL
|
||||
self.csrf_token_url = settings.LARK_CSRF_TOKEN_URL
|
||||
self.user_info_url = settings.LARK_USER_INFO_URL
|
||||
self.ws_base_url = settings.LARK_WS_URL
|
||||
|
||||
_, self.x_csrf_token = self.get_csrf_token()
|
||||
_, self.me_id = self.get_self_user_info()
|
||||
self.me_id = str(self.me_id)
|
||||
|
||||
def get_csrf_token(self):
|
||||
from builder.params import ParamsBuilder
|
||||
"""Get CSRF token"""
|
||||
headers = HeaderBuilder.build_get_csrf_token_header().get()
|
||||
params = ParamsBuilder.build_get_csrf_token_param().get()
|
||||
response = requests.post(self.csrf_token_url, headers=headers, cookies=self.auth.cookie, params=params)
|
||||
res_json = response.json()
|
||||
x_csrf_token = response.cookies.get('swp_csrf_token')
|
||||
if not x_csrf_token:
|
||||
logger.error("未在响应中找到swp_csrf_token")
|
||||
return res_json, x_csrf_token
|
||||
|
||||
def get_self_user_info(self):
|
||||
from builder.params import ParamsBuilder
|
||||
"""Get current user info"""
|
||||
headers = HeaderBuilder.build_get_user_info_header(self.x_csrf_token).get()
|
||||
params = ParamsBuilder.build_get_user_info_param().get()
|
||||
response = requests.get(self.user_info_url, headers=headers, cookies=self.auth.cookie, params=params)
|
||||
res_json = response.json()
|
||||
user_id = res_json['data']['user']['id']
|
||||
return res_json, user_id
|
||||
|
||||
def search_some(self, query):
|
||||
"""Search for users or groups"""
|
||||
headers = HeaderBuilder.build_search_header().get()
|
||||
Packet = ProtoBuilder.build_search_request_proto(headers['x-request-id'], query)
|
||||
response = requests.post(self.base_url, headers=headers, cookies=self.auth.cookie, data=Packet.SerializeToString())
|
||||
SearchResponsePacket, userAndGroupIds = ProtoBuilder.decode_search_response_proto(response.content)
|
||||
return SearchResponsePacket, userAndGroupIds
|
||||
|
||||
def create_chat(self, userId):
|
||||
"""Create a chat with a user or group"""
|
||||
headers = HeaderBuilder.build_create_chat_header().get()
|
||||
Packet = ProtoBuilder.build_create_chat_request_proto(headers['x-request-id'], userId)
|
||||
response = requests.post(self.base_url, headers=headers, cookies=self.auth.cookie, data=Packet.SerializeToString())
|
||||
PutChatResponsePacket, chatId = ProtoBuilder.decode_create_chat_response_proto(response.content)
|
||||
return PutChatResponsePacket, chatId
|
||||
|
||||
def send_msg(self, sends_text, chatId):
|
||||
"""Send a message to a chat"""
|
||||
headers = HeaderBuilder.build_send_msg_header().get()
|
||||
Packet = ProtoBuilder.build_send_message_request_proto(sends_text, headers['x-request-id'], chatId)
|
||||
response = requests.post(self.base_url, headers=headers, cookies=self.auth.cookie, data=Packet.SerializeToString())
|
||||
return response
|
||||
|
||||
def get_other_user_all_name(self, user_id, chat_id):
|
||||
"""Get another user's display name"""
|
||||
headers = HeaderBuilder.build_get_user_all_name_header().get()
|
||||
packet = ProtoBuilder.build_get_user_all_name_request_proto(headers['x-request-id'], user_id, chat_id)
|
||||
response = requests.post(self.base_url, headers=headers, cookies=self.auth.cookie, data=packet.SerializeToString())
|
||||
content = response.content
|
||||
user_name = ProtoBuilder.decode_info_response_proto(content)
|
||||
return user_name
|
||||
|
||||
def get_group_name(self, chat_id):
|
||||
"""Get group chat name"""
|
||||
headers = HeaderBuilder.build_get_group_name_header().get()
|
||||
packet = ProtoBuilder.build_get_group_name_request_proto(headers['x-request-id'], chat_id)
|
||||
response = requests.post(self.base_url, headers=headers, cookies=self.auth.cookie, data=packet.SerializeToString())
|
||||
group_name = ProtoBuilder.decode_group_info_response_proto(response.content)
|
||||
return group_name
|
||||
|
||||
async def send_ack(self, ws, packet_sid):
|
||||
"""Send acknowledgment for received messages"""
|
||||
payload = FLY_BOOK_PROTO.Packet()
|
||||
payload.cmd = 1
|
||||
payload.payloadType = 1
|
||||
payload.sid = packet_sid
|
||||
payload = payload.SerializeToString()
|
||||
|
||||
frame = FLY_BOOK_PROTO.Frame()
|
||||
current = int(time.time() * 1000)
|
||||
frame.seqid = current
|
||||
frame.logid = current
|
||||
frame.service = 1
|
||||
frame.method = 1
|
||||
|
||||
extended_entry = FLY_BOOK_PROTO.ExtendedEntry()
|
||||
extended_entry.key = 'x-request-time'
|
||||
extended_entry.value = f'{current}000'
|
||||
frame.headers.append(extended_entry)
|
||||
frame.payloadType = "pb"
|
||||
frame.payload = payload
|
||||
|
||||
serialized_frame = frame.SerializeToString()
|
||||
await ws.send(serialized_frame)
|
||||
|
||||
@staticmethod
|
||||
def start_message_processor():
|
||||
def run_loop(loop):
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.run_forever()
|
||||
threading.Thread(target=run_loop, args=(LarkClient.loop,)).start()
|
||||
|
||||
async def connect_websocket(self, message_handler):
|
||||
"""Connect to Lark websocket and handle messages"""
|
||||
from builder.params import ParamsBuilder
|
||||
params = ParamsBuilder.build_receive_msg_param(self.auth).get()
|
||||
url = f"{self.ws_base_url}?{urlencode(params)}"
|
||||
async with websockets.connect(url) as websocket:
|
||||
LarkClient.start_message_processor()
|
||||
async for message in websocket:
|
||||
try:
|
||||
packet_sid = ProtoBuilder.extra_packet_id(message)
|
||||
await self.send_ack(websocket, packet_sid)
|
||||
ReceiveTextContent = ProtoBuilder.decode_receive_msg_proto(message)
|
||||
asyncio.run_coroutine_threadsafe(self.process_msg(ReceiveTextContent, message_handler), LarkClient.loop)
|
||||
except Exception as e:
|
||||
# logger.error(f"Error processing message: {e}")
|
||||
continue
|
||||
|
||||
async def process_msg(self, msg, message_handler):
|
||||
from_id, chat_id, chat_type, content = msg['fromId'], msg['chatId'], msg['chatType'], msg['content']
|
||||
user_name = self.get_other_user_all_name(from_id, chat_id)
|
||||
is_group_chat = (chat_type == 2)
|
||||
group_name = None
|
||||
if is_group_chat:
|
||||
group_name = self.get_group_name(chat_id)
|
||||
await message_handler(
|
||||
user_name=user_name,
|
||||
user_id=from_id,
|
||||
content=content,
|
||||
is_group_chat=is_group_chat,
|
||||
group_name=group_name,
|
||||
chat_id=chat_id
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
auth = get_auth()
|
||||
lark_client = LarkClient(auth)
|
||||
fromId = 7478340774602522627
|
||||
chatId = 7478340637890854916
|
||||
chatId = 7373962691750363140
|
||||
user_name = lark_client.get_other_user_all_name(fromId, chatId)
|
||||
print(user_name)
|
||||
|
||||
group_name = lark_client.get_group_name(chatId)
|
||||
print(group_name)
|
||||
3
app/config/__init__.py
Normal file
3
app/config/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
Application configuration
|
||||
"""
|
||||
38
app/config/settings.py
Normal file
38
app/config/settings.py
Normal file
@ -0,0 +1,38 @@
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
class Settings:
|
||||
"""Application settings"""
|
||||
|
||||
DB_HOST = os.getenv("DB_HOST", "localhost")
|
||||
DB_PORT = int(os.getenv("DB_PORT", "3306"))
|
||||
DB_USER = os.getenv("DB_USER", "root")
|
||||
DB_PASSWORD = os.getenv("DB_PASSWORD", "password")
|
||||
DB_NAME = os.getenv("DB_NAME", "lark_messages")
|
||||
|
||||
SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
|
||||
|
||||
LARK_COOKIE = os.getenv("LARK_COOKIE", "")
|
||||
LARK_BASE_URL = "https://internal-api-lark-api.feishu.cn/im/gateway/"
|
||||
LARK_CSRF_TOKEN_URL = "https://internal-api-lark-api.feishu.cn/accounts/csrf"
|
||||
LARK_USER_INFO_URL = "https://internal-api-lark-api.feishu.cn/accounts/web/user"
|
||||
LARK_WS_URL = "wss://msg-frontier.feishu.cn/ws/v2"
|
||||
|
||||
FUNCTION_TRIGGER_FLAG = os.getenv("FUNCTION_TRIGGER_FLAG", "/run")
|
||||
|
||||
AI_BOT_PREFIX = os.getenv("AI_BOT_PREFIX", "AI Bot:")
|
||||
|
||||
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
||||
OPENAI_API_BASE_URL = os.getenv("OPENAI_API_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
|
||||
OPENAI_API_MODEL = os.getenv("OPENAI_API_MODEL", "qwen-plus")
|
||||
# ENVIRON = {}
|
||||
# for i in os.getenv("ENVIRON", "").split(";"):
|
||||
# if '=' not in i:
|
||||
# continue
|
||||
# ENVIRON.update({i.split("=")[0]: i.split("=")[1]})
|
||||
|
||||
|
||||
settings = Settings()
|
||||
3
app/core/__init__.py
Normal file
3
app/core/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
Core business logic modules
|
||||
"""
|
||||
53
app/core/llm_service.py
Normal file
53
app/core/llm_service.py
Normal file
@ -0,0 +1,53 @@
|
||||
"""
|
||||
Service for Large Language Model operations
|
||||
"""
|
||||
import json
|
||||
from loguru import logger
|
||||
from openai import OpenAI
|
||||
from app.config.settings import settings
|
||||
|
||||
class LLMService:
|
||||
"""Service for handling LLM API calls"""
|
||||
|
||||
def __init__(self):
|
||||
api_key = settings.OPENAI_API_KEY
|
||||
self.api_key = api_key
|
||||
if api_key:
|
||||
self.openai_client = OpenAI(
|
||||
api_key=api_key,
|
||||
base_url=settings.OPENAI_API_BASE_URL,
|
||||
)
|
||||
else:
|
||||
self.openai_client = None
|
||||
logger.warning("未在配置中设置 OPENAI_API_KEY")
|
||||
|
||||
def chat_completion(self, messages, tools=None, model=None):
|
||||
"""
|
||||
发送请求到OpenAI并返回回复
|
||||
|
||||
Args:
|
||||
messages: 消息列表
|
||||
tools: 工具列表
|
||||
model: 模型名称,默认使用settings中的配置
|
||||
|
||||
Returns:
|
||||
OpenAI API的响应对象
|
||||
"""
|
||||
if not self.openai_client:
|
||||
raise ValueError("OpenAI client is not initialized")
|
||||
model = model or settings.OPENAI_API_MODEL
|
||||
if tools:
|
||||
return self.openai_client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
tools=tools
|
||||
)
|
||||
else:
|
||||
return self.openai_client.chat.completions.create(
|
||||
model=model,
|
||||
messages=messages
|
||||
)
|
||||
|
||||
def is_available(self):
|
||||
"""检查API是否可用"""
|
||||
return self.openai_client is not None
|
||||
179
app/core/mcp_server.py
Normal file
179
app/core/mcp_server.py
Normal file
@ -0,0 +1,179 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import os
|
||||
import sys
|
||||
import random
|
||||
import datetime
|
||||
from loguru import logger
|
||||
from sqlalchemy import func, desc
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
|
||||
|
||||
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
|
||||
if BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, BASE_DIR)
|
||||
|
||||
from app.core.llm_service import LLMService
|
||||
from app.db.session import get_db_session, close_db_session
|
||||
from app.db.models import Message
|
||||
from app.api.auth import get_auth
|
||||
from app.api.lark_client import LarkClient
|
||||
|
||||
mcp = FastMCP("LARK_MCP_SERVER")
|
||||
registered_tools = []
|
||||
llm_service = LLMService()
|
||||
|
||||
|
||||
def register_tool(name: str, description: str):
|
||||
def decorator(func):
|
||||
mcp.tool(name=name, description=description)(func)
|
||||
registered_tools.append((name, description))
|
||||
return func
|
||||
return decorator
|
||||
|
||||
@register_tool(name="list_tools", description="List all available tools and their descriptions")
|
||||
def list_tools() -> str:
|
||||
result = "🛠️ 当前可用功能列表:\n"
|
||||
for name, desc in registered_tools:
|
||||
result += f"- `{name}`:{desc}\n"
|
||||
return result
|
||||
|
||||
@register_tool(name="get_weather", description="获取城市天气")
|
||||
def get_weather(city):
|
||||
"""
|
||||
获取城市天气
|
||||
:param city: 城市名称
|
||||
:return: 城市天气
|
||||
"""
|
||||
from extension.weather_api.api import get_city_weather
|
||||
return get_city_weather(city)
|
||||
|
||||
@register_tool(name="extra_order_from_content", description="提取文字中的订单信息,包括订单号、商品名称、数量等,以json格式返回")
|
||||
def extra_order_from_content(content: str) -> str:
|
||||
"""
|
||||
提取订单信息
|
||||
:param content: 消息内容
|
||||
:return: 提取的订单信息
|
||||
"""
|
||||
res = llm_service.chat_completion(
|
||||
messages=[
|
||||
{"role": "user", "content": content},
|
||||
{"role": "system", "content": "请提取订单信息,包括订单号、商品名称、数量等,以json格式返回"},
|
||||
],
|
||||
tools=None,
|
||||
model="qwen-plus"
|
||||
)
|
||||
if res and res.choices:
|
||||
content = res.choices[0].message.content
|
||||
if content:
|
||||
return content
|
||||
return "未能提取到订单信息,请检查消息内容是否包含有效的订单信息。"
|
||||
|
||||
|
||||
@register_tool(name="tell_joke", description="Tell a random joke")
|
||||
def tell_joke() -> str:
|
||||
jokes = [
|
||||
"为什么程序员都喜欢黑色?因为他们不喜欢 bug 光。",
|
||||
"Python 和蛇有什么共同点?一旦缠上你就放不下了。",
|
||||
"为什么 Java 开发者很少被邀去派对?因为他们总是抛出异常。",
|
||||
]
|
||||
return random.choice(jokes)
|
||||
|
||||
|
||||
@register_tool(name="get_time", description="Get the current time")
|
||||
def get_time() -> str:
|
||||
now = datetime.datetime.now()
|
||||
return f"当前时间是 {now.strftime('%Y-%m-%d %H:%M:%S')}"
|
||||
|
||||
|
||||
@register_tool(name="fortune", description="Draw a random fortune")
|
||||
def fortune() -> str:
|
||||
fortunes = [
|
||||
"大吉:今天适合尝试新事物!✨",
|
||||
"中吉:平稳的一天,保持专注。",
|
||||
"小吉:会有小惊喜出现~",
|
||||
"凶:注意不要过度疲劳。",
|
||||
"大凶:小心电子设备出问题 🧯"
|
||||
]
|
||||
return random.choice(fortunes)
|
||||
|
||||
|
||||
@register_tool(name="count_daily_speakers", description="获取今天发言的人数统计")
|
||||
def count_daily_speakers() -> str:
|
||||
"""查询数据库统计今天有多少人发言"""
|
||||
db = get_db_session()
|
||||
try:
|
||||
today = datetime.datetime.now().date()
|
||||
today_start = datetime.datetime.combine(today, datetime.time.min)
|
||||
today_end = datetime.datetime.combine(today, datetime.time.max)
|
||||
speaker_count = db.query(func.count(func.distinct(Message.user_id)))\
|
||||
.filter(Message.message_time >= today_start)\
|
||||
.filter(Message.message_time <= today_end)\
|
||||
.scalar()
|
||||
message_count = db.query(func.count(Message.id))\
|
||||
.filter(Message.message_time >= today_start)\
|
||||
.filter(Message.message_time <= today_end)\
|
||||
.scalar()
|
||||
|
||||
return f"今天已有 {speaker_count} 人发言,共发送了 {message_count} 条消息。"
|
||||
except Exception as e:
|
||||
logger.error(f"查询今日发言人数时出错: {str(e)}")
|
||||
return f"查询失败: {str(e)}"
|
||||
finally:
|
||||
close_db_session(db)
|
||||
|
||||
@register_tool(name="get_top_speaker_today", description="获取今天发言最多的用户")
|
||||
def get_top_speaker_today() -> str:
|
||||
"""查询数据库统计今天谁的发言最多"""
|
||||
db = get_db_session()
|
||||
try:
|
||||
today = datetime.datetime.now().date()
|
||||
today_start = datetime.datetime.combine(today, datetime.time.min)
|
||||
today_end = datetime.datetime.combine(today, datetime.time.max)
|
||||
result = db.query(
|
||||
Message.user_name,
|
||||
Message.user_id,
|
||||
func.count(Message.id).label('message_count')
|
||||
)\
|
||||
.filter(Message.message_time >= today_start)\
|
||||
.filter(Message.message_time <= today_end)\
|
||||
.group_by(Message.user_id, Message.user_name)\
|
||||
.order_by(desc('message_count'))\
|
||||
.first()
|
||||
if not result:
|
||||
return "今天还没有人发言。"
|
||||
user_name, user_id, message_count = result
|
||||
return f"今日话题王: {user_name},共发送了 {message_count} 条消息。"
|
||||
except Exception as e:
|
||||
logger.error(f"查询今日最多发言用户时出错: {str(e)}")
|
||||
return f"查询失败: {str(e)}"
|
||||
finally:
|
||||
close_db_session(db)
|
||||
|
||||
@register_tool(name="send_message", description="给指定用户发送消息 {user:用户名称 content:消息内容}")
|
||||
def send_message(user: str, content: str) -> str:
|
||||
"""给指定用户发送私信"""
|
||||
lark_client = LarkClient(get_auth())
|
||||
SearchResponsePacket, userAndGroupIds = lark_client.search_some(user)
|
||||
if not userAndGroupIds:
|
||||
return f"未找到用户 '{user}'。"
|
||||
user_or_group_id = userAndGroupIds[0]
|
||||
if user_or_group_id['type'] == 'user':
|
||||
logger.info(f'搜索到用户: {user}')
|
||||
userId = user_or_group_id['id']
|
||||
PutChatResponsePacket, chatId = lark_client.create_chat(userId)
|
||||
found_user_name = lark_client.get_other_user_all_name(userId, chatId)
|
||||
logger.info(f'用户名称: {found_user_name}')
|
||||
else:
|
||||
logger.info('搜索到群组')
|
||||
chatId = user_or_group_id['id']
|
||||
group_name = lark_client.get_group_name(chatId)
|
||||
logger.info(f'群组名称: {group_name}')
|
||||
return f"'{user}' 是一个群组,不是用户,无法发送私信。"
|
||||
|
||||
_ = lark_client.send_msg(content, chatId)
|
||||
return f"成功向 {user} 发送了私信: '{content}'"
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(get_weather("北京"))
|
||||
mcp.run(transport="stdio")
|
||||
108
app/core/message_service.py
Normal file
108
app/core/message_service.py
Normal file
@ -0,0 +1,108 @@
|
||||
"""
|
||||
Service for processing and storing Lark messages
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from loguru import logger
|
||||
from datetime import datetime
|
||||
from app.db.models import Message
|
||||
from app.db.session import get_db_session, close_db_session
|
||||
from app.config.settings import settings
|
||||
from app.core.llm_service import LLMService
|
||||
from fastmcp import Client
|
||||
from fastmcp.client.transports import PythonStdioTransport
|
||||
|
||||
class MessageService:
|
||||
"""Service for processing and storing messages"""
|
||||
|
||||
def __init__(self, lark_client):
|
||||
self.lark_client = lark_client
|
||||
self.db = get_db_session()
|
||||
self.llm_service = LLMService()
|
||||
self.mcp_transport = PythonStdioTransport("app/core/mcp_server.py", env={"PATHEXT": os.environ.get("PATHEXT", "")})
|
||||
self.system_message = {"role": "system", "content": "你是一个很有帮助的助手。当用户提问需要调用工具时,请使用 tools 中定义的函数。"}
|
||||
|
||||
async def process_message(self, user_name, user_id, content, is_group_chat, group_name, chat_id):
|
||||
"""Process and store a message in the database"""
|
||||
try:
|
||||
message_source = f"群聊 {group_name}" if is_group_chat else "私聊"
|
||||
logger.info(f"收到{message_source}消息 - 用户: {user_name}, 内容: {content}")
|
||||
if not content or not content.strip():
|
||||
logger.warning("收到非纯文本消息,跳过存储")
|
||||
return
|
||||
message = Message(
|
||||
user_name=user_name,
|
||||
user_id=user_id,
|
||||
content=content,
|
||||
is_group_chat=is_group_chat,
|
||||
group_name=group_name,
|
||||
chat_id=chat_id,
|
||||
message_time=datetime.now()
|
||||
)
|
||||
self.db.add(message)
|
||||
self.db.commit()
|
||||
if content.strip().startswith(settings.FUNCTION_TRIGGER_FLAG):
|
||||
await self._handle_function_call(user_name, content, chat_id, is_group_chat)
|
||||
except Exception as e:
|
||||
self.db.rollback()
|
||||
logger.error(f"存储消息时出错: {str(e)}")
|
||||
|
||||
|
||||
async def _handle_function_call(self, user_name, content, chat_id, is_group_chat):
|
||||
"""处理flag触发的函数调用请求并发送响应"""
|
||||
try:
|
||||
logger.info(f"触发flag函数调用 - 用户: {user_name}, 内容: {content}")
|
||||
query = content.strip()[len(settings.FUNCTION_TRIGGER_FLAG):].strip()
|
||||
if not self.llm_service.is_available():
|
||||
error_msg = "未在配置中设置 OPENAI_API_KEY"
|
||||
logger.error(error_msg)
|
||||
self.lark_client.send_msg(error_msg, chat_id)
|
||||
return
|
||||
|
||||
async with Client(self.mcp_transport) as mcp_client:
|
||||
tools = []
|
||||
for tool in await mcp_client.list_tools():
|
||||
info = tool.model_dump() if hasattr(tool, "model_dump") else tool.dict()
|
||||
tools.append({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": info["name"],
|
||||
"description": info.get("description", ""),
|
||||
"parameters": info.get("parameters", {})
|
||||
}
|
||||
})
|
||||
messages = [
|
||||
self.system_message,
|
||||
{"role": "user", "content": query}
|
||||
]
|
||||
resp = self.llm_service.chat_completion(messages, tools)
|
||||
msg = resp.choices[0].message
|
||||
if msg.tool_calls:
|
||||
call = msg.tool_calls[0]
|
||||
fn_name = call.function.name
|
||||
args = json.loads(call.function.arguments)
|
||||
output = await mcp_client.call_tool(fn_name, args)
|
||||
logger.info(f"调用函数 {fn_name} -> {output}")
|
||||
messages.append(msg)
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"content": output,
|
||||
"tool_call_id": call.id
|
||||
})
|
||||
summary = self.llm_service.chat_completion(messages)
|
||||
response = summary.choices[0].message.content
|
||||
else:
|
||||
response = msg.content
|
||||
self.lark_client.send_msg(response, chat_id)
|
||||
except Exception as e:
|
||||
logger.error(f"处理flag函数调用时出错: {str(e)}")
|
||||
error_msg = f"执行错误: {str(e)}"
|
||||
try:
|
||||
self.lark_client.send_msg(error_msg, chat_id)
|
||||
except Exception as send_err:
|
||||
logger.error(f"发送错误消息失败: {str(send_err)}")
|
||||
|
||||
def close(self):
|
||||
"""Close database session"""
|
||||
close_db_session(self.db)
|
||||
3
app/db/__init__.py
Normal file
3
app/db/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
Database connection and models
|
||||
"""
|
||||
23
app/db/models.py
Normal file
23
app/db/models.py
Normal file
@ -0,0 +1,23 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, Boolean, DateTime
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.sql import func
|
||||
from datetime import datetime
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
class Message(Base):
|
||||
"""Model for storing Lark chat messages"""
|
||||
__tablename__ = "messages"
|
||||
|
||||
id = Column(Integer, primary_key=True, autoincrement=True)
|
||||
user_name = Column(String(255), nullable=False, comment="User display name")
|
||||
user_id = Column(String(255), nullable=False, comment="User ID from Lark")
|
||||
content = Column(Text, nullable=False, comment="Message content")
|
||||
is_group_chat = Column(Boolean, default=False, comment="Whether the message is from a group chat")
|
||||
group_name = Column(String(255), nullable=True, comment="Group chat name (if applicable)")
|
||||
chat_id = Column(String(255), nullable=False, comment="Chat ID")
|
||||
message_time = Column(DateTime, default=datetime.now, comment="Time when the message was sent")
|
||||
created_at = Column(DateTime, default=func.now(), comment="Record creation time")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Message(id={self.id}, user_name='{self.user_name}', content='{self.content[:20]}...', is_group_chat={self.is_group_chat})>"
|
||||
67
app/db/session.py
Normal file
67
app/db/session.py
Normal file
@ -0,0 +1,67 @@
|
||||
"""
|
||||
Database session management and initialization
|
||||
"""
|
||||
from loguru import logger
|
||||
from app.db.models import Base
|
||||
from app.config.settings import settings
|
||||
from sqlalchemy import create_engine, text, exc
|
||||
from sqlalchemy.orm import sessionmaker, scoped_session
|
||||
from sqlalchemy.pool import QueuePool
|
||||
|
||||
def get_db_uri_without_db():
|
||||
"""获取不包含特定数据库名的URI"""
|
||||
uri_parts = settings.SQLALCHEMY_DATABASE_URI.split('/')
|
||||
uri_parts[-1] = ''
|
||||
return '/'.join(uri_parts)
|
||||
|
||||
def create_database_if_not_exists():
|
||||
"""如果数据库不存在则创建"""
|
||||
try:
|
||||
uri = get_db_uri_without_db()
|
||||
temp_engine = create_engine(uri)
|
||||
|
||||
with temp_engine.connect() as conn:
|
||||
create_db_sql = text(f"CREATE DATABASE IF NOT EXISTS {settings.DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
|
||||
conn.execute(create_db_sql)
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"数据库 '{settings.DB_NAME}' 已确认存在或已创建")
|
||||
except Exception as e:
|
||||
logger.error(f"创建数据库时出错: {str(e)}")
|
||||
raise
|
||||
|
||||
engine = create_engine(
|
||||
settings.SQLALCHEMY_DATABASE_URI,
|
||||
pool_size=10,
|
||||
max_overflow=20,
|
||||
pool_recycle=3600,
|
||||
pool_pre_ping=True,
|
||||
pool_timeout=30,
|
||||
poolclass=QueuePool
|
||||
)
|
||||
|
||||
session_factory = sessionmaker(bind=engine)
|
||||
SessionLocal = scoped_session(session_factory)
|
||||
|
||||
def init_db():
|
||||
"""初始化数据库,如果不存在则创建"""
|
||||
try:
|
||||
create_database_if_not_exists()
|
||||
Base.metadata.create_all(bind=engine)
|
||||
except Exception as e:
|
||||
logger.error(f"初始化数据库时出错: {str(e)}")
|
||||
raise
|
||||
|
||||
def get_db_session():
|
||||
"""获取数据库会话"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
return db
|
||||
except Exception:
|
||||
db.close()
|
||||
raise
|
||||
|
||||
def close_db_session(db):
|
||||
"""关闭数据库会话"""
|
||||
if db:
|
||||
db.close()
|
||||
3
app/utils/__init__.py
Normal file
3
app/utils/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
Utility functions and helper classes
|
||||
"""
|
||||
85
app/utils/lark_utils.py
Normal file
85
app/utils/lark_utils.py
Normal file
@ -0,0 +1,85 @@
|
||||
"""
|
||||
Lark API utility functions
|
||||
"""
|
||||
import os
|
||||
import execjs
|
||||
import subprocess
|
||||
from loguru import logger
|
||||
from functools import partial
|
||||
|
||||
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
|
||||
|
||||
def init_js():
|
||||
"""
|
||||
Initialize JavaScript environment for Lark decryption
|
||||
"""
|
||||
try:
|
||||
script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
js_path = os.path.join(script_dir, 'static', 'lark_decrypt.js')
|
||||
pathext = os.environ.get("PATHEXT", "")
|
||||
if '.EXE' not in pathext:
|
||||
pathext += '.EXE;'
|
||||
os.environ['PATHEXT'] = pathext
|
||||
lark_decrypt_js = execjs.compile(open(js_path, 'r', encoding='utf-8').read())
|
||||
return lark_decrypt_js
|
||||
except Exception as e:
|
||||
try:
|
||||
script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
js_path = os.path.join(script_dir, 'static', 'lark_decrypt.js')
|
||||
lark_decrypt_js = execjs.compile(open(js_path, 'r', encoding='utf-8').read())
|
||||
return lark_decrypt_js
|
||||
except Exception as e:
|
||||
logger.error(f"Error: Could not load JavaScript file: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def trans_cookies(cookies_str):
|
||||
"""
|
||||
Transform cookie string to dictionary
|
||||
|
||||
Args:
|
||||
cookies_str (str): Cookie string
|
||||
|
||||
Returns:
|
||||
dict: Cookie dictionary
|
||||
"""
|
||||
cookies = dict()
|
||||
for i in cookies_str.split("; "):
|
||||
try:
|
||||
cookies[i.split('=')[0]] = '='.join(i.split('=')[1:])
|
||||
except:
|
||||
continue
|
||||
return cookies
|
||||
|
||||
def generate_access_key(mystr):
|
||||
"""Generate access key using JavaScript function"""
|
||||
lark_decrypt_js = init_js()
|
||||
if lark_decrypt_js:
|
||||
access_key = lark_decrypt_js.call('generate_access_key', mystr)
|
||||
return access_key
|
||||
return None
|
||||
|
||||
def generate_request_id():
|
||||
"""Generate request ID using JavaScript function"""
|
||||
lark_decrypt_js = init_js()
|
||||
if lark_decrypt_js:
|
||||
request_id = lark_decrypt_js.call('generate_request_id')
|
||||
return request_id
|
||||
return None
|
||||
|
||||
def generate_long_request_id():
|
||||
"""Generate long request ID using JavaScript function"""
|
||||
lark_decrypt_js = init_js()
|
||||
|
||||
if lark_decrypt_js:
|
||||
request_id = lark_decrypt_js.call('generate_long_request_id')
|
||||
return request_id
|
||||
return None
|
||||
|
||||
def generate_request_cid():
|
||||
"""Generate request CID using JavaScript function"""
|
||||
lark_decrypt_js = init_js()
|
||||
if lark_decrypt_js:
|
||||
request_cid = lark_decrypt_js.call('generate_request_cid')
|
||||
return request_cid
|
||||
return None
|
||||
Reference in New Issue
Block a user