Lark AI Agent 🚀
This commit is contained in:
20
.env.example
Normal file
20
.env.example
Normal file
@ -0,0 +1,20 @@
|
||||
# Database configuration
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USER=YOUR_MYSQL_USERNAME
|
||||
DB_PASSWORD=YOUR_MYSQL_PASSWORD
|
||||
DB_NAME=lark_messages
|
||||
|
||||
# Lark API configuration
|
||||
LARK_COOKIE="YOUR LARK Cookie"
|
||||
|
||||
# Function trigger flag
|
||||
FUNCTION_TRIGGER_FLAG="/run"
|
||||
|
||||
# AI Bot message prefix (preferably longer)
|
||||
AI_BOT_PREFIX="Lark AI Bot:"
|
||||
|
||||
# OpenAI API configuration
|
||||
OPENAI_API_KEY="Your api key"
|
||||
OPENAI_API_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"
|
||||
OPENAI_API_MODEL="qwen-plus"
|
||||
32
.gitignore
vendored
Normal file
32
.gitignore
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
__pycache__
|
||||
*node_modules/*
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
MANIFEST
|
||||
*.manifest
|
||||
*.spec
|
||||
.cache
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
__pypackages__/
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
.env
|
||||
test.py
|
||||
29
Dockerfile
Normal file
29
Dockerfile
Normal file
@ -0,0 +1,29 @@
|
||||
FROM python:3.10-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y \
|
||||
curl \
|
||||
gnupg \
|
||||
build-essential \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
|
||||
&& apt-get install -y nodejs \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN python --version && node --version && npm --version
|
||||
|
||||
COPY requirements.txt .
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 5000
|
||||
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
ENV NODE_ENV=production
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
266
README.md
Normal file
266
README.md
Normal file
@ -0,0 +1,266 @@
|
||||
# Lark MCP - 飞书全场景 Function Call AI 助手 🚀
|
||||
|
||||
[](https://www.python.org/)
|
||||
[](https://nodejs.org/zh-cn/)
|
||||
|
||||
一个基于飞书(Lark)的全场景MCP Function Call AI Agent,实现大模型通过飞书进行函数调用和消息处理。**无需配置飞书机器人,你的飞书账号即是AI助手。**
|
||||
|
||||
|
||||
**无需配置飞书机器人,你的飞书账号即是AI助手。**
|
||||
|
||||
|
||||
**只需定义函数和注释,你的飞书机器人会自动根据场景调用。**
|
||||
|
||||
|
||||
## 项目概述 🌟
|
||||
|
||||
Lark MCP是一个现代化的Python应用程序,能够:
|
||||
|
||||
- 📊 逆向飞书Protobuf格式传输的Websockets和API,监听并记录消息
|
||||
- 🤖 提供自定义函数供大模型调用
|
||||
- 🔄 实现基于MCP (Model Context Protocol) 的函数调用框架
|
||||
- 💾 使用SQLAlchemy将消息存储到MySQL数据库
|
||||
|
||||
## 效果图🧸
|
||||
|
||||
<div align="center">
|
||||
<img src="static/resource/back_end.png" width="600" alt="后台日志">
|
||||
<br>
|
||||
<em>图1: 后台日志</em>
|
||||
</div>
|
||||
|
||||
|
||||
<div align="center">
|
||||
<img src="static/resource/front_end_1.png" width="600" alt="聊天数据库查询">
|
||||
<br>
|
||||
<em>图2: 聊天数据库查询</em>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<img src="static/resource/front_end_2.png" width="600" alt="天气查询">
|
||||
<br>
|
||||
<em>图3: 天气查询</em>
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<img src="static/resource/functions.png" width="600" alt="注册函数">
|
||||
<br>
|
||||
<em>图4: 简单注册函数,只需定义函数和注释</em>
|
||||
</div>
|
||||
|
||||
## ✨ 功能特点
|
||||
|
||||
- **函数注册机制**: 简单直观的函数注册装饰器
|
||||
- **消息自动处理**: 记录所有接收到的消息(私聊和群聊)
|
||||
- **异步处理**: 采用async/await模式进行异步通信
|
||||
- **数据持久化**: 使用SQLAlchemy将消息存储在MySQL数据库中
|
||||
- **灵活配置**: 通过环境变量进行配置
|
||||
- **容器化部署**: 支持Docker快速部署
|
||||
- **智能函数调用**: AI会根据用户输入的文字自动分析并调用最匹配的函数,开发者只需添加函数及其注释描述
|
||||
|
||||
## 📦 当前支持的函数
|
||||
|
||||
项目目前内置了以下函数供大模型调用:
|
||||
|
||||
| 函数名 | 描述 |
|
||||
|-------|------|
|
||||
| `tell_joke` | 讲一个随机笑话 |
|
||||
| `get_time` | 获取当前时间 |
|
||||
| `roll_dice` | 掷一个指定面数的骰子 |
|
||||
| `make_todo_list` | 从逗号分隔的任务创建待办清单 |
|
||||
| `translate_to_chinese` | 将英文单词翻译成中文 |
|
||||
| `countdown` | 创建一个从指定数字开始的倒计时 |
|
||||
| `random_color` | 生成一个随机的十六进制颜色代码 |
|
||||
| `fortune` | 抽取一个随机运势 |
|
||||
| `count_daily_speakers` | 获取今天发言的人数统计 |
|
||||
| `get_top_speaker_today` | 获取今天发言最多的用户 |
|
||||
| `send_message` | 给指定用户发送消息 |
|
||||
| `list_tools` | 列出所有可用的工具及其描述 |
|
||||
|
||||
|
||||
你可以通过在飞书中输入触发指令后跟要执行的操作来调用这些功能,例如: `/run 讲个笑话`
|
||||
|
||||
## 📂 项目结构
|
||||
|
||||
```
|
||||
project/
|
||||
├── app/ # 应用程序模块
|
||||
│ ├── api/ # API相关模块
|
||||
│ │ ├── auth.py # 认证模块
|
||||
│ │ └── lark_client.py # 飞书客户端
|
||||
│ ├── config/ # 配置模块
|
||||
│ │ └── settings.py # 应用配置
|
||||
│ ├── core/ # 核心业务逻辑
|
||||
│ │ ├── mcp_server.py # MCP服务器
|
||||
│ │ └── message_service.py # 消息处理服务
|
||||
│ ├── db/ # 数据库相关
|
||||
│ │ ├── models.py # 数据模型
|
||||
│ │ └── session.py # 数据库会话管理
|
||||
│ └── utils/ # 工具函数
|
||||
├── builder/ # 请求构建器
|
||||
├── static/ # 静态资源
|
||||
│ ├── resource/ # 图片资源
|
||||
│ ├── proto_pb2.py # 协议定义
|
||||
│ └── lark_decrypt.js # 飞书解密工具
|
||||
├── .env # 环境变量
|
||||
├── main.py # 应用入口
|
||||
└── Dockerfile # Docker配置
|
||||
```
|
||||
|
||||
## 🛠️ 自定义函数开发
|
||||
|
||||
在 `app/core/mcp_server.py` 文件中,您可以使用 `@register_tool` 装饰器添加您自己的自定义函数:
|
||||
|
||||
```python
|
||||
@register_tool(name="tell_joke", description="讲一个随机笑话")
|
||||
def tell_joke() -> str:
|
||||
jokes = [
|
||||
"为什么程序员都喜欢黑色?因为他们不喜欢 bug 光。",
|
||||
"Python 和蛇有什么共同点?一旦缠上你就放不下了。",
|
||||
"为什么 Java 开发者很少被邀去派对?因为他们总是抛出异常。",
|
||||
]
|
||||
return random.choice(jokes)
|
||||
|
||||
@register_tool(name="send_message", description="给指定用户发送消息 {user:用户名称 content:消息内容}")
|
||||
def send_message(user: str, content: str) -> str:
|
||||
"""给指定用户发送私信"""
|
||||
lark_client = LarkClient(get_auth())
|
||||
# ... 实现逻辑 ...
|
||||
return f"成功向 {user} 发送了私信: '{content}'"
|
||||
```
|
||||
|
||||
**重要**: 只需添加函数和对应的描述,AI会根据用户的文字自动分析并调用最匹配的函数,无需手动实现函数匹配逻辑。
|
||||
|
||||
## 🔧 环境要求
|
||||
|
||||
- Python 3.10+
|
||||
- Node.js 20+
|
||||
- MySQL数据库
|
||||
|
||||
## 📦 安装方法
|
||||
|
||||
### 使用本地环境
|
||||
|
||||
1. 安装依赖:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Windows用户注意:
|
||||
Windows系统需要额外安装以下依赖:
|
||||
```bash
|
||||
pip install win-inet-pton==1.1.0
|
||||
```
|
||||
|
||||
### 使用Docker
|
||||
|
||||
方法一:单独构建镜像
|
||||
```bash
|
||||
# 构建镜像
|
||||
docker build -t feishuapp .
|
||||
|
||||
# 运行容器
|
||||
docker run -it feishuapp bash
|
||||
```
|
||||
|
||||
方法二:使用Docker Compose(推荐)
|
||||
```bash
|
||||
# 启动所有服务(应用和数据库)
|
||||
docker-compose up -d
|
||||
|
||||
# 查看日志
|
||||
docker-compose logs -f
|
||||
|
||||
# 停止所有服务
|
||||
docker-compose down
|
||||
```
|
||||
|
||||
使用Docker Compose可以一键启动整个应用环境,包括MySQL数据库和应用服务,更加方便和高效。
|
||||
|
||||
## 🛠️ 配置说明
|
||||
|
||||
复制`.env.example`文件命名为`.env`文件,包含以下配置:
|
||||
|
||||
```
|
||||
# 数据库设置
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USER=root
|
||||
DB_PASSWORD=123456
|
||||
DB_NAME=lark_messages
|
||||
|
||||
# 飞书的Cookie设置 - 只需配置LARK_COOKIE即可,告别飞书机器人
|
||||
LARK_COOKIE=""
|
||||
|
||||
# 调用函数的触发前缀 (以FUNCTION_TRIGGER_FLAG开头的消息会被大模型解析,所有消息都会被记录到数据库,无论是否以该前缀开头)
|
||||
FUNCTION_TRIGGER_FLAG="/run"
|
||||
|
||||
# 机器人发言前缀 (暂未使用)
|
||||
AI_BOT_PREFIX="Lark AI Bot:"
|
||||
|
||||
# OpenAI API配置 默认是通义千问的,满足OpenAI的大模型厂商都可以
|
||||
OPENAI_API_KEY=""
|
||||
OPENAI_API_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"
|
||||
OPENAI_API_MODEL="qwen-plus"
|
||||
```
|
||||
|
||||
## 🚀 使用指南
|
||||
|
||||
### 运行应用程序
|
||||
|
||||
方法一:直接运行
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
方法二:使用Docker Compose
|
||||
```bash
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
应用程序将:
|
||||
1. 初始化MCP服务器
|
||||
2. 连接到飞书API并使用你的飞书账号作为AI助手
|
||||
3. 监听传入的消息
|
||||
4. 处理并执行大模型通过飞书发起的函数调用
|
||||
5. 将消息存储在MySQL数据库中
|
||||
|
||||
|
||||
## 🗄️ 数据库结构
|
||||
|
||||
应用程序将消息存储在`messages`表中,该表具有以下结构:
|
||||
|
||||
| 列名 | 类型 | 描述 |
|
||||
|----------------|---------------|---------------------------|
|
||||
| id | INT (PK) | 主键 |
|
||||
| user_name | VARCHAR(255) | 消息发送者的名称 |
|
||||
| user_id | VARCHAR(255) | 发送者的飞书用户ID |
|
||||
| content | TEXT | 消息内容 |
|
||||
| is_group_chat | BOOLEAN | 消息是否来自群聊 |
|
||||
| group_name | VARCHAR(255) | 群聊名称(如适用) |
|
||||
| chat_id | VARCHAR(255) | 聊天ID |
|
||||
| message_time | DATETIME | 消息发送时间 |
|
||||
| created_at | DATETIME | 记录创建时间 |
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
欢迎贡献!请随时提交Pull Request。
|
||||
|
||||
1. Fork这个仓库
|
||||
2. 创建您的特性分支 (`git checkout -b feature/amazing-feature`)
|
||||
3. 提交您的更改 (`git commit -m '添加一些很棒的特性'`)
|
||||
4. 推送到分支 (`git push origin feature/amazing-feature`)
|
||||
5. 打开Pull Request
|
||||
|
||||
## 🐛 问题与支持
|
||||
|
||||
如果您遇到任何问题或有疑问,请[提交issue](https://github.com/cv-cat/LarkAgentX/issues)或访问我们的[讨论论坛](https://github.com/cv-cat/LarkAgentX/discussions)。
|
||||
|
||||
## 📈 Star 趋势
|
||||
<a href="https://www.star-history.com/#cv-cat/LarkAgentX&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=cv-cat/LarkAgentX&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=cv-cat/LarkAgentX&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=cv-cat/LarkAgentX&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
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
|
||||
0
builder/__init__.py
Normal file
0
builder/__init__.py
Normal file
257
builder/header.py
Normal file
257
builder/header.py
Normal file
@ -0,0 +1,257 @@
|
||||
from app.utils.lark_utils import generate_request_id, generate_long_request_id
|
||||
|
||||
class Header:
|
||||
def __init__(self):
|
||||
self.headers = {}
|
||||
|
||||
def set_header(self, key, value):
|
||||
self.headers[key] = value
|
||||
|
||||
def set_header_from_dict(self, kv):
|
||||
for k, v in kv.items():
|
||||
self.set_header(k, v)
|
||||
|
||||
def remove_header(self, key):
|
||||
if key in self.headers:
|
||||
del self.headers[key]
|
||||
|
||||
def get(self):
|
||||
return self.headers
|
||||
|
||||
class HeaderBuilder:
|
||||
@staticmethod
|
||||
def build_common_header():
|
||||
common_header = {
|
||||
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"cache-control": "max-age=0",
|
||||
"priority": "u=0, i",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "document",
|
||||
"sec-fetch-mode": "navigate",
|
||||
"sec-fetch-site": "same-origin",
|
||||
"sec-fetch-user": "?1",
|
||||
"upgrade-insecure-requests": "1",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(common_header)
|
||||
return header
|
||||
|
||||
@staticmethod
|
||||
def build_get_csrf_token_header():
|
||||
get_csrf_token_header = {
|
||||
"accept": "application/json, text/plain, */*",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"cache-control": "no-cache",
|
||||
"content-length": "0",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-api-version": "1.0.8",
|
||||
"x-app-id": "12",
|
||||
"x-device-info": "platform=websdk",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-request-id": generate_request_id(),
|
||||
"x-terminal-type": "2"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(get_csrf_token_header)
|
||||
return header
|
||||
|
||||
@staticmethod
|
||||
def build_get_user_info_header(x_csrf_token):
|
||||
get_user_info_header = {
|
||||
"accept": "application/json, text/plain, */*",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"cache-control": "no-cache",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-api-version": "1.0.8",
|
||||
"x-app-id": "12",
|
||||
"x-csrf-token": x_csrf_token,
|
||||
"x-device-info": "platform=websdk",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-locale": "zh-CN",
|
||||
"x-request-id": generate_long_request_id(),
|
||||
"x-terminal-type": "2"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(get_user_info_header)
|
||||
return header
|
||||
|
||||
@staticmethod
|
||||
def build_send_msg_header():
|
||||
send_msg_header = {
|
||||
"accept": "*/*",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"content-type": "application/x-protobuf",
|
||||
"locale": "zh_CN",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-appid": "161471",
|
||||
"x-command": "5",
|
||||
"x-command-version": "5.7.0",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-request-id": generate_request_id(),
|
||||
"x-source": "web",
|
||||
"x-web-version": "3.9.32"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(send_msg_header)
|
||||
return header
|
||||
|
||||
@staticmethod
|
||||
def build_create_chat_header():
|
||||
create_chat_header = {
|
||||
"accept": "*/*",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"content-type": "application/x-protobuf",
|
||||
"locale": "zh_CN",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-appid": "161471",
|
||||
"x-command": "13",
|
||||
"x-command-version": "2.7.0",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-request-id": generate_request_id(),
|
||||
"x-source": "web",
|
||||
"x-web-version": "3.9.32"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(create_chat_header)
|
||||
return header
|
||||
|
||||
|
||||
@staticmethod
|
||||
def build_search_header():
|
||||
search_header = {
|
||||
"accept": "*/*",
|
||||
"accept-encoding": "gzip, deflate, br, zstd",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"content-length": "117",
|
||||
"content-type": "application/x-protobuf",
|
||||
"locale": "zh_CN",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-appid": "161471",
|
||||
"x-command": "11021",
|
||||
"x-command-version": "2.7.0",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-request-id": generate_request_id(),
|
||||
"x-source": "web",
|
||||
"x-web-version": "3.9.32"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(search_header)
|
||||
return header
|
||||
|
||||
@staticmethod
|
||||
def build_get_user_all_name_header():
|
||||
search_header = {
|
||||
"accept": "*/*",
|
||||
"accept-encoding": "gzip, deflate, br, zstd",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"content-length": "117",
|
||||
"content-type": "application/x-protobuf",
|
||||
"locale": "zh_CN",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-appid": "161471",
|
||||
"x-command": "5023",
|
||||
"x-command-version": "2.7.0",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-request-id": generate_request_id(),
|
||||
"x-source": "web",
|
||||
"x-web-version": "3.9.32"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(search_header)
|
||||
return header
|
||||
|
||||
@staticmethod
|
||||
def build_get_group_name_header():
|
||||
search_header = {
|
||||
"accept": "*/*",
|
||||
"accept-encoding": "gzip, deflate, br, zstd",
|
||||
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
|
||||
"content-length": "117",
|
||||
"content-type": "application/x-protobuf",
|
||||
"locale": "zh_CN",
|
||||
"origin": "https://open-dev.feishu.cn",
|
||||
"priority": "u=1, i",
|
||||
"referer": "https://open-dev.feishu.cn/",
|
||||
"sec-ch-ua": "\"Microsoft Edge\";v=\"125\", \"Chromium\";v=\"125\", \"Not.A/Brand\";v=\"24\"",
|
||||
"sec-ch-ua-mobile": "?0",
|
||||
"sec-ch-ua-platform": "\"Windows\"",
|
||||
"sec-fetch-dest": "empty",
|
||||
"sec-fetch-mode": "cors",
|
||||
"sec-fetch-site": "same-site",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
|
||||
"x-appid": "161471",
|
||||
"x-command": "64",
|
||||
"x-command-version": "2.7.0",
|
||||
"x-lgw-os-type": "1",
|
||||
"x-lgw-terminal-type": "2",
|
||||
"x-request-id": generate_request_id(),
|
||||
"x-source": "web",
|
||||
"x-web-version": "3.9.32"
|
||||
}
|
||||
header = Header()
|
||||
header.set_header_from_dict(search_header)
|
||||
return header
|
||||
76
builder/params.py
Normal file
76
builder/params.py
Normal file
@ -0,0 +1,76 @@
|
||||
import re
|
||||
import time
|
||||
import requests
|
||||
from builder.header import HeaderBuilder
|
||||
from app.utils.lark_utils import generate_access_key, generate_request_id
|
||||
|
||||
|
||||
class Params:
|
||||
def __init__(self):
|
||||
self.params = {}
|
||||
|
||||
def add_param_by_dict(self, params):
|
||||
self.params.update(params)
|
||||
|
||||
def add_param(self, key, value):
|
||||
self.params[key] = value
|
||||
|
||||
def get(self):
|
||||
return self.params
|
||||
|
||||
|
||||
class ParamsBuilder:
|
||||
base_url = 'https://open-dev.feishu.cn/messenger/'
|
||||
get_ticket_url = "https://login.feishu.cn/suite/passport/frontier_ticket/"
|
||||
|
||||
@staticmethod
|
||||
def build_receive_msg_param(auth):
|
||||
params = Params()
|
||||
headers = HeaderBuilder.build_common_header().get()
|
||||
|
||||
cookies = auth.cookie
|
||||
deviceid = cookies.get('passport_web_did')
|
||||
res = requests.get(ParamsBuilder.base_url, cookies=cookies, headers=headers)
|
||||
res_text = res.text
|
||||
appKey = re.findall(r'appKey: "(.*?)"', res_text)[0]
|
||||
mystr = f'2{appKey}{deviceid}f8a69f1719916z'
|
||||
access_key = generate_access_key(mystr)
|
||||
request_id = generate_request_id()
|
||||
params.add_param("local_device_id", deviceid)
|
||||
|
||||
response = requests.get(ParamsBuilder.get_ticket_url, headers=headers, cookies=cookies, params=params.get())
|
||||
res_json = response.json()
|
||||
ticket = res_json.get('ticket')
|
||||
|
||||
params = Params()
|
||||
params.add_param_by_dict({
|
||||
"access_key": access_key,
|
||||
"aid": "1",
|
||||
"ticket": ticket,
|
||||
"device_id": deviceid,
|
||||
"fpid": "2",
|
||||
"accept_encoding": "gzip",
|
||||
"request_id": request_id
|
||||
})
|
||||
return params
|
||||
|
||||
@staticmethod
|
||||
def build_get_user_info_param():
|
||||
params = Params()
|
||||
params.add_param_by_dict({
|
||||
"app_id": "12",
|
||||
"_t": str(int(time.time() * 1000))
|
||||
})
|
||||
return params
|
||||
|
||||
@staticmethod
|
||||
def build_get_csrf_token_param():
|
||||
params = Params()
|
||||
params.add_param_by_dict({
|
||||
"_t": str(int(time.time() * 1000))
|
||||
})
|
||||
return params
|
||||
|
||||
@classmethod
|
||||
def build_get_other_user_info_param(cls, user_id):
|
||||
pass
|
||||
276
builder/proto.py
Normal file
276
builder/proto.py
Normal file
@ -0,0 +1,276 @@
|
||||
import json
|
||||
|
||||
import static.proto_pb2 as FLY_BOOK_PROTO
|
||||
from protobuf_to_dict import protobuf_to_dict
|
||||
from app.utils.lark_utils import generate_request_cid
|
||||
|
||||
class ProtoBuilder:
|
||||
@staticmethod
|
||||
def build_send_message_request_proto(sends_text, request_id, chatId):
|
||||
cid_1 = generate_request_cid()
|
||||
cid_2 = generate_request_cid()
|
||||
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.payloadType = 1
|
||||
Packet.cmd = 5
|
||||
Packet.cid = request_id
|
||||
|
||||
PutMessageRequest = FLY_BOOK_PROTO.PutMessageRequest()
|
||||
PutMessageRequest.type = 4
|
||||
PutMessageRequest.chatId = chatId
|
||||
PutMessageRequest.cid = cid_1
|
||||
PutMessageRequest.isNotified = 1
|
||||
PutMessageRequest.version = 1
|
||||
|
||||
PutMessageRequest.content.richText.elementIds.append(cid_2)
|
||||
PutMessageRequest.content.richText.innerText = sends_text
|
||||
PutMessageRequest.content.richText.elements.dictionary[cid_2].tag = 1
|
||||
|
||||
TextProperty = FLY_BOOK_PROTO.TextProperty()
|
||||
TextProperty.content = str(sends_text)
|
||||
PutMessageRequest.content.richText.elements.dictionary[cid_2].property = TextProperty.SerializeToString()
|
||||
|
||||
Packet.payload = PutMessageRequest.SerializeToString()
|
||||
return Packet
|
||||
|
||||
@staticmethod
|
||||
def build_search_request_proto(request_id, query):
|
||||
request_cid = generate_request_cid()
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.payloadType = 1
|
||||
Packet.cmd = 11021
|
||||
Packet.cid = request_id
|
||||
|
||||
UniversalSearchRequest = FLY_BOOK_PROTO.UniversalSearchRequest()
|
||||
UniversalSearchRequest.header.searchSession = request_cid
|
||||
UniversalSearchRequest.header.sessionSeqId = 1
|
||||
UniversalSearchRequest.header.query = query
|
||||
UniversalSearchRequest.header.searchContext.tagName = 'SMART_SEARCH'
|
||||
|
||||
EntityItem_1 = FLY_BOOK_PROTO.EntityItem()
|
||||
EntityItem_1.type = 1
|
||||
# EntityItem_1.filter.userFilter.isResigned = 1
|
||||
# EntityItem_1.filter.userFilter.haveChatter = 0
|
||||
# EntityItem_1.filter.userFilter.exclude = 1
|
||||
|
||||
EntityItem_2 = FLY_BOOK_PROTO.EntityItem()
|
||||
EntityItem_2.type = 2
|
||||
EntityFilter = FLY_BOOK_PROTO.EntityItem.EntityFilter()
|
||||
EntityItem_2.filter.CopyFrom(EntityFilter)
|
||||
|
||||
EntityItem_3 = FLY_BOOK_PROTO.EntityItem()
|
||||
GroupChatFilter = FLY_BOOK_PROTO.GroupChatFilter()
|
||||
EntityItem_3.type = 3
|
||||
EntityItem_3.filter.groupChatFilter.CopyFrom(GroupChatFilter)
|
||||
|
||||
EntityItem_4 = FLY_BOOK_PROTO.EntityItem()
|
||||
EntityItem_4.type = 10
|
||||
EntityFilter = FLY_BOOK_PROTO.EntityItem.EntityFilter()
|
||||
EntityItem_4.filter.CopyFrom(EntityFilter)
|
||||
|
||||
UniversalSearchRequest.header.searchContext.entityItems.append(EntityItem_1)
|
||||
UniversalSearchRequest.header.searchContext.entityItems.append(EntityItem_2)
|
||||
UniversalSearchRequest.header.searchContext.entityItems.append(EntityItem_3)
|
||||
UniversalSearchRequest.header.searchContext.entityItems.append(EntityItem_4)
|
||||
UniversalSearchRequest.header.searchContext.commonFilter.includeOuterTenant = 1
|
||||
UniversalSearchRequest.header.searchContext.sourceKey = 'messenger'
|
||||
UniversalSearchRequest.header.locale = 'zh_CN'
|
||||
SearchExtraParam = FLY_BOOK_PROTO.SearchExtraParam()
|
||||
UniversalSearchRequest.header.extraParam.CopyFrom(SearchExtraParam)
|
||||
Packet.payload = UniversalSearchRequest.SerializeToString()
|
||||
return Packet
|
||||
|
||||
@staticmethod
|
||||
def decode_search_response_proto(message):
|
||||
userAndGroupIds = []
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.ParseFromString(message)
|
||||
Packet = protobuf_to_dict(Packet)
|
||||
if 'payload' in Packet:
|
||||
payload = Packet['payload']
|
||||
UniversalSearchResponse = FLY_BOOK_PROTO.UniversalSearchResponse()
|
||||
UniversalSearchResponse.ParseFromString(payload)
|
||||
UniversalSearchResponse = protobuf_to_dict(UniversalSearchResponse)
|
||||
Packet['payload'] = UniversalSearchResponse
|
||||
|
||||
for result in UniversalSearchResponse['results']:
|
||||
if result['type'] == 1:
|
||||
userAndGroupIds.append({
|
||||
'type': 'user',
|
||||
'id': result['id']
|
||||
})
|
||||
elif result['type'] == 3:
|
||||
userAndGroupIds.append({
|
||||
'type': 'group',
|
||||
'id': result['id']
|
||||
})
|
||||
|
||||
return Packet, userAndGroupIds
|
||||
|
||||
|
||||
@staticmethod
|
||||
def build_create_chat_request_proto(request_id, chatId):
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.payloadType = 1
|
||||
Packet.cmd = 13
|
||||
Packet.cid = request_id
|
||||
|
||||
PutChatRequest = FLY_BOOK_PROTO.PutChatRequest()
|
||||
PutChatRequest.type = 1
|
||||
PutChatRequest.chatterIds.append(chatId)
|
||||
Packet.payload = PutChatRequest.SerializeToString()
|
||||
return Packet
|
||||
|
||||
@staticmethod
|
||||
def decode_create_chat_response_proto(message):
|
||||
chatId = None
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.ParseFromString(message)
|
||||
Packet = protobuf_to_dict(Packet)
|
||||
if 'payload' in Packet:
|
||||
payload = Packet['payload']
|
||||
PutChatResponse = FLY_BOOK_PROTO.PutChatResponse()
|
||||
PutChatResponse.ParseFromString(payload)
|
||||
PutChatResponse = protobuf_to_dict(PutChatResponse)
|
||||
Packet['payload'] = PutChatResponse
|
||||
chatId = PutChatResponse['chat']['id']
|
||||
return Packet, chatId
|
||||
|
||||
@staticmethod
|
||||
def extra_packet_id(message):
|
||||
Frame = FLY_BOOK_PROTO.Frame()
|
||||
Frame.ParseFromString(message)
|
||||
Frame = protobuf_to_dict(Frame)
|
||||
payload = Frame['payload']
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.ParseFromString(payload)
|
||||
Packet = protobuf_to_dict(Packet)
|
||||
Frame['payload'] = Packet
|
||||
packet_id = Packet['sid']
|
||||
return packet_id
|
||||
|
||||
@staticmethod
|
||||
def decode_receive_msg_proto(message):
|
||||
ReceiveTextContent = {
|
||||
'fromId': None,
|
||||
'chatId': None,
|
||||
'chatType': None,
|
||||
'content': None
|
||||
}
|
||||
Frame = FLY_BOOK_PROTO.Frame()
|
||||
Frame.ParseFromString(message)
|
||||
Frame = protobuf_to_dict(Frame)
|
||||
payload = Frame['payload']
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.ParseFromString(payload)
|
||||
Packet = protobuf_to_dict(Packet)
|
||||
Frame['payload'] = Packet
|
||||
Packet_sid = Packet['sid']
|
||||
if 'payload' in Packet:
|
||||
payload = Packet['payload']
|
||||
PushMessagesRequest = FLY_BOOK_PROTO.PushMessagesRequest()
|
||||
PushMessagesRequest.ParseFromString(payload)
|
||||
PushMessagesRequest = protobuf_to_dict(PushMessagesRequest)
|
||||
Packet['payload'] = PushMessagesRequest
|
||||
if 'messages' in PushMessagesRequest:
|
||||
messages = PushMessagesRequest['messages']
|
||||
for k, v in messages.items():
|
||||
message_type = v['type']
|
||||
fromId = v['fromId']
|
||||
content = v['content']
|
||||
chatId = v['chatId']
|
||||
chatType = v['chatType']
|
||||
ReceiveTextContent['fromId'] = fromId
|
||||
ReceiveTextContent['chatId'] = chatId
|
||||
ReceiveTextContent['chatType'] = chatType
|
||||
if message_type == 4:
|
||||
receive_content = ''
|
||||
TextContent = FLY_BOOK_PROTO.TextContent()
|
||||
TextContent.ParseFromString(content)
|
||||
TextContent = protobuf_to_dict(TextContent)
|
||||
v['content'] = TextContent
|
||||
dictionary = TextContent['richText']['elements']['dictionary']
|
||||
try:
|
||||
dictionary = dict(sorted(dictionary.items(), key=lambda item: int(item[0])))
|
||||
except:
|
||||
pass
|
||||
for k, v in dictionary.items():
|
||||
property = v['property']
|
||||
TextProperty = FLY_BOOK_PROTO.TextProperty()
|
||||
TextProperty.ParseFromString(property)
|
||||
TextProperty = protobuf_to_dict(TextProperty)
|
||||
v['property'] = TextProperty
|
||||
receive_content += TextProperty['content']
|
||||
ReceiveTextContent['content'] = receive_content
|
||||
return ReceiveTextContent
|
||||
|
||||
@staticmethod
|
||||
def build_get_user_all_name_request_proto(request_id, user_id, chatId):
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.payloadType = 1
|
||||
Packet.cmd = 5023
|
||||
Packet.cid = request_id
|
||||
|
||||
GetUserInfoRequest = FLY_BOOK_PROTO.GetUserInfoRequest()
|
||||
GetUserInfoRequest.userId = int(user_id)
|
||||
GetUserInfoRequest.chatId = int(chatId)
|
||||
GetUserInfoRequest.userType = 1
|
||||
|
||||
Packet.payload = GetUserInfoRequest.SerializeToString()
|
||||
return Packet
|
||||
|
||||
@staticmethod
|
||||
def decode_info_response_proto(message):
|
||||
translation = None
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
|
||||
Packet.ParseFromString(message)
|
||||
Packet = protobuf_to_dict(Packet)
|
||||
if 'payload' in Packet:
|
||||
payload = Packet['payload']
|
||||
UserInfo = FLY_BOOK_PROTO.UserInfo()
|
||||
UserInfo.ParseFromString(payload)
|
||||
UserInfo = protobuf_to_dict(UserInfo)
|
||||
Packet['payload'] = UserInfo
|
||||
detail = UserInfo['userInfoDetail']['detail']
|
||||
translation = detail['nickname'] if 'nickname' in detail else None
|
||||
locales = detail['locales']
|
||||
for locale in locales:
|
||||
if locale['key_string'] == 'zh_cn':
|
||||
translation = locale['translation']
|
||||
break
|
||||
return translation
|
||||
|
||||
@staticmethod
|
||||
def decode_group_info_response_proto(message):
|
||||
nickname = None
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
|
||||
Packet.ParseFromString(message)
|
||||
Packet = protobuf_to_dict(Packet)
|
||||
if 'payload' in Packet:
|
||||
payload = Packet['payload']
|
||||
UserInfo = FLY_BOOK_PROTO.UserInfo()
|
||||
UserInfo.ParseFromString(payload)
|
||||
UserInfo = protobuf_to_dict(UserInfo)
|
||||
Packet['payload'] = UserInfo
|
||||
detail = UserInfo['userInfoDetail']['detail']
|
||||
nickname = detail['nickname1'] if 'nickname1' in detail else None
|
||||
if not nickname:
|
||||
nickname = detail['nickname4'] if 'nickname4' in detail else None
|
||||
if nickname:
|
||||
nickname = nickname.decode('utf-8')
|
||||
return nickname
|
||||
|
||||
@staticmethod
|
||||
def build_get_group_name_request_proto(request_id, chatId):
|
||||
Packet = FLY_BOOK_PROTO.Packet()
|
||||
Packet.payloadType = 1
|
||||
Packet.cmd = 64
|
||||
Packet.cid = request_id
|
||||
|
||||
GetGroupInfoRequest = FLY_BOOK_PROTO.GetGroupInfoRequest()
|
||||
GetGroupInfoRequest.chatId = str(chatId)
|
||||
|
||||
Packet.payload = GetGroupInfoRequest.SerializeToString()
|
||||
return Packet
|
||||
45
docker-compose.yml
Normal file
45
docker-compose.yml
Normal file
@ -0,0 +1,45 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: lark-mcp-app
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "5000:5000"
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
- db
|
||||
networks:
|
||||
- lark-network
|
||||
volumes:
|
||||
- ./:/app
|
||||
- /app/node_modules
|
||||
|
||||
db:
|
||||
image: mysql:8.0
|
||||
container_name: lark-mysql
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
|
||||
MYSQL_DATABASE: ${DB_NAME}
|
||||
MYSQL_USER: ${DB_USER}
|
||||
MYSQL_PASSWORD: ${DB_PASSWORD}
|
||||
volumes:
|
||||
- mysql-data:/var/lib/mysql
|
||||
ports:
|
||||
- "3306:3306"
|
||||
networks:
|
||||
- lark-network
|
||||
command: --default-authentication-plugin=mysql_native_password --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
|
||||
|
||||
networks:
|
||||
lark-network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
mysql-data:
|
||||
driver: local
|
||||
0
extension/__init__.py
Normal file
0
extension/__init__.py
Normal file
BIN
extension/weather_api/GEOIP.db
Normal file
BIN
extension/weather_api/GEOIP.db
Normal file
Binary file not shown.
74
extension/weather_api/api.py
Normal file
74
extension/weather_api/api.py
Normal file
@ -0,0 +1,74 @@
|
||||
from datetime import datetime
|
||||
|
||||
import requests
|
||||
|
||||
from .db import select_city_code, get_weather_code
|
||||
|
||||
|
||||
def get_city_geocode(city):
|
||||
"""
|
||||
Get the geocode of a city in a province.
|
||||
"""
|
||||
return select_city_code(city)
|
||||
|
||||
def get_city_weather(city):
|
||||
"""
|
||||
Get the weather of a city in a province.
|
||||
"""
|
||||
URL = f'https://weatherapi.market.xiaomi.com/wtr-v3/weather/all'
|
||||
city_code = select_city_code(city)
|
||||
|
||||
if city_code:
|
||||
result = f'地区:{city}的天气情况\n'
|
||||
date = datetime.today().strftime('%Y%m%d')
|
||||
params = {
|
||||
'latitude': 0,
|
||||
'longitude': 0,
|
||||
'locationKey': f'weathercn:{city_code}',
|
||||
'appKey': f'weather{date}',
|
||||
'sign': 'zUFJoAR2ZVrDy1vF3D07',
|
||||
'isGlobal': 'false',
|
||||
'locale': 'zh_CN',
|
||||
'days': '1'
|
||||
}
|
||||
response = requests.get(URL, params=params, verify=False)
|
||||
data = response.json()
|
||||
current = data['current']
|
||||
temperature = current['temperature']
|
||||
result += f'温度: {temperature["value"]}{temperature["unit"]}\n'
|
||||
weather_code = current['weather']
|
||||
weather = get_weather_code(weather_code)
|
||||
result += f'当前天气: {weather}\n'
|
||||
pressure = current['pressure']
|
||||
result += f'气压: {pressure["value"]}{pressure["unit"]}\n'
|
||||
humidity = current['humidity']
|
||||
result += f'湿度: {humidity["value"]}{humidity["unit"]}\n'
|
||||
visibility = current['visibility']
|
||||
if len(visibility['value']) > 0:
|
||||
result += f'能见度: {visibility["value"]}{visibility["unit"]}\n'
|
||||
wind = current['wind']
|
||||
result += f'风向: {wind["direction"]["value"]}{wind["direction"]["unit"]}\n'
|
||||
result += f'风力: {wind["speed"]["value"]}{wind["speed"]["unit"]}\n'
|
||||
forecastDaily = data['forecastDaily']
|
||||
aqi = forecastDaily['aqi']
|
||||
if aqi['status'] == 0:
|
||||
value = aqi['value']
|
||||
result += f'今天空气质量指数: {value[0]}\n'
|
||||
precipitationProbability = forecastDaily['precipitationProbability']
|
||||
if precipitationProbability['status'] == '0':
|
||||
value = precipitationProbability['value']
|
||||
result += f'\n今天降水概率: {value[0]}\n'
|
||||
result += f'未来几天降水概率: {value[1:]}\n'
|
||||
sunRiseSet = forecastDaily['sunRiseSet']
|
||||
if sunRiseSet['status'] == 0:
|
||||
value = sunRiseSet["value"]
|
||||
result += f'今日日出时间: {value[0]["from"]}\n'
|
||||
result += f'今日日落时间: {value[0]["to"]}\n'
|
||||
temperature = forecastDaily['temperature']
|
||||
if temperature['status'] ==0:
|
||||
value = temperature['value']
|
||||
result += f'今日气温:: {min(value[0]["from"], value[0]["to"])}-{max(value[0]["to"], value[1]["from"])}{temperature["unit"]}\n'
|
||||
return result
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(get_city_weather('北京'))
|
||||
178
extension/weather_api/db.py
Normal file
178
extension/weather_api/db.py
Normal file
@ -0,0 +1,178 @@
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
DB_PATH = os.path.join(ROOT, 'GEOIP.db')
|
||||
|
||||
WEATHER_CODE = [
|
||||
{
|
||||
"code": 0,
|
||||
"wea": "晴"
|
||||
},
|
||||
{
|
||||
"code": 1,
|
||||
"wea": "多云"
|
||||
},
|
||||
{
|
||||
"code": 2,
|
||||
"wea": "阴"
|
||||
},
|
||||
{
|
||||
"code": 3,
|
||||
"wea": "阵雨"
|
||||
},
|
||||
{
|
||||
"code": 4,
|
||||
"wea": "雷阵雨"
|
||||
},
|
||||
{
|
||||
"code": 5,
|
||||
"wea": "雷阵雨并伴有冰雹"
|
||||
},
|
||||
{
|
||||
"code": 6,
|
||||
"wea": "雨夹雪"
|
||||
},
|
||||
{
|
||||
"code": 7,
|
||||
"wea": "小雨"
|
||||
},
|
||||
{
|
||||
"code": 8,
|
||||
"wea": "中雨"
|
||||
},
|
||||
{
|
||||
"code": 9,
|
||||
"wea": "大雨"
|
||||
},
|
||||
{
|
||||
"code": 10,
|
||||
"wea": "暴雨"
|
||||
},
|
||||
{
|
||||
"code": 11,
|
||||
"wea": "大暴雨"
|
||||
},
|
||||
{
|
||||
"code": 12,
|
||||
"wea": "特大暴雨"
|
||||
},
|
||||
{
|
||||
"code": 13,
|
||||
"wea": "阵雪"
|
||||
},
|
||||
{
|
||||
"code": 14,
|
||||
"wea": "小雪"
|
||||
},
|
||||
{
|
||||
"code": 15,
|
||||
"wea": "中雪"
|
||||
},
|
||||
{
|
||||
"code": 16,
|
||||
"wea": "大雪"
|
||||
},
|
||||
{
|
||||
"code": 17,
|
||||
"wea": "暴雪"
|
||||
},
|
||||
{
|
||||
"code": 18,
|
||||
"wea": "雾"
|
||||
},
|
||||
{
|
||||
"code": 19,
|
||||
"wea": "冻雨"
|
||||
},
|
||||
{
|
||||
"code": 20,
|
||||
"wea": "沙尘暴"
|
||||
},
|
||||
{
|
||||
"code": 21,
|
||||
"wea": "小雨-中雨"
|
||||
},
|
||||
{
|
||||
"code": 22,
|
||||
"wea": "中雨-大雨"
|
||||
},
|
||||
{
|
||||
"code": 23,
|
||||
"wea": "大雨-暴雨"
|
||||
},
|
||||
{
|
||||
"code": 24,
|
||||
"wea": "暴雨-大暴雨"
|
||||
},
|
||||
{
|
||||
"code": 25,
|
||||
"wea": "大暴雨-特大暴雨"
|
||||
},
|
||||
{
|
||||
"code": 26,
|
||||
"wea": "小雪-中雪"
|
||||
},
|
||||
{
|
||||
"code": 27,
|
||||
"wea": "中雪-大雪"
|
||||
},
|
||||
{
|
||||
"code": 28,
|
||||
"wea": "大雪-暴雪"
|
||||
},
|
||||
{
|
||||
"code": 29,
|
||||
"wea": "浮沉"
|
||||
},
|
||||
{
|
||||
"code": 30,
|
||||
"wea": "扬沙"
|
||||
},
|
||||
{
|
||||
"code": 31,
|
||||
"wea": "强沙尘暴"
|
||||
},
|
||||
{
|
||||
"code": 32,
|
||||
"wea": "飑"
|
||||
},
|
||||
{
|
||||
"code": 33,
|
||||
"wea": "龙卷风"
|
||||
},
|
||||
{
|
||||
"code": 34,
|
||||
"wea": "若高吹雪"
|
||||
},
|
||||
{
|
||||
"code": 35,
|
||||
"wea": "轻雾"
|
||||
},
|
||||
{
|
||||
"code": 53,
|
||||
"wea": "霾"
|
||||
},
|
||||
{
|
||||
"code": 99,
|
||||
"wea": "未知"
|
||||
}
|
||||
]
|
||||
|
||||
def get_weather_code(code):
|
||||
for item in WEATHER_CODE:
|
||||
if item['code'] == int(code):
|
||||
return item['wea']
|
||||
return '未知'
|
||||
|
||||
def select_city_code(city):
|
||||
city = city.replace('市','')
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
cursor = conn.cursor()
|
||||
result = cursor.execute("SELECT city_num FROM citys WHERE name like ?", (f'{city}',))
|
||||
city_num = result.fetchone()
|
||||
if city_num:
|
||||
return city_num[0]
|
||||
else:
|
||||
return None
|
||||
73
main.py
Normal file
73
main.py
Normal file
@ -0,0 +1,73 @@
|
||||
"""
|
||||
Lark Message Recorder - Main Entry Point
|
||||
Records all received Lark messages to a MySQL database.
|
||||
"""
|
||||
import multiprocessing
|
||||
import sys
|
||||
import asyncio
|
||||
from loguru import logger
|
||||
|
||||
def start_mcp_server():
|
||||
"""Start the MCP server in a separate process"""
|
||||
logger.info("Starting MCP server...")
|
||||
from app.core.mcp_server import mcp
|
||||
mcp.run(transport="stdio")
|
||||
|
||||
async def main():
|
||||
"""Main function to run the Lark message recorder"""
|
||||
from app.db.session import init_db
|
||||
from app.api.auth import get_auth
|
||||
from app.api.lark_client import LarkClient
|
||||
from app.core.message_service import MessageService
|
||||
mcp_process = multiprocessing.Process(target=start_mcp_server)
|
||||
mcp_process.daemon = True
|
||||
mcp_process.start()
|
||||
|
||||
logger.info("初始化数据库...")
|
||||
try:
|
||||
init_db()
|
||||
logger.info("数据库初始化成功.")
|
||||
except Exception as e:
|
||||
logger.error(f"数据库初始化失败: {str(e)}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.info("初始化认证...")
|
||||
try:
|
||||
auth = get_auth()
|
||||
logger.info("认证初始化成功.")
|
||||
except Exception as e:
|
||||
logger.error(f"认证初始化失败: {str(e)}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.info("创建 Lark 客户端...")
|
||||
try:
|
||||
lark_client = LarkClient(auth)
|
||||
logger.info("Lark 客户端创建成功.")
|
||||
except Exception as e:
|
||||
logger.error(f"Lark 客户端创建失败: {str(e)}")
|
||||
sys.exit(1)
|
||||
|
||||
logger.info("创建消息服务...")
|
||||
message_service = MessageService(lark_client)
|
||||
|
||||
try:
|
||||
logger.info("连接到 Lark WebSocket...")
|
||||
logger.info("开始接收消息...")
|
||||
logger.info('================================================================')
|
||||
await lark_client.connect_websocket(message_service.process_message)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("程序被用户中断.")
|
||||
except Exception as e:
|
||||
logger.error(f"连接到 Lark WebSocket 失败: {str(e)}")
|
||||
sys.exit(1)
|
||||
finally:
|
||||
message_service.close()
|
||||
logger.info("消息服务关闭.")
|
||||
if mcp_process.is_alive():
|
||||
logger.info("Shutting down MCP server...")
|
||||
mcp_process.terminate()
|
||||
mcp_process.join()
|
||||
logger.info("MCP server shut down.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
14
requirements.txt
Normal file
14
requirements.txt
Normal file
@ -0,0 +1,14 @@
|
||||
loguru==0.7.3
|
||||
mcp==1.6.0
|
||||
openai==1.74.0
|
||||
protobuf==5.29.3
|
||||
protobuf3-to-dict==0.1.5
|
||||
PyExecJS==1.5.1
|
||||
PyMySQL==1.1.0
|
||||
python-dotenv==1.1.0
|
||||
requests==2.31.0
|
||||
SQLAlchemy==2.0.30
|
||||
websockets==15.0.1
|
||||
fastmcp==2.1.2
|
||||
Brotli==1.1.0
|
||||
cryptography==44.0.2
|
||||
0
static/__init__.py
Normal file
0
static/__init__.py
Normal file
183
static/lark_decrypt.js
Normal file
183
static/lark_decrypt.js
Normal file
@ -0,0 +1,183 @@
|
||||
function T(e, t) {
|
||||
var n = (65535 & e) + (65535 & t);
|
||||
return (e >> 16) + (t >> 16) + (n >> 16) << 16 | 65535 & n
|
||||
}
|
||||
function f(e, t, n, i, r, a) {
|
||||
return T((o = T(T(t, e), T(i, a))) << (s = r) | o >>> 32 - s, n);
|
||||
var o, s
|
||||
}
|
||||
function h(e, t, n, i, r, a, o) {
|
||||
return f(t & n | ~t & i, e, t, r, a, o)
|
||||
}
|
||||
function y(e, t, n, i, r, a, o) {
|
||||
return f(t & i | n & ~i, e, t, r, a, o)
|
||||
}
|
||||
function S(e, t, n, i, r, a, o) {
|
||||
return f(t ^ n ^ i, e, t, r, a, o)
|
||||
}
|
||||
function A(e, t, n, i, r, a, o) {
|
||||
return f(n ^ (t | ~i), e, t, r, a, o)
|
||||
}
|
||||
function g(e, t) {
|
||||
var n, i, r, a, o;
|
||||
e[t >> 5] |= 128 << t % 32,
|
||||
e[14 + (t + 64 >>> 9 << 4)] = t;
|
||||
var s = 1732584193
|
||||
, c = -271733879
|
||||
, d = -1732584194
|
||||
, l = 271733878;
|
||||
for (n = 0; n < e.length; n += 16)
|
||||
i = s,
|
||||
r = c,
|
||||
a = d,
|
||||
o = l,
|
||||
s = h(s, c, d, l, e[n], 7, -680876936),
|
||||
l = h(l, s, c, d, e[n + 1], 12, -389564586),
|
||||
d = h(d, l, s, c, e[n + 2], 17, 606105819),
|
||||
c = h(c, d, l, s, e[n + 3], 22, -1044525330),
|
||||
s = h(s, c, d, l, e[n + 4], 7, -176418897),
|
||||
l = h(l, s, c, d, e[n + 5], 12, 1200080426),
|
||||
d = h(d, l, s, c, e[n + 6], 17, -1473231341),
|
||||
c = h(c, d, l, s, e[n + 7], 22, -45705983),
|
||||
s = h(s, c, d, l, e[n + 8], 7, 1770035416),
|
||||
l = h(l, s, c, d, e[n + 9], 12, -1958414417),
|
||||
d = h(d, l, s, c, e[n + 10], 17, -42063),
|
||||
c = h(c, d, l, s, e[n + 11], 22, -1990404162),
|
||||
s = h(s, c, d, l, e[n + 12], 7, 1804603682),
|
||||
l = h(l, s, c, d, e[n + 13], 12, -40341101),
|
||||
d = h(d, l, s, c, e[n + 14], 17, -1502002290),
|
||||
s = y(s, c = h(c, d, l, s, e[n + 15], 22, 1236535329), d, l, e[n + 1], 5, -165796510),
|
||||
l = y(l, s, c, d, e[n + 6], 9, -1069501632),
|
||||
d = y(d, l, s, c, e[n + 11], 14, 643717713),
|
||||
c = y(c, d, l, s, e[n], 20, -373897302),
|
||||
s = y(s, c, d, l, e[n + 5], 5, -701558691),
|
||||
l = y(l, s, c, d, e[n + 10], 9, 38016083),
|
||||
d = y(d, l, s, c, e[n + 15], 14, -660478335),
|
||||
c = y(c, d, l, s, e[n + 4], 20, -405537848),
|
||||
s = y(s, c, d, l, e[n + 9], 5, 568446438),
|
||||
l = y(l, s, c, d, e[n + 14], 9, -1019803690),
|
||||
d = y(d, l, s, c, e[n + 3], 14, -187363961),
|
||||
c = y(c, d, l, s, e[n + 8], 20, 1163531501),
|
||||
s = y(s, c, d, l, e[n + 13], 5, -1444681467),
|
||||
l = y(l, s, c, d, e[n + 2], 9, -51403784),
|
||||
d = y(d, l, s, c, e[n + 7], 14, 1735328473),
|
||||
s = S(s, c = y(c, d, l, s, e[n + 12], 20, -1926607734), d, l, e[n + 5], 4, -378558),
|
||||
l = S(l, s, c, d, e[n + 8], 11, -2022574463),
|
||||
d = S(d, l, s, c, e[n + 11], 16, 1839030562),
|
||||
c = S(c, d, l, s, e[n + 14], 23, -35309556),
|
||||
s = S(s, c, d, l, e[n + 1], 4, -1530992060),
|
||||
l = S(l, s, c, d, e[n + 4], 11, 1272893353),
|
||||
d = S(d, l, s, c, e[n + 7], 16, -155497632),
|
||||
c = S(c, d, l, s, e[n + 10], 23, -1094730640),
|
||||
s = S(s, c, d, l, e[n + 13], 4, 681279174),
|
||||
l = S(l, s, c, d, e[n], 11, -358537222),
|
||||
d = S(d, l, s, c, e[n + 3], 16, -722521979),
|
||||
c = S(c, d, l, s, e[n + 6], 23, 76029189),
|
||||
s = S(s, c, d, l, e[n + 9], 4, -640364487),
|
||||
l = S(l, s, c, d, e[n + 12], 11, -421815835),
|
||||
d = S(d, l, s, c, e[n + 15], 16, 530742520),
|
||||
s = A(s, c = S(c, d, l, s, e[n + 2], 23, -995338651), d, l, e[n], 6, -198630844),
|
||||
l = A(l, s, c, d, e[n + 7], 10, 1126891415),
|
||||
d = A(d, l, s, c, e[n + 14], 15, -1416354905),
|
||||
c = A(c, d, l, s, e[n + 5], 21, -57434055),
|
||||
s = A(s, c, d, l, e[n + 12], 6, 1700485571),
|
||||
l = A(l, s, c, d, e[n + 3], 10, -1894986606),
|
||||
d = A(d, l, s, c, e[n + 10], 15, -1051523),
|
||||
c = A(c, d, l, s, e[n + 1], 21, -2054922799),
|
||||
s = A(s, c, d, l, e[n + 8], 6, 1873313359),
|
||||
l = A(l, s, c, d, e[n + 15], 10, -30611744),
|
||||
d = A(d, l, s, c, e[n + 6], 15, -1560198380),
|
||||
c = A(c, d, l, s, e[n + 13], 21, 1309151649),
|
||||
s = A(s, c, d, l, e[n + 4], 6, -145523070),
|
||||
l = A(l, s, c, d, e[n + 11], 10, -1120210379),
|
||||
d = A(d, l, s, c, e[n + 2], 15, 718787259),
|
||||
c = A(c, d, l, s, e[n + 9], 21, -343485551),
|
||||
s = T(s, i),
|
||||
c = T(c, r),
|
||||
d = T(d, a),
|
||||
l = T(l, o);
|
||||
return [s, c, d, l]
|
||||
}
|
||||
function I(e) {
|
||||
var t, n = "", i = 32 * e.length;
|
||||
for (t = 0; t < i; t += 8)
|
||||
n += String.fromCharCode(e[t >> 5] >>> t % 32 & 255);
|
||||
return n
|
||||
}
|
||||
function m(e) {
|
||||
var t, n = [];
|
||||
for (n[(e.length >> 2) - 1] = void 0,
|
||||
t = 0; t < n.length; t += 1)
|
||||
n[t] = 0;
|
||||
var i = 8 * e.length;
|
||||
for (t = 0; t < i; t += 8)
|
||||
n[t >> 5] |= (255 & e.charCodeAt(t / 8)) << t % 32;
|
||||
return n
|
||||
}
|
||||
function C(e) {
|
||||
var t, n, i = "";
|
||||
for (n = 0; n < e.length; n += 1)
|
||||
t = e.charCodeAt(n),
|
||||
i += "0123456789abcdef".charAt(t >>> 4 & 15) + "0123456789abcdef".charAt(15 & t);
|
||||
return i
|
||||
}
|
||||
function N(e) {
|
||||
return unescape(encodeURIComponent(e))
|
||||
}
|
||||
function O(e) {
|
||||
return function(e) {
|
||||
return I(g(m(e), 8 * e.length))
|
||||
}(N(e))
|
||||
}
|
||||
function generate_access_key(e) {
|
||||
return C(O(e))
|
||||
}
|
||||
|
||||
|
||||
// request_id
|
||||
function generate_request_id() {
|
||||
return (Math.random().toString(36) + "0000000000").substring(2, 2 + "0000000000".length)
|
||||
}
|
||||
|
||||
function generate_long_request_id() {
|
||||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (function(e) {
|
||||
var t = 16 * Math.random() | 0;
|
||||
return ("x" === e ? t : 3 & t | 8).toString(16)
|
||||
}
|
||||
))
|
||||
}
|
||||
// request_cid and session_id
|
||||
function generate_request_cid() {
|
||||
let e = 10, t = undefined
|
||||
const n = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("")
|
||||
, i = [];
|
||||
let r = null
|
||||
, a = null
|
||||
, o = null;
|
||||
const s = n.length;
|
||||
if (t = (t = t || s) > s ? s : t,
|
||||
e)
|
||||
for (r = 0; r < e; r++)
|
||||
o = 0 | Math.random() * t,
|
||||
i[r] = n[o];
|
||||
else
|
||||
for (i[8] = "-",
|
||||
i[13] = "-",
|
||||
i[18] = "-",
|
||||
i[23] = "-",
|
||||
i[14] = "4",
|
||||
r = 0; r < 36; r++)
|
||||
i[r] || (a = 0 | 16 * Math.random(),
|
||||
i[r] = n[19 === r ? 3 & a | 8 : a]);
|
||||
return i.join("")
|
||||
}
|
||||
|
||||
|
||||
function generate_csrf_token() {
|
||||
let e = "swp_csrf_token"
|
||||
let document = {
|
||||
cookie: "locale=zh-CN; _gcl_au=1.1.1773137480.1713790863; _ga=GA1.1.252483876.1713790863; _ga_VPYRHN104D=GS1.1.1713790863.1.1.1713790872.51.0.0; lang=zh; __tea__ug__uid=1007701713790873353; et=5149005c67cbe62db3d7f613bb9c7440; Hm_lvt_e78c0cb1b97ef970304b53d2097845fd=1716609558; i18n_locale=zh-CN; _csrf_token=36b375aad3381c672c2752df4c2f78c9bc1b51ae-1716787751; ccm_cdn_host=//lf-scm-cn.feishucdn.com; MONITOR_WEB_ID=eb362632-773d-4a6c-b3f7-fd69a73f80e1; msToken=1aL_Z6EfXm8A5YvLxai6CT2XUrk4rk-TS1Tr9VEIqx5dwdqXD_raGfMXYFZPQr3B_aVm00bKlLyYQ6fw2u-BHADiWT81bCZ2Vfft2Dm0_AzIVT8PUcoBPjUu0STE1Q==; swp_csrf_token=b2f409f7-fd71-4915-bf04-9248fcedd78d"
|
||||
}
|
||||
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*".concat(encodeURIComponent(e).replace(/[-.+*]/g, "\\$&"), "\\s*\\=\\s*([^;]*).*$)|^.*$")), "$1")) || ""
|
||||
}
|
||||
|
||||
855
static/proto.proto
Normal file
855
static/proto.proto
Normal file
@ -0,0 +1,855 @@
|
||||
syntax = "proto3";
|
||||
|
||||
|
||||
|
||||
message Frame {
|
||||
optional uint64 seqid = 1;
|
||||
optional uint64 logid = 2;
|
||||
optional int32 service = 3;
|
||||
optional int32 method = 4;
|
||||
repeated ExtendedEntry headers = 5;
|
||||
optional string payloadEncoding = 6;
|
||||
optional string payloadType = 7;
|
||||
optional bytes payload = 8;
|
||||
}
|
||||
|
||||
message Packet {
|
||||
optional string sid = 1;
|
||||
optional PayloadType payloadType = 2;
|
||||
optional int32 cmd = 3;
|
||||
optional uint32 status = 4;
|
||||
optional bytes payload = 5;
|
||||
optional string cid = 6;
|
||||
optional PipeEntity pipeEntity = 7;
|
||||
repeated VersionPayload versionPayloads = 8;
|
||||
repeated PipeEntity pipeEntities = 9;
|
||||
optional uint32 waitRetryInterval = 10;
|
||||
optional int32 command = 11;
|
||||
optional uint64 cursor = 12;
|
||||
}
|
||||
|
||||
message PushMessagesRequest {
|
||||
map<string, entities.Message> messages = 1;
|
||||
map<string, bool> participatedMessageIds = 3;
|
||||
map<string, bool> forcePush = 8;
|
||||
map<string, bool> messagesAtMe = 9;
|
||||
}
|
||||
|
||||
message PutMessageRequest {
|
||||
optional Type type = 1;
|
||||
optional Content content = 2;
|
||||
optional string chatId = 3;
|
||||
optional string rootId = 4;
|
||||
optional string parentId = 5;
|
||||
optional string cid = 6;
|
||||
optional bool isNotified = 7;
|
||||
optional bool sendToChat = 8;
|
||||
optional int32 version = 9;
|
||||
optional bool isThreadGroupTopic = 10;
|
||||
optional bool isAnonymous = 11;
|
||||
repeated string leftStaticResourceKeys = 101;
|
||||
optional bytes thriftMessage = 102;
|
||||
}
|
||||
|
||||
|
||||
message PutChatRequest {
|
||||
optional Type type = 1;
|
||||
repeated string userIds = 2;
|
||||
optional string groupName = 3;
|
||||
optional string groupDesc = 4;
|
||||
optional bool isPublic = 5;
|
||||
repeated string chatterIds = 6;
|
||||
optional string organizationId = 7;
|
||||
optional string fromChatId = 8;
|
||||
repeated string initMessageIds = 9;
|
||||
optional string iconKey = 10;
|
||||
map<string, DocPermType> docPerms = 11;
|
||||
optional bool isCrossTenant = 12;
|
||||
optional bool isPublicV2 = 13;
|
||||
map<string, DocPair> docPerms2 = 15;
|
||||
optional string cid = 16;
|
||||
|
||||
enum DocPermType {
|
||||
UNKNOWN = 0;
|
||||
READ = 1;
|
||||
EDIT = 2;
|
||||
}
|
||||
|
||||
message DocPair {
|
||||
map<string, DocPermType> perms = 1;
|
||||
}
|
||||
}
|
||||
|
||||
message PutChatResponse {
|
||||
optional Chat chat = 1;
|
||||
optional FeedCard feedCard = 2;
|
||||
}
|
||||
|
||||
message UniversalSearchRequest {
|
||||
optional SearchCommonRequestHeader header = 1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
message UniversalSearchResponse {
|
||||
optional SearchCommonResponseHeader header = 1;
|
||||
repeated SearchResult results = 2;
|
||||
optional SearchExtraFields extraFields = 3;
|
||||
repeated FailedEntityInfo failedEntityInfos = 5;
|
||||
|
||||
|
||||
message SearchResult {
|
||||
optional string id = 1;
|
||||
optional SearchEntityType type = 2;
|
||||
optional string titleHighlighted = 3;
|
||||
optional string summaryHighlighted = 4;
|
||||
optional string extrasHighlighted = 5;
|
||||
optional string avatarKey = 6;
|
||||
optional string extraInfoSeparator = 10;
|
||||
}
|
||||
|
||||
enum SearchEntityType {
|
||||
UNKNOWN = 0;
|
||||
USER = 1;
|
||||
BOT = 2;
|
||||
GROUP_CHAT = 3;
|
||||
CRYPTO_P2P_CHAT = 4;
|
||||
MESSAGE = 5;
|
||||
DOC = 7;
|
||||
WIKI = 8;
|
||||
APP = 9;
|
||||
ONCALL = 10;
|
||||
THREAD = 11;
|
||||
QA_CARD = 12;
|
||||
URL = 13;
|
||||
DEPARTMENT = 14;
|
||||
PANO = 15;
|
||||
SLASH_COMMAND = 16;
|
||||
SECTION = 17;
|
||||
RESOURCE = 18;
|
||||
CUSTOMIZATION = 19;
|
||||
FACILITY = 20;
|
||||
MAIL_CONTACT = 21;
|
||||
CHAMELEON = 22;
|
||||
CALENDAR_EVENT = 23;
|
||||
}
|
||||
|
||||
|
||||
message SearchCommonResponseHeader {
|
||||
optional string searchSession = 1;
|
||||
optional int32 sessionSeqId = 2;
|
||||
optional int32 total = 3;
|
||||
optional bool hasMore = 4;
|
||||
optional string paginationToken = 5;
|
||||
optional InvokeAbnormalNotice invokeAbnormalNotice = 6;
|
||||
optional ColdAndHotStorageInfo storageInfo = 7;
|
||||
|
||||
enum InvokeAbnormalNotice {
|
||||
INVOKE_NORMAL = 0;
|
||||
REQUEST_CANCELED = 1;
|
||||
VERSION_SWITCH = 2;
|
||||
QUERY_LENGTH_EXCEEDED = 3;
|
||||
}
|
||||
|
||||
message ColdAndHotStorageInfo {
|
||||
optional bool isNeedColdData = 1;
|
||||
optional int32 timeSize = 2;
|
||||
optional TimeUnit timeUnit = 3;
|
||||
optional string timeText = 4;
|
||||
optional HasMoreInfo hasMoreInfo = 5;
|
||||
|
||||
enum TimeUnit {
|
||||
TimeUNKNOWN = 0;
|
||||
DAY = 1;
|
||||
WEEK = 2;
|
||||
MONTH = 3;
|
||||
YEAR = 4;
|
||||
}
|
||||
enum HasMoreInfo {
|
||||
UNKNOWN = 0;
|
||||
HOT_HAS_MORE = 1;
|
||||
HOT_HAS_NO_MORE = 2;
|
||||
COLD_HAS_MORE = 3;
|
||||
COLD_HAS_NO_MORE = 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
message SearchExtraFields {
|
||||
optional bytes chatterPermissionResponse = 1;
|
||||
}
|
||||
|
||||
message FailedEntityInfo {
|
||||
optional SearchEntityType entityType = 1;
|
||||
optional bool isNeedLocalFallback = 2;
|
||||
optional string localPaginationToken = 3;
|
||||
|
||||
enum SearchEntityType {
|
||||
UNKNOWN = 0;
|
||||
USER = 1;
|
||||
BOT = 2;
|
||||
GROUP_CHAT = 3;
|
||||
CRYPTO_P2P_CHAT = 4;
|
||||
MESSAGE = 5;
|
||||
DOC = 7;
|
||||
WIKI = 8;
|
||||
APP = 9;
|
||||
ONCALL = 10;
|
||||
THREAD = 11;
|
||||
QA_CARD = 12;
|
||||
URL = 13;
|
||||
DEPARTMENT = 14;
|
||||
PANO = 15;
|
||||
SLASH_COMMAND = 16;
|
||||
SECTION = 17;
|
||||
RESOURCE = 18;
|
||||
CUSTOMIZATION = 19;
|
||||
FACILITY = 20;
|
||||
MAIL_CONTACT = 21;
|
||||
CHAMELEON = 22;
|
||||
CALENDAR_EVENT = 23;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
message SearchCommonRequestHeader {
|
||||
optional string searchSession = 1;
|
||||
optional int32 sessionSeqId = 2;
|
||||
optional string query = 3;
|
||||
optional string paginationToken = 4;
|
||||
optional BaseEntity.SearchContext searchContext = 5;
|
||||
optional string locale = 6;
|
||||
optional string impressionId = 7;
|
||||
optional SearchExtraParam extraParam = 8;
|
||||
optional Layout titleLayout = 9;
|
||||
optional Layout summaryLayout = 10;
|
||||
optional int32 pageSize = 11;
|
||||
optional Layout sectionSummaryLayout = 13;
|
||||
message Layout {
|
||||
optional int32 line = 1;
|
||||
optional int32 width = 2;
|
||||
}
|
||||
}
|
||||
message SearchExtraParam {
|
||||
optional bytes chatterPermissionRequest = 1;
|
||||
optional int32 queryInputState = 2;
|
||||
}
|
||||
message BaseEntity {
|
||||
message SearchContext {
|
||||
optional string tagName = 1;
|
||||
repeated EntityItem entityItems = 2;
|
||||
optional CommonFilter commonFilter = 3;
|
||||
optional string sourceKey = 5;
|
||||
}
|
||||
}
|
||||
|
||||
message CommonFilter {
|
||||
optional bool includeOuterTenant = 1;
|
||||
optional string chatId = 2;
|
||||
}
|
||||
message UserFilter {
|
||||
message FieldValues {
|
||||
repeated string values = 1;
|
||||
}
|
||||
optional bool isResigned = 1;
|
||||
optional bool haveChatter = 2;
|
||||
map<string, FieldValues> customFields = 3;
|
||||
optional bool exclude = 4;
|
||||
}
|
||||
message GroupChatFilter {
|
||||
repeated SearchType searchTypes = 1;
|
||||
repeated string chatMemberIds = 2;
|
||||
repeated string excludedChatIds = 3;
|
||||
optional bool searchCrypto = 4;
|
||||
optional bool addableAsUser = 5;
|
||||
}
|
||||
|
||||
enum SearchType {
|
||||
TYPE_UNSPECIFIED = 0;
|
||||
SEARCH_TYPE_1 = 1;
|
||||
SEARCH_TYPE_2 = 2;
|
||||
}
|
||||
message EntityItem {
|
||||
optional SearchEntityType type = 1;
|
||||
optional EntityFilter filter = 2;
|
||||
repeated string boostChatIds = 4;
|
||||
optional string localPaginationToken = 5;
|
||||
|
||||
message EntityFilter {
|
||||
oneof filter {
|
||||
UserFilter userFilter = 1;
|
||||
GroupChatFilter groupChatFilter = 2;
|
||||
}
|
||||
}
|
||||
enum SearchEntityType {
|
||||
UNKNOWN = 0;
|
||||
USER = 1;
|
||||
BOT = 2;
|
||||
GROUP_CHAT = 3;
|
||||
CRYPTO_P2P_CHAT = 4;
|
||||
MESSAGE = 5;
|
||||
DOC = 7;
|
||||
WIKI = 8;
|
||||
APP = 9;
|
||||
ONCALL = 10;
|
||||
THREAD = 11;
|
||||
QA_CARD = 12;
|
||||
URL = 13;
|
||||
DEPARTMENT = 14;
|
||||
PANO = 15;
|
||||
SLASH_COMMAND = 16;
|
||||
SECTION = 17;
|
||||
RESOURCE = 18;
|
||||
CUSTOMIZATION = 19;
|
||||
FACILITY = 20;
|
||||
MAIL_CONTACT = 21;
|
||||
CHAMELEON = 22;
|
||||
CALENDAR_EVENT = 23;
|
||||
}
|
||||
}
|
||||
|
||||
message Content {
|
||||
optional string text = 1;
|
||||
optional string imageKey = 2;
|
||||
optional bool isOriginSource = 31;
|
||||
optional string title = 3;
|
||||
repeated string attachments = 4;
|
||||
optional bool isNotified = 5;
|
||||
optional string audioKey = 7;
|
||||
optional int32 audioDuration = 8;
|
||||
optional string chatId = 9;
|
||||
optional string cryptoToken = 10;
|
||||
optional string fileKey = 6;
|
||||
optional string fileName = 11;
|
||||
optional string fileMime = 12;
|
||||
optional int64 fileSize = 13;
|
||||
optional FileTransMode fileTransMode = 28;
|
||||
optional string senderDeviceId = 29;
|
||||
optional RichText richText = 14;
|
||||
optional int32 duration = 15;
|
||||
optional int32 attendeesCount = 17;
|
||||
optional bool isGroupAnnouncement = 18;
|
||||
optional string stickerSetId = 24;
|
||||
optional string stickerId = 25;
|
||||
optional string shareUserId = 27;
|
||||
|
||||
enum FileTransMode {
|
||||
UNKNOWN = 0;
|
||||
LAN_TRANS = 1;
|
||||
}
|
||||
}
|
||||
message entities {
|
||||
message Message {
|
||||
optional string id = 1;
|
||||
optional Type type = 2;
|
||||
optional string fromId = 3;
|
||||
optional int64 createTime = 4;
|
||||
optional bytes content = 5;
|
||||
optional Status status = 6;
|
||||
optional FromType fromType = 7;
|
||||
optional string rootId = 8;
|
||||
optional string parentId = 9;
|
||||
optional string chatId = 10;
|
||||
optional int64 lastModifyTime = 11;
|
||||
optional string cid = 12;
|
||||
optional int32 position = 13;
|
||||
optional int64 updateTime = 14;
|
||||
optional bool isNotified = 15;
|
||||
optional string replyCount = 16;
|
||||
optional string parentSourceMessageId = 17;
|
||||
optional string rootSourceMessageId = 18;
|
||||
optional bool isDing = 19;
|
||||
optional string threadId = 20;
|
||||
optional bool sendToChat = 21;
|
||||
optional bool isTruncated = 22;
|
||||
optional bool isRemoved = 23;
|
||||
optional string channelId = 24;
|
||||
optional int32 threadPosition = 28;
|
||||
optional int64 removerId = 29;
|
||||
optional string translateLanguage = 30;
|
||||
optional RemoverType removerType = 31;
|
||||
optional int32 noBadgedCount = 33;
|
||||
optional bool isBadged = 34;
|
||||
optional int32 badgeCount = 35;
|
||||
optional int32 threadBadgeCount = 36;
|
||||
optional int32 threadReplyCount = 37;
|
||||
repeated string atOutChatterIds = 38;
|
||||
optional string messageLanguage = 39;
|
||||
optional bool isNoTraceRemoved = 41;
|
||||
optional bool isAutoTranslatedByReceiver = 42;
|
||||
optional MessageSensitivity sensitivity = 43;
|
||||
optional bool isVisibleV2 = 44;
|
||||
optional ChatType chatType = 46;
|
||||
optional string originalSenderId = 47;
|
||||
optional bool isStaticResourceMessageDeleted = 48;
|
||||
optional int64 messagePipeVersion = 52;
|
||||
optional bool isBatchCopyMessages = 53;
|
||||
optional bool isSpecialFocus = 56;
|
||||
optional bool isIncludeDocUrl = 58;
|
||||
optional int64 cipherId = 59;
|
||||
enum Type {
|
||||
UNKNOWN = 0;
|
||||
POST = 2;
|
||||
FILE = 3;
|
||||
TEXT = 4;
|
||||
IMAGE = 5;
|
||||
SYSTEM = 6;
|
||||
AUDIO = 7;
|
||||
EMAIL = 8;
|
||||
SHARE_GROUP_CHAT = 9;
|
||||
STICKER = 10;
|
||||
MERGE_FORWARD = 11;
|
||||
CALENDAR = 12;
|
||||
CLOUD_FILE = 13;
|
||||
CARD = 14;
|
||||
MEDIA = 15;
|
||||
SHARE_CALENDAR_EVENT = 16;
|
||||
HONGBAO = 17;
|
||||
GENERAL_CALENDAR = 18;
|
||||
VIDEO_CHAT = 19;
|
||||
LOCATION = 20;
|
||||
COMMERCIALIZED_HONGBAO = 22;
|
||||
SHARE_USER_CARD = 23;
|
||||
TODO = 24;
|
||||
FOLDER = 25;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
enum FromType {
|
||||
UNKNOWN_FROMTYPE = 0;
|
||||
USER = 1;
|
||||
BOT = 2;
|
||||
}
|
||||
|
||||
enum Status {
|
||||
UNKNOWN_STATUS = 0;
|
||||
NORMAL = 1;
|
||||
DELETED = 2;
|
||||
MODIFIED = 3;
|
||||
}
|
||||
|
||||
enum RemoverType {
|
||||
UNKNOWN_REMOVERTYPE = 0;
|
||||
GROUPOWNER = 1;
|
||||
SYSADMIN = 2;
|
||||
GROUPADMIN = 3;
|
||||
}
|
||||
|
||||
enum MessageSensitivity {
|
||||
UNKNOWN_SENSITIVITY = 0;
|
||||
SAFE = 1;
|
||||
DANGEROUS = 2;
|
||||
}
|
||||
|
||||
enum ChatType {
|
||||
UNKNOWN_CHAT_TYPE = 0;
|
||||
P2P = 1;
|
||||
GROUP = 2;
|
||||
TOPIC_GROUP = 3;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
message TextContent {
|
||||
optional string text = 1;
|
||||
optional RichText richText = 3;
|
||||
}
|
||||
|
||||
message RichText {
|
||||
repeated string elementIds = 1;
|
||||
optional string innerText = 2;
|
||||
optional RichTextElements elements = 3;
|
||||
repeated string imageIds = 5;
|
||||
repeated string atIds = 6;
|
||||
repeated string anchorIds = 7;
|
||||
repeated string i18nIds = 8;
|
||||
repeated string mediaIds = 9;
|
||||
repeated string docsIds = 10;
|
||||
repeated string interactiveIds = 11;
|
||||
repeated string mentionIds = 12;
|
||||
int32 version = 13;
|
||||
}
|
||||
|
||||
|
||||
message RichTextElements {
|
||||
map<string, RichTextElement> dictionary = 1;
|
||||
map<string, RichTextElementStyleRefs> styleRefs = 2;
|
||||
repeated RichTextStyle styles = 3;
|
||||
|
||||
message RichTextStyle {
|
||||
optional string name = 1;
|
||||
optional string value = 2;
|
||||
}
|
||||
|
||||
message RichTextElementStyleRefs {
|
||||
repeated int32 styleIds = 1 [packed = false];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
message RichTextElement {
|
||||
optional Tag tag = 1;
|
||||
map<string, string> style = 2;
|
||||
optional bytes property = 3;
|
||||
repeated string childIds = 4;
|
||||
repeated string styleKeys = 5;
|
||||
enum Tag {
|
||||
UNKNOWN_TAG = 0;
|
||||
TEXT = 1;
|
||||
IMG = 2;
|
||||
P = 3;
|
||||
FIGURE = 4;
|
||||
AT = 5;
|
||||
A = 6;
|
||||
B = 7;
|
||||
I = 8;
|
||||
U = 9;
|
||||
EMOTION = 10;
|
||||
BUTTON = 11;
|
||||
SELECT = 12;
|
||||
PROGRESS_SELECT_OPTION = 13;
|
||||
DIV = 14;
|
||||
TEXTABLE_AREA = 15;
|
||||
TIME = 16;
|
||||
LINK = 17;
|
||||
MEDIA = 18;
|
||||
SELECTMENU = 19;
|
||||
OVERFLOWMENU = 20;
|
||||
DATEPICKER = 21;
|
||||
DOCS = 22;
|
||||
H1 = 23;
|
||||
H2 = 24;
|
||||
H3 = 25;
|
||||
UL = 26;
|
||||
OL = 27;
|
||||
LI = 28;
|
||||
QUOTE = 29;
|
||||
CODE = 30;
|
||||
CODE_BLOCK = 31;
|
||||
HR = 32;
|
||||
TIMEPICKER = 33;
|
||||
DATETIMEPICKER = 34;
|
||||
REACTION = 35;
|
||||
MENTION = 36;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
message TextProperty {
|
||||
optional string content = 1;
|
||||
optional string i18nKey = 2;
|
||||
optional int32 numberOfLines = 3;
|
||||
}
|
||||
message ExtendedEntry {
|
||||
optional string key = 1;
|
||||
optional string value = 2;
|
||||
}
|
||||
|
||||
|
||||
enum PayloadType {
|
||||
TYPE_UNKNOWN = 0;
|
||||
PB2 = 1;
|
||||
JSON = 2;
|
||||
}
|
||||
|
||||
message PipeEntity {
|
||||
optional string type = 1;
|
||||
optional int64 id = 3;
|
||||
}
|
||||
|
||||
message VersionPayload {
|
||||
optional VersionRange versionRange = 1;
|
||||
optional bytes payload = 2;
|
||||
}
|
||||
|
||||
message VersionRange {
|
||||
optional string start = 1;
|
||||
optional string end = 2;
|
||||
}
|
||||
|
||||
enum Type {
|
||||
UNKNOWN = 0;
|
||||
POST = 2;
|
||||
FILE = 3;
|
||||
TEXT = 4;
|
||||
IMAGE = 5;
|
||||
SYSTEM = 6;
|
||||
AUDIO = 7;
|
||||
EMAIL = 8;
|
||||
SHARE_GROUP_CHAT = 9;
|
||||
STICKER = 10;
|
||||
MERGE_FORWARD = 11;
|
||||
CALENDAR = 12;
|
||||
CLOUD_FILE = 13;
|
||||
CARD = 14;
|
||||
MEDIA = 15;
|
||||
SHARE_CALENDAR_EVENT = 16;
|
||||
HONGBAO = 17;
|
||||
GENERAL_CALENDAR = 18;
|
||||
VIDEO_CHAT = 19;
|
||||
LOCATION = 20;
|
||||
COMMERCIALIZED_HONGBAO = 22;
|
||||
SHARE_USER_CARD = 23;
|
||||
TODO = 24;
|
||||
FOLDER = 25;
|
||||
}
|
||||
|
||||
message Chat {
|
||||
optional string id = 1;
|
||||
optional Type type = 2;
|
||||
optional string lastMessageId = 3;
|
||||
optional string name = 4;
|
||||
optional string ownerId = 6;
|
||||
optional int32 newMessageCount = 7;
|
||||
optional Status status = 8;
|
||||
optional int64 updateTime = 9;
|
||||
optional string key = 10;
|
||||
optional string description = 11;
|
||||
optional int32 memberCount = 12;
|
||||
optional bool isDepartment = 13;
|
||||
optional bool isPublic = 14;
|
||||
optional int32 lastMessagePosition = 15;
|
||||
optional int32 userCount = 16;
|
||||
optional string namePinyin = 17;
|
||||
optional int64 createTime = 18;
|
||||
optional bool isCustomerService = 19;
|
||||
optional Role role = 20;
|
||||
optional bool isCustomIcon = 21;
|
||||
optional int32 noBadgedNewMessageCount = 22;
|
||||
optional bool offEditGroupChatInfo = 23;
|
||||
optional Announcement announcement = 24;
|
||||
optional string tenantId = 25;
|
||||
optional int64 updateTimeMs = 26;
|
||||
optional bool isRemind = 27;
|
||||
optional bool isDissolved = 30;
|
||||
optional bool isMeeting = 31;
|
||||
optional string lastVisibleMessageId = 32;
|
||||
optional string lastThreadId = 33;
|
||||
optional int32 newThreadCount = 34;
|
||||
optional int32 lastThreadPosition = 35;
|
||||
optional bool isCrypto = 36;
|
||||
optional int32 noBadgedNewThreadCount = 37;
|
||||
optional int32 threadStartPosition = 38;
|
||||
optional ChatMode chatMode = 39;
|
||||
optional bool isCrossTenant = 41;
|
||||
optional bool isTenant = 42;
|
||||
optional SupportView supportView = 43;
|
||||
optional int64 joinTimeMs = 44;
|
||||
optional int64 oncallId = 45;
|
||||
optional int32 lastVisibleMessagePosition = 46;
|
||||
optional int32 lastVisibleMessageNoBadgedCount = 47;
|
||||
optional int32 readPosition = 48;
|
||||
optional int32 readPositionBadgeCount = 49;
|
||||
optional int32 lastMessagePositionBadgeCount = 50;
|
||||
optional bool enableWatermark = 51;
|
||||
optional string sidebarId = 53;
|
||||
optional string namePy = 100;
|
||||
map<string, string> i18nNames = 101 [deprecated = true];
|
||||
optional I18nInf i18nInf = 102;
|
||||
optional int32 readThreadPosition = 103;
|
||||
optional int32 readThreadPositionBadgeCount = 104;
|
||||
optional int32 lastThreadPositionBadgeCount = 105;
|
||||
optional int32 lastVisibleThreadPosition = 106;
|
||||
optional string lastVisibleThreadId = 107;
|
||||
optional bool isPublicV2 = 109;
|
||||
optional bool allowPost = 111;
|
||||
optional int64 burnedTime = 112;
|
||||
optional int32 putChatterApplyCount = 113;
|
||||
optional bool showBanner = 114;
|
||||
optional bool isLargeGroup = 115;
|
||||
optional int32 firstChatMessagePosition = 116;
|
||||
repeated int32 tags = 117 [packed = false];
|
||||
map<string, string> extra = 118;
|
||||
optional bool isSamePageMeeting = 119;
|
||||
optional int64 myThreadsReadTimestamp = 120;
|
||||
optional int64 myThreadsLastTimestamp = 121;
|
||||
|
||||
enum Type {
|
||||
UNKNOWN = 0;
|
||||
P2P = 1;
|
||||
GROUP = 2;
|
||||
TOPIC_GROUP = 3;
|
||||
}
|
||||
|
||||
enum Status {
|
||||
NORMAL = 0;
|
||||
ARCHIVE = 1;
|
||||
DELETED = 2;
|
||||
}
|
||||
|
||||
enum ChatMode {
|
||||
UNKNOWN_CHAT_MODE = 0;
|
||||
DEFAULT = 1;
|
||||
THREAD = 2;
|
||||
THREAD_V2 = 3;
|
||||
}
|
||||
|
||||
enum SupportView {
|
||||
VIEW_UNKNOWN = 0;
|
||||
VIEW_P2PGROUP = 1;
|
||||
VIEW_MEETING = 2;
|
||||
VIEW_THREAD = 3;
|
||||
VIEW_CRYPTO = 4;
|
||||
}
|
||||
|
||||
enum Role {
|
||||
IGNORE = 0;
|
||||
MEMBER = 1;
|
||||
VISITOR = 2;
|
||||
THREAD_FOLLOWER = 3;
|
||||
}
|
||||
|
||||
message Announcement {
|
||||
optional string content = 1;
|
||||
optional int64 updateTime = 2;
|
||||
optional string lastEditorId = 3;
|
||||
optional string docUrl = 4;
|
||||
optional bool enableOpendoc = 5;
|
||||
}
|
||||
|
||||
message I18nInf {
|
||||
map<string, string> i18nNames = 1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
message FeedCard {
|
||||
optional string id = 1;
|
||||
optional Type type = 2;
|
||||
optional int64 updateTime = 3;
|
||||
optional bool isDelayed = 4;
|
||||
optional int64 parentCardId = 5;
|
||||
optional int64 rankTime = 6;
|
||||
optional FeedType feedType = 7;
|
||||
optional string imprId = 8;
|
||||
optional int64 updateTimeMs = 9;
|
||||
|
||||
enum Type {
|
||||
UNKNOWN_TYPE = 0;
|
||||
CHAT = 1;
|
||||
MAIL = 2;
|
||||
DOC = 3;
|
||||
THREAD = 4;
|
||||
BOX = 5;
|
||||
OPENAPP = 6;
|
||||
TOPIC = 7;
|
||||
APP_CHAT = 8;
|
||||
}
|
||||
|
||||
enum FeedType {
|
||||
TYPE_UNKNOWN = 0;
|
||||
TYPE_NEWS = 1;
|
||||
TYPE_SOCIAL = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message GetUserInfoRequest{
|
||||
optional int64 chatId = 1;
|
||||
optional int64 userId = 3;
|
||||
optional int32 userType = 4;
|
||||
}
|
||||
|
||||
// 18 {
|
||||
// 1 {
|
||||
// 13: 0x796d5f73
|
||||
// }
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "id_id"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "hi_in"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "zh_cn"
|
||||
// 2: "qsj666"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "ru_ru"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "zh_tw"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "ja_jp"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "de_de"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "fr_fr"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "vi_vn"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "ko_kr"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1 {
|
||||
// 12: 0x73755f6e
|
||||
// }
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "th_th"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "pt_br"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "zh_hk"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1 {
|
||||
// 12: 0x73655f73
|
||||
// }
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
// 18 {
|
||||
// 1: "it_it"
|
||||
// 2: "\344\271\224\344\270\226\345\230\211"
|
||||
// }
|
||||
message Detail {
|
||||
optional bytes nickname = 2;
|
||||
optional bytes nickname1 = 4;
|
||||
optional bytes nickname2 = 7;
|
||||
optional bytes nickname3 = 13;
|
||||
optional bytes nickname4 = 17;
|
||||
repeated LocaleEntry locales = 18;
|
||||
}
|
||||
|
||||
message LocaleEntry {
|
||||
oneof key {
|
||||
string key_string = 1;
|
||||
uint32 key_numeric1 = 12;
|
||||
uint32 key_numeric2 = 13;
|
||||
}
|
||||
string translation = 2;
|
||||
}
|
||||
|
||||
message UserInfoDetail {
|
||||
Detail detail = 2;
|
||||
}
|
||||
|
||||
message UserInfo {
|
||||
UserInfoDetail userInfoDetail = 1;
|
||||
}
|
||||
|
||||
message GetGroupInfoRequest{
|
||||
optional string chatId = 1;
|
||||
}
|
||||
244
static/proto_pb2.py
Normal file
244
static/proto_pb2.py
Normal file
File diff suppressed because one or more lines are too long
BIN
static/resource/back_end.png
Normal file
BIN
static/resource/back_end.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 95 KiB |
BIN
static/resource/front_end.png
Normal file
BIN
static/resource/front_end.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
BIN
static/resource/front_end_1.png
Normal file
BIN
static/resource/front_end_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
BIN
static/resource/front_end_2.png
Normal file
BIN
static/resource/front_end_2.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
BIN
static/resource/functions.png
Normal file
BIN
static/resource/functions.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Reference in New Issue
Block a user