mirror of
https://github.com/langbot-app/LangBot.git
synced 2025-11-25 19:37:36 +08:00
Compare commits
147 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92acaf6c27 | ||
|
|
4d53b3cb06 | ||
|
|
7cad4ffa37 | ||
|
|
b6f312325f | ||
|
|
43a6492cab | ||
|
|
92e3546e8a | ||
|
|
8a9000cc67 | ||
|
|
6e3514c0b2 | ||
|
|
2782c8cebe | ||
|
|
13e29a9966 | ||
|
|
601b0a8964 | ||
|
|
7c2ceb0aca | ||
|
|
42fabd5133 | ||
|
|
210a8856e2 | ||
|
|
c531cb11af | ||
|
|
07e073f526 | ||
|
|
c5457374a8 | ||
|
|
5198349591 | ||
|
|
8a4967525a | ||
|
|
30b068c6e2 | ||
|
|
ea3fff59ac | ||
|
|
b09ce8296f | ||
|
|
f9d07779a9 | ||
|
|
51634c1caf | ||
|
|
0e00da6617 | ||
|
|
5ee6baeaaa | ||
|
|
f11a036c60 | ||
|
|
0ac02ff4ce | ||
|
|
99cc50b5cb | ||
|
|
1d8fb02989 | ||
|
|
122cb1188c | ||
|
|
ca36ade288 | ||
|
|
0877046db7 | ||
|
|
ce9615a00e | ||
|
|
dbe5a41395 | ||
|
|
4a4ca54c6e | ||
|
|
47acb63feb | ||
|
|
038c5d41e2 | ||
|
|
011a795895 | ||
|
|
873a0339d8 | ||
|
|
715da548c8 | ||
|
|
5378c6ba35 | ||
|
|
8799f86ea4 | ||
|
|
686be4acbc | ||
|
|
5744eca37a | ||
|
|
70f8ddb1ba | ||
|
|
be1328cee9 | ||
|
|
c0dbf6fd13 | ||
|
|
ffe9c3e0f8 | ||
|
|
e20b79b0ed | ||
|
|
e04d46db2c | ||
|
|
7341435127 | ||
|
|
8b56f94667 | ||
|
|
f5e98d4ebb | ||
|
|
23a0dba470 | ||
|
|
512371cc25 | ||
|
|
cd4a06b692 | ||
|
|
629ebae0e9 | ||
|
|
394d4b3c1b | ||
|
|
432440d6bf | ||
|
|
a0fd152d19 | ||
|
|
1a62e08bab | ||
|
|
edbc59c117 | ||
|
|
cfdd0f8cb2 | ||
|
|
808f30675d | ||
|
|
46072abb41 | ||
|
|
71ffbb9eb5 | ||
|
|
27bbb2297a | ||
|
|
0d235aaef8 | ||
|
|
e22c804deb | ||
|
|
c136e790ef | ||
|
|
3697afd9d6 | ||
|
|
c597c6482a | ||
|
|
dda8c637d8 | ||
|
|
e6d7aaa440 | ||
|
|
028458b33c | ||
|
|
9c7d8099cb | ||
|
|
5640dc332d | ||
|
|
40275c3ef1 | ||
|
|
ebe0b2f335 | ||
|
|
97603e8441 | ||
|
|
72cd444861 | ||
|
|
955b859f2c | ||
|
|
dea5cc9c0c | ||
|
|
d13ab1703e | ||
|
|
61ab6a009b | ||
|
|
a9ae36d362 | ||
|
|
f518395ce5 | ||
|
|
20b17fe378 | ||
|
|
572182180c | ||
|
|
de261099aa | ||
|
|
50f0122955 | ||
|
|
fe9eff923e | ||
|
|
dd36278032 | ||
|
|
a079821976 | ||
|
|
fa233e0a24 | ||
|
|
22306cb4ea | ||
|
|
f2d45a3668 | ||
|
|
db91ff12f7 | ||
|
|
eb841fb73e | ||
|
|
bd0438df76 | ||
|
|
9ca1fc59ef | ||
|
|
84a80a5ec8 | ||
|
|
4b2e248646 | ||
|
|
b90e45590a | ||
|
|
ff93d563a8 | ||
|
|
53228498ed | ||
|
|
8ece82e43a | ||
|
|
8b4684675e | ||
|
|
8cca12fff2 | ||
|
|
a74111612e | ||
|
|
c7799a65c4 | ||
|
|
aabb01c50f | ||
|
|
95e2ada965 | ||
|
|
3fe7d53c76 | ||
|
|
e8634bb1ab | ||
|
|
dbe46b5770 | ||
|
|
6d9fba30b1 | ||
|
|
6a866bf871 | ||
|
|
3c961e4652 | ||
|
|
7abd999420 | ||
|
|
fca8fbb135 | ||
|
|
c67caf18df | ||
|
|
fe956fe4a5 | ||
|
|
0e52f679a2 | ||
|
|
b9500283ec | ||
|
|
441b69b528 | ||
|
|
898bcdc96b | ||
|
|
02bc1fc45e | ||
|
|
5585981dc3 | ||
|
|
a4777f194b | ||
|
|
41aeda8dc0 | ||
|
|
2ed522667e | ||
|
|
1932444666 | ||
|
|
b49b7e963d | ||
|
|
435c11ff27 | ||
|
|
2e93600437 | ||
|
|
faecb70d0f | ||
|
|
92e1ac5c3a | ||
|
|
8963a2117b | ||
|
|
aa300258ab | ||
|
|
48841daff5 | ||
|
|
8878f1ed87 | ||
|
|
f6205d79c0 | ||
|
|
d6d5dac6b3 | ||
|
|
05b979e68a | ||
|
|
9f7d9e4c0d |
16
.github/ISSUE_TEMPLATE/bug-report.yml
vendored
16
.github/ISSUE_TEMPLATE/bug-report.yml
vendored
@@ -3,22 +3,6 @@ description: 报错或漏洞请使用这个模板创建,不使用此模板创
|
|||||||
title: "[Bug]: "
|
title: "[Bug]: "
|
||||||
labels: ["bug?"]
|
labels: ["bug?"]
|
||||||
body:
|
body:
|
||||||
- type: dropdown
|
|
||||||
attributes:
|
|
||||||
label: 消息平台适配器
|
|
||||||
description: "接入的消息平台类型"
|
|
||||||
options:
|
|
||||||
- 其他(或暂未使用)
|
|
||||||
- Nakuru(go-cqhttp)
|
|
||||||
- aiocqhttp(使用 OneBot 协议接入的)
|
|
||||||
- qq-botpy(QQ官方API WebSocket)
|
|
||||||
- qqofficial(QQ官方API Webhook)
|
|
||||||
- lark(飞书)
|
|
||||||
- wecom(企业微信)
|
|
||||||
- gewechat(个人微信)
|
|
||||||
- discord
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: input
|
- type: input
|
||||||
attributes:
|
attributes:
|
||||||
label: 运行环境
|
label: 运行环境
|
||||||
|
|||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -19,7 +19,7 @@ cookies.json
|
|||||||
data/labels/announcement_saved.json
|
data/labels/announcement_saved.json
|
||||||
cmdpriv.json
|
cmdpriv.json
|
||||||
tips.py
|
tips.py
|
||||||
.venv
|
venv*
|
||||||
bin/
|
bin/
|
||||||
.vscode
|
.vscode
|
||||||
test_*
|
test_*
|
||||||
@@ -39,3 +39,4 @@ botpy.log*
|
|||||||
/libs/wecom_api/test.py
|
/libs/wecom_api/test.py
|
||||||
/venv
|
/venv
|
||||||
/jp-tyo-churros-05.rockchin.top
|
/jp-tyo-churros-05.rockchin.top
|
||||||
|
test.py
|
||||||
40
README.md
40
README.md
@@ -8,8 +8,8 @@
|
|||||||
|
|
||||||
<a href="https://trendshift.io/repositories/12901" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12901" alt="RockChinQ%2FLangBot | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
<a href="https://trendshift.io/repositories/12901" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12901" alt="RockChinQ%2FLangBot | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
<a href="https://docs.langbot.app">项目主页</a> |
|
<a href="https://langbot.app">项目主页</a> |
|
||||||
<a href="https://docs.langbot.app/insight/intro.htmll">功能介绍</a> |
|
<a href="https://docs.langbot.app/insight/intro.html">功能介绍</a> |
|
||||||
<a href="https://docs.langbot.app/insight/guide.html">部署文档</a> |
|
<a href="https://docs.langbot.app/insight/guide.html">部署文档</a> |
|
||||||
<a href="https://docs.langbot.app/usage/faq.html">常见问题</a> |
|
<a href="https://docs.langbot.app/usage/faq.html">常见问题</a> |
|
||||||
<a href="https://docs.langbot.app/plugin/plugin-intro.html">插件介绍</a> |
|
<a href="https://docs.langbot.app/plugin/plugin-intro.html">插件介绍</a> |
|
||||||
@@ -26,7 +26,7 @@
|
|||||||
[](https://qm.qq.com/q/JLi38whHum)
|
[](https://qm.qq.com/q/JLi38whHum)
|
||||||
[](https://github.com/RockChinQ/LangBot/releases/latest)
|
[](https://github.com/RockChinQ/LangBot/releases/latest)
|
||||||

|

|
||||||
<img src="https://img.shields.io/badge/python-3.10 | 3.11 | 3.12-blue.svg" alt="python">
|
<img src="https://img.shields.io/badge/python-3.10 ~ 3.13 -blue.svg" alt="python">
|
||||||
[](https://gitcode.com/RockChinQ/LangBot)
|
[](https://gitcode.com/RockChinQ/LangBot)
|
||||||
|
|
||||||
[简体中文](README.md) / [English](README_EN.md) / [日本語](README_JP.md)
|
[简体中文](README.md) / [English](README_EN.md) / [日本語](README_JP.md)
|
||||||
@@ -39,7 +39,7 @@
|
|||||||
|
|
||||||
- 💬 大模型对话、Agent:支持多种大模型,适配群聊和私聊;具有多轮对话、工具调用、多模态能力,并深度适配 [Dify](https://dify.ai)。目前支持 QQ、QQ频道、企业微信、个人微信、飞书、Discord、Telegram 等平台。
|
- 💬 大模型对话、Agent:支持多种大模型,适配群聊和私聊;具有多轮对话、工具调用、多模态能力,并深度适配 [Dify](https://dify.ai)。目前支持 QQ、QQ频道、企业微信、个人微信、飞书、Discord、Telegram 等平台。
|
||||||
- 🛠️ 高稳定性、功能完备:原生支持访问控制、限速、敏感词过滤等机制;配置简单,支持多种部署方式。
|
- 🛠️ 高稳定性、功能完备:原生支持访问控制、限速、敏感词过滤等机制;配置简单,支持多种部署方式。
|
||||||
- 🧩 插件扩展、活跃社区:支持事件驱动、组件扩展等插件机制;丰富生态,目前已有数十个[插件](https://docs.langbot.app/plugin/plugin-intro.html)
|
- 🧩 插件扩展、活跃社区:支持事件驱动、组件扩展等插件机制;适配 Anthropic [MCP 协议](https://modelcontextprotocol.io/);目前已有数十个[插件](https://docs.langbot.app/plugin/plugin-intro.html)
|
||||||
- 😻 [New] Web 管理面板:支持通过浏览器管理 LangBot 实例,具体支持功能,查看[文档](https://docs.langbot.app/webui/intro.html)
|
- 😻 [New] Web 管理面板:支持通过浏览器管理 LangBot 实例,具体支持功能,查看[文档](https://docs.langbot.app/webui/intro.html)
|
||||||
|
|
||||||
## 📦 开始使用
|
## 📦 开始使用
|
||||||
@@ -87,17 +87,20 @@
|
|||||||
| QQ 个人号 | ✅ | QQ 个人号私聊、群聊 |
|
| QQ 个人号 | ✅ | QQ 个人号私聊、群聊 |
|
||||||
| QQ 官方机器人 | ✅ | QQ 官方机器人,支持频道、私聊、群聊 |
|
| QQ 官方机器人 | ✅ | QQ 官方机器人,支持频道、私聊、群聊 |
|
||||||
| 企业微信 | ✅ | |
|
| 企业微信 | ✅ | |
|
||||||
|
| 企微对外客服 | ✅ | |
|
||||||
| 个人微信 | ✅ | 使用 [Gewechat](https://github.com/Devo919/Gewechat) 接入 |
|
| 个人微信 | ✅ | 使用 [Gewechat](https://github.com/Devo919/Gewechat) 接入 |
|
||||||
| 微信公众号 | ✅ | |
|
| 微信公众号 | ✅ | |
|
||||||
| 飞书 | ✅ | |
|
| 飞书 | ✅ | |
|
||||||
| 钉钉 | ✅ | |
|
| 钉钉 | ✅ | |
|
||||||
| Discord | ✅ | |
|
| Discord | ✅ | |
|
||||||
| Telegram | ✅ | |
|
| Telegram | ✅ | |
|
||||||
|
| Slack | ✅ | |
|
||||||
|
| LINE | 🚧 | |
|
||||||
| WhatsApp | 🚧 | |
|
| WhatsApp | 🚧 | |
|
||||||
|
|
||||||
🚧: 正在开发中
|
🚧: 正在开发中
|
||||||
|
|
||||||
### 大模型
|
### 大模型能力
|
||||||
|
|
||||||
| 模型 | 状态 | 备注 |
|
| 模型 | 状态 | 备注 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -107,6 +110,7 @@
|
|||||||
| [Anthropic](https://www.anthropic.com/) | ✅ | |
|
| [Anthropic](https://www.anthropic.com/) | ✅ | |
|
||||||
| [xAI](https://x.ai/) | ✅ | |
|
| [xAI](https://x.ai/) | ✅ | |
|
||||||
| [智谱AI](https://open.bigmodel.cn/) | ✅ | |
|
| [智谱AI](https://open.bigmodel.cn/) | ✅ | |
|
||||||
|
| [PPIO](https://ppinfra.com/user/register?invited_by=QJKFYD&utm_source=github_langbot) | ✅ | 大模型和 GPU 资源平台 |
|
||||||
| [Dify](https://dify.ai) | ✅ | LLMOps 平台 |
|
| [Dify](https://dify.ai) | ✅ | LLMOps 平台 |
|
||||||
| [Ollama](https://ollama.com/) | ✅ | 本地大模型运行平台 |
|
| [Ollama](https://ollama.com/) | ✅ | 本地大模型运行平台 |
|
||||||
| [LMStudio](https://lmstudio.ai/) | ✅ | 本地大模型运行平台 |
|
| [LMStudio](https://lmstudio.ai/) | ✅ | 本地大模型运行平台 |
|
||||||
@@ -114,12 +118,34 @@
|
|||||||
| [SiliconFlow](https://siliconflow.cn/) | ✅ | 大模型聚合平台 |
|
| [SiliconFlow](https://siliconflow.cn/) | ✅ | 大模型聚合平台 |
|
||||||
| [阿里云百炼](https://bailian.console.aliyun.com/) | ✅ | 大模型聚合平台, LLMOps 平台 |
|
| [阿里云百炼](https://bailian.console.aliyun.com/) | ✅ | 大模型聚合平台, LLMOps 平台 |
|
||||||
| [火山方舟](https://console.volcengine.com/ark/region:ark+cn-beijing/model?vendor=Bytedance&view=LIST_VIEW) | ✅ | 大模型聚合平台, LLMOps 平台 |
|
| [火山方舟](https://console.volcengine.com/ark/region:ark+cn-beijing/model?vendor=Bytedance&view=LIST_VIEW) | ✅ | 大模型聚合平台, LLMOps 平台 |
|
||||||
|
| [ModelScope](https://modelscope.cn/docs/model-service/API-Inference/intro) | ✅ | 大模型聚合平台 |
|
||||||
|
| [MCP](https://modelcontextprotocol.io/) | ✅ | 支持通过 MCP 协议获取工具 |
|
||||||
|
|
||||||
|
### TTS
|
||||||
|
|
||||||
|
| 平台/模型 | 备注 |
|
||||||
|
| --- | --- |
|
||||||
|
| [FishAudio](https://fish.audio/zh-CN/discovery/) | [插件](https://github.com/the-lazy-me/NewChatVoice) |
|
||||||
|
| [海豚 AI](https://www.ttson.cn/?source=thelazy) | [插件](https://github.com/the-lazy-me/NewChatVoice) |
|
||||||
|
| [AzureTTS](https://portal.azure.com/) | [插件](https://github.com/Ingnaryk/LangBot_AzureTTS) |
|
||||||
|
|
||||||
|
### 文生图
|
||||||
|
|
||||||
|
| 平台/模型 | 备注 |
|
||||||
|
| --- | --- |
|
||||||
|
| 阿里云百炼 | [插件](https://github.com/Thetail001/LangBot_BailianTextToImagePlugin)
|
||||||
|
|
||||||
## 😘 社区贡献
|
## 😘 社区贡献
|
||||||
|
|
||||||
LangBot 离不开以下贡献者和社区内所有人的贡献,我们欢迎任何形式的贡献和反馈。
|
感谢以下[代码贡献者](https://github.com/RockChinQ/LangBot/graphs/contributors)和社区里其他成员对 LangBot 的贡献:
|
||||||
|
|
||||||
|
|
||||||
<a href="https://github.com/RockChinQ/LangBot/graphs/contributors">
|
<a href="https://github.com/RockChinQ/LangBot/graphs/contributors">
|
||||||
<img src="https://contrib.rocks/image?repo=RockChinQ/LangBot" />
|
<img src="https://contrib.rocks/image?repo=RockChinQ/LangBot" />
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
以及 LangBot 核心团队成员:
|
||||||
|
|
||||||
|
- [RockChinQ](https://github.com/RockChinQ)
|
||||||
|
- [the-lazy-me](https://github.com/the-lazy-me)
|
||||||
|
- [wangcham](https://github.com/wangcham)
|
||||||
|
- [KaedeSAMA](https://github.com/KaedeSAMA)
|
||||||
22
README_EN.md
22
README_EN.md
@@ -7,8 +7,8 @@
|
|||||||
|
|
||||||
<a href="https://trendshift.io/repositories/12901" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12901" alt="RockChinQ%2FLangBot | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
<a href="https://trendshift.io/repositories/12901" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12901" alt="RockChinQ%2FLangBot | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
<a href="https://docs.langbot.app">Home</a> |
|
<a href="https://langbot.app">Home</a> |
|
||||||
<a href="https://docs.langbot.app/insight/intro.htmll">Features</a> |
|
<a href="https://docs.langbot.app/insight/intro.html">Features</a> |
|
||||||
<a href="https://docs.langbot.app/insight/guide.html">Deployment</a> |
|
<a href="https://docs.langbot.app/insight/guide.html">Deployment</a> |
|
||||||
<a href="https://docs.langbot.app/usage/faq.html">FAQ</a> |
|
<a href="https://docs.langbot.app/usage/faq.html">FAQ</a> |
|
||||||
<a href="https://docs.langbot.app/plugin/plugin-intro.html">Plugin</a> |
|
<a href="https://docs.langbot.app/plugin/plugin-intro.html">Plugin</a> |
|
||||||
@@ -24,7 +24,7 @@
|
|||||||
[](https://discord.gg/wdNEHETs87)
|
[](https://discord.gg/wdNEHETs87)
|
||||||
[](https://github.com/RockChinQ/LangBot/releases/latest)
|
[](https://github.com/RockChinQ/LangBot/releases/latest)
|
||||||
)
|
)
|
||||||
<img src="https://img.shields.io/badge/python-3.10 | 3.11 | 3.12-blue.svg" alt="python">
|
<img src="https://img.shields.io/badge/python-3.10 ~ 3.13 -blue.svg" alt="python">
|
||||||
|
|
||||||
[简体中文](README.md) / [English](README_EN.md) / [日本語](README_JP.md)
|
[简体中文](README.md) / [English](README_EN.md) / [日本語](README_JP.md)
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@
|
|||||||
|
|
||||||
- 💬 Chat with LLM / Agent: Supports multiple LLMs, adapt to group chats and private chats; Supports multi-round conversations, tool calls, and multi-modal capabilities. Deeply integrates with [Dify](https://dify.ai). Currently supports QQ, QQ Channel, WeCom, personal WeChat, Lark, DingTalk, Discord, Telegram, etc.
|
- 💬 Chat with LLM / Agent: Supports multiple LLMs, adapt to group chats and private chats; Supports multi-round conversations, tool calls, and multi-modal capabilities. Deeply integrates with [Dify](https://dify.ai). Currently supports QQ, QQ Channel, WeCom, personal WeChat, Lark, DingTalk, Discord, Telegram, etc.
|
||||||
- 🛠️ High Stability, Feature-rich: Native access control, rate limiting, sensitive word filtering, etc. mechanisms; Easy to use, supports multiple deployment methods.
|
- 🛠️ High Stability, Feature-rich: Native access control, rate limiting, sensitive word filtering, etc. mechanisms; Easy to use, supports multiple deployment methods.
|
||||||
- 🧩 Plugin Extension, Active Community: Support event-driven, component extension, etc. plugin mechanisms; Rich ecology, currently has dozens of [plugins](https://docs.langbot.app/plugin/plugin-intro.html)
|
- 🧩 Plugin Extension, Active Community: Support event-driven, component extension, etc. plugin mechanisms; Integrate Anthropic [MCP protocol](https://modelcontextprotocol.io/); Currently has dozens of [plugins](https://docs.langbot.app/plugin/plugin-intro.html)
|
||||||
- 😻 [New] Web UI: Support management LangBot instance through the browser, for details, see [documentation](https://docs.langbot.app/webui/intro.html)
|
- 😻 [New] Web UI: Support management LangBot instance through the browser, for details, see [documentation](https://docs.langbot.app/webui/intro.html)
|
||||||
|
|
||||||
## 📦 Getting Started
|
## 📦 Getting Started
|
||||||
@@ -85,11 +85,14 @@ Directly use the released version to run, see the [Manual Deployment](https://do
|
|||||||
| Personal QQ | ✅ | |
|
| Personal QQ | ✅ | |
|
||||||
| QQ Official API | ✅ | |
|
| QQ Official API | ✅ | |
|
||||||
| WeCom | ✅ | |
|
| WeCom | ✅ | |
|
||||||
|
| WeComCS | ✅ | |
|
||||||
| Personal WeChat | ✅ | Use [Gewechat](https://github.com/Devo919/Gewechat) to access |
|
| Personal WeChat | ✅ | Use [Gewechat](https://github.com/Devo919/Gewechat) to access |
|
||||||
| Lark | ✅ | |
|
| Lark | ✅ | |
|
||||||
| DingTalk | ✅ | |
|
| DingTalk | ✅ | |
|
||||||
| Discord | ✅ | |
|
| Discord | ✅ | |
|
||||||
| Telegram | ✅ | |
|
| Telegram | ✅ | |
|
||||||
|
| Slack | ✅ | |
|
||||||
|
| LINE | 🚧 | |
|
||||||
| WhatsApp | 🚧 | |
|
| WhatsApp | 🚧 | |
|
||||||
|
|
||||||
🚧: In development
|
🚧: In development
|
||||||
@@ -105,20 +108,27 @@ Directly use the released version to run, see the [Manual Deployment](https://do
|
|||||||
| [xAI](https://x.ai/) | ✅ | |
|
| [xAI](https://x.ai/) | ✅ | |
|
||||||
| [Zhipu AI](https://open.bigmodel.cn/) | ✅ | |
|
| [Zhipu AI](https://open.bigmodel.cn/) | ✅ | |
|
||||||
| [Dify](https://dify.ai) | ✅ | LLMOps platform |
|
| [Dify](https://dify.ai) | ✅ | LLMOps platform |
|
||||||
|
| [PPIO](https://ppinfra.com/user/register?invited_by=QJKFYD&utm_source=github_langbot) | ✅ | LLM and GPU resource platform |
|
||||||
| [Ollama](https://ollama.com/) | ✅ | Local LLM running platform |
|
| [Ollama](https://ollama.com/) | ✅ | Local LLM running platform |
|
||||||
| [LMStudio](https://lmstudio.ai/) | ✅ | Local LLM running platform |
|
| [LMStudio](https://lmstudio.ai/) | ✅ | Local LLM running platform |
|
||||||
| [GiteeAI](https://ai.gitee.com/) | ✅ | LLM interface gateway(MaaS) |
|
| [GiteeAI](https://ai.gitee.com/) | ✅ | LLM interface gateway(MaaS) |
|
||||||
| [SiliconFlow](https://siliconflow.cn/) | ✅ | LLM gateway(MaaS) |
|
| [SiliconFlow](https://siliconflow.cn/) | ✅ | LLM gateway(MaaS) |
|
||||||
| [Aliyun Bailian](https://bailian.console.aliyun.com/) | ✅ | LLM gateway(MaaS), LLMOps platform |
|
| [Aliyun Bailian](https://bailian.console.aliyun.com/) | ✅ | LLM gateway(MaaS), LLMOps platform |
|
||||||
| [Volc Engine Ark](https://console.volcengine.com/ark/region:ark+cn-beijing/model?vendor=Bytedance&view=LIST_VIEW) | ✅ | LLM gateway(MaaS), LLMOps platform |
|
| [Volc Engine Ark](https://console.volcengine.com/ark/region:ark+cn-beijing/model?vendor=Bytedance&view=LIST_VIEW) | ✅ | LLM gateway(MaaS), LLMOps platform |
|
||||||
|
| [ModelScope](https://modelscope.cn/docs/model-service/API-Inference/intro) | ✅ | LLM gateway(MaaS) |
|
||||||
|
| [MCP](https://modelcontextprotocol.io/) | ✅ | Support tool access through MCP protocol |
|
||||||
|
|
||||||
## 🤝 Community Contribution
|
## 🤝 Community Contribution
|
||||||
|
|
||||||
Thanks to the following contributors and everyone in the community for their contributions.
|
Thank you for the following [code contributors](https://github.com/RockChinQ/LangBot/graphs/contributors) and other members in the community for their contributions to LangBot:
|
||||||
|
|
||||||
|
|
||||||
<a href="https://github.com/RockChinQ/LangBot/graphs/contributors">
|
<a href="https://github.com/RockChinQ/LangBot/graphs/contributors">
|
||||||
<img src="https://contrib.rocks/image?repo=RockChinQ/LangBot" />
|
<img src="https://contrib.rocks/image?repo=RockChinQ/LangBot" />
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
And the core team members of LangBot:
|
||||||
|
|
||||||
|
- [RockChinQ](https://github.com/RockChinQ)
|
||||||
|
- [the-lazy-me](https://github.com/the-lazy-me)
|
||||||
|
- [wangcham](https://github.com/wangcham)
|
||||||
|
- [KaedeSAMA](https://github.com/KaedeSAMA)
|
||||||
|
|||||||
22
README_JP.md
22
README_JP.md
@@ -7,8 +7,8 @@
|
|||||||
|
|
||||||
<a href="https://trendshift.io/repositories/12901" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12901" alt="RockChinQ%2FLangBot | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
<a href="https://trendshift.io/repositories/12901" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12901" alt="RockChinQ%2FLangBot | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
<a href="https://docs.langbot.app">ホーム</a> |
|
<a href="https://langbot.app">ホーム</a> |
|
||||||
<a href="https://docs.langbot.app/insight/intro.htmll">機能</a> |
|
<a href="https://docs.langbot.app/insight/intro.html">機能</a> |
|
||||||
<a href="https://docs.langbot.app/insight/guide.html">デプロイ</a> |
|
<a href="https://docs.langbot.app/insight/guide.html">デプロイ</a> |
|
||||||
<a href="https://docs.langbot.app/usage/faq.html">FAQ</a> |
|
<a href="https://docs.langbot.app/usage/faq.html">FAQ</a> |
|
||||||
<a href="https://docs.langbot.app/plugin/plugin-intro.html">プラグイン</a> |
|
<a href="https://docs.langbot.app/plugin/plugin-intro.html">プラグイン</a> |
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
[](https://discord.gg/wdNEHETs87)
|
[](https://discord.gg/wdNEHETs87)
|
||||||
[](https://github.com/RockChinQ/LangBot/releases/latest)
|
[](https://github.com/RockChinQ/LangBot/releases/latest)
|
||||||
)
|
)
|
||||||
<img src="https://img.shields.io/badge/python-3.10 | 3.11 | 3.12-blue.svg" alt="python">
|
<img src="https://img.shields.io/badge/python-3.10 ~ 3.13 -blue.svg" alt="python">
|
||||||
|
|
||||||
[简体中文](README.md) / [English](README_EN.md) / [日本語](README_JP.md)
|
[简体中文](README.md) / [English](README_EN.md) / [日本語](README_JP.md)
|
||||||
|
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
|
|
||||||
- 💬 LLM / エージェントとのチャット: 複数のLLMをサポートし、グループチャットとプライベートチャットに対応。マルチラウンドの会話、ツールの呼び出し、マルチモーダル機能をサポート。 [Dify](https://dify.ai) と深く統合。現在、QQ、QQ チャンネル、WeChat、個人 WeChat、Lark、DingTalk、Discord、Telegram など、複数のプラットフォームをサポートしています。
|
- 💬 LLM / エージェントとのチャット: 複数のLLMをサポートし、グループチャットとプライベートチャットに対応。マルチラウンドの会話、ツールの呼び出し、マルチモーダル機能をサポート。 [Dify](https://dify.ai) と深く統合。現在、QQ、QQ チャンネル、WeChat、個人 WeChat、Lark、DingTalk、Discord、Telegram など、複数のプラットフォームをサポートしています。
|
||||||
- 🛠️ 高い安定性、豊富な機能: ネイティブのアクセス制御、レート制限、敏感な単語のフィルタリングなどのメカニズムをサポート。使いやすく、複数のデプロイ方法をサポート。
|
- 🛠️ 高い安定性、豊富な機能: ネイティブのアクセス制御、レート制限、敏感な単語のフィルタリングなどのメカニズムをサポート。使いやすく、複数のデプロイ方法をサポート。
|
||||||
- 🧩 プラグイン拡張、活発なコミュニティ: イベント駆動、コンポーネント拡張などのプラグインメカニズムをサポート。豊富なエコシステム、現在数十の[プラグイン](https://docs.langbot.app/plugin/plugin-intro.html)が存在。
|
- 🧩 プラグイン拡張、活発なコミュニティ: イベント駆動、コンポーネント拡張などのプラグインメカニズムをサポート。適配 Anthropic [MCP プロトコル](https://modelcontextprotocol.io/);豊富なエコシステム、現在数十の[プラグイン](https://docs.langbot.app/plugin/plugin-intro.html)が存在。
|
||||||
- 😻 [新機能] Web UI: ブラウザを通じてLangBotインスタンスを管理することをサポート。詳細は[ドキュメント](https://docs.langbot.app/webui/intro.html)を参照。
|
- 😻 [新機能] Web UI: ブラウザを通じてLangBotインスタンスを管理することをサポート。詳細は[ドキュメント](https://docs.langbot.app/webui/intro.html)を参照。
|
||||||
|
|
||||||
## 📦 始め方
|
## 📦 始め方
|
||||||
@@ -84,11 +84,14 @@ LangBotはBTPanelにリストされています。BTPanelをインストール
|
|||||||
| 個人QQ | ✅ | |
|
| 個人QQ | ✅ | |
|
||||||
| QQ公式API | ✅ | |
|
| QQ公式API | ✅ | |
|
||||||
| WeCom | ✅ | |
|
| WeCom | ✅ | |
|
||||||
|
| WeComCS | ✅ | |
|
||||||
| 個人WeChat | ✅ | [Gewechat](https://github.com/Devo919/Gewechat)を使用して接続 |
|
| 個人WeChat | ✅ | [Gewechat](https://github.com/Devo919/Gewechat)を使用して接続 |
|
||||||
| Lark | ✅ | |
|
| Lark | ✅ | |
|
||||||
| DingTalk | ✅ | |
|
| DingTalk | ✅ | |
|
||||||
| Discord | ✅ | |
|
| Discord | ✅ | |
|
||||||
| Telegram | ✅ | |
|
| Telegram | ✅ | |
|
||||||
|
| Slack | ✅ | |
|
||||||
|
| LINE | 🚧 | |
|
||||||
| WhatsApp | 🚧 | |
|
| WhatsApp | 🚧 | |
|
||||||
|
|
||||||
🚧: 開発中
|
🚧: 開発中
|
||||||
@@ -103,6 +106,7 @@ LangBotはBTPanelにリストされています。BTPanelをインストール
|
|||||||
| [Anthropic](https://www.anthropic.com/) | ✅ | |
|
| [Anthropic](https://www.anthropic.com/) | ✅ | |
|
||||||
| [xAI](https://x.ai/) | ✅ | |
|
| [xAI](https://x.ai/) | ✅ | |
|
||||||
| [Zhipu AI](https://open.bigmodel.cn/) | ✅ | |
|
| [Zhipu AI](https://open.bigmodel.cn/) | ✅ | |
|
||||||
|
| [PPIO](https://ppinfra.com/user/register?invited_by=QJKFYD&utm_source=github_langbot) | ✅ | 大模型とGPUリソースプラットフォーム |
|
||||||
| [Dify](https://dify.ai) | ✅ | LLMOpsプラットフォーム |
|
| [Dify](https://dify.ai) | ✅ | LLMOpsプラットフォーム |
|
||||||
| [Ollama](https://ollama.com/) | ✅ | ローカルLLM実行プラットフォーム |
|
| [Ollama](https://ollama.com/) | ✅ | ローカルLLM実行プラットフォーム |
|
||||||
| [LMStudio](https://lmstudio.ai/) | ✅ | ローカルLLM実行プラットフォーム |
|
| [LMStudio](https://lmstudio.ai/) | ✅ | ローカルLLM実行プラットフォーム |
|
||||||
@@ -110,14 +114,20 @@ LangBotはBTPanelにリストされています。BTPanelをインストール
|
|||||||
| [SiliconFlow](https://siliconflow.cn/) | ✅ | LLMゲートウェイ(MaaS) |
|
| [SiliconFlow](https://siliconflow.cn/) | ✅ | LLMゲートウェイ(MaaS) |
|
||||||
| [Aliyun Bailian](https://bailian.console.aliyun.com/) | ✅ | LLMゲートウェイ(MaaS), LLMOpsプラットフォーム |
|
| [Aliyun Bailian](https://bailian.console.aliyun.com/) | ✅ | LLMゲートウェイ(MaaS), LLMOpsプラットフォーム |
|
||||||
| [Volc Engine Ark](https://console.volcengine.com/ark/region:ark+cn-beijing/model?vendor=Bytedance&view=LIST_VIEW) | ✅ | LLMゲートウェイ(MaaS), LLMOpsプラットフォーム |
|
| [Volc Engine Ark](https://console.volcengine.com/ark/region:ark+cn-beijing/model?vendor=Bytedance&view=LIST_VIEW) | ✅ | LLMゲートウェイ(MaaS), LLMOpsプラットフォーム |
|
||||||
|
| [ModelScope](https://modelscope.cn/docs/model-service/API-Inference/intro) | ✅ | LLMゲートウェイ(MaaS) |
|
||||||
|
| [MCP](https://modelcontextprotocol.io/) | ✅ | MCPプロトコルをサポート |
|
||||||
|
|
||||||
## 🤝 コミュニティ貢献
|
## 🤝 コミュニティ貢献
|
||||||
|
|
||||||
以下の貢献者とコミュニティの皆さんの貢献に感謝します。
|
LangBot への貢献に対して、以下の [コード貢献者](https://github.com/RockChinQ/LangBot/graphs/contributors) とコミュニティの他のメンバーに感謝します。
|
||||||
|
|
||||||
|
|
||||||
<a href="https://github.com/RockChinQ/LangBot/graphs/contributors">
|
<a href="https://github.com/RockChinQ/LangBot/graphs/contributors">
|
||||||
<img src="https://contrib.rocks/image?repo=RockChinQ/LangBot" />
|
<img src="https://contrib.rocks/image?repo=RockChinQ/LangBot" />
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
|
LangBot の核心チームメンバー:
|
||||||
|
|
||||||
|
- [RockChinQ](https://github.com/RockChinQ)
|
||||||
|
- [the-lazy-me](https://github.com/the-lazy-me)
|
||||||
|
- [wangcham](https://github.com/wangcham)
|
||||||
|
- [KaedeSAMA](https://github.com/KaedeSAMA)
|
||||||
|
|||||||
@@ -8,6 +8,8 @@ services:
|
|||||||
- ./data:/app/data
|
- ./data:/app/data
|
||||||
- ./plugins:/app/plugins
|
- ./plugins:/app/plugins
|
||||||
restart: on-failure
|
restart: on-failure
|
||||||
|
environment:
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
ports:
|
ports:
|
||||||
- 5300:5300 # 供 WebUI 使用
|
- 5300:5300 # 供 WebUI 使用
|
||||||
- 2280-2290:2280-2290 # 供消息平台适配器方向连接
|
- 2280-2290:2280-2290 # 供消息平台适配器方向连接
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ class EchoTextHandler(dingtalk_stream.ChatbotHandler):
|
|||||||
"""异步等待消息的到来"""
|
"""异步等待消息的到来"""
|
||||||
while self.incoming_message is None:
|
while self.incoming_message is None:
|
||||||
await asyncio.sleep(0.1) # 异步等待,避免阻塞
|
await asyncio.sleep(0.1) # 异步等待,避免阻塞
|
||||||
|
|
||||||
return self.incoming_message
|
return self.incoming_message
|
||||||
|
|
||||||
async def get_dingtalk_client(client_id, client_secret):
|
async def get_dingtalk_client(client_id, client_secret):
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import traceback
|
|||||||
|
|
||||||
|
|
||||||
class DingTalkClient:
|
class DingTalkClient:
|
||||||
def __init__(self, client_id: str, client_secret: str,robot_name:str,robot_code:str):
|
def __init__(self, client_id: str, client_secret: str,robot_name:str,robot_code:str,markdown_card:bool):
|
||||||
"""初始化 WebSocket 连接并自动启动"""
|
"""初始化 WebSocket 连接并自动启动"""
|
||||||
self.credential = dingtalk_stream.Credential(client_id, client_secret)
|
self.credential = dingtalk_stream.Credential(client_id, client_secret)
|
||||||
self.client = dingtalk_stream.DingTalkStreamClient(self.credential)
|
self.client = dingtalk_stream.DingTalkStreamClient(self.credential)
|
||||||
@@ -26,6 +26,7 @@ class DingTalkClient:
|
|||||||
self.robot_name = robot_name
|
self.robot_name = robot_name
|
||||||
self.robot_code = robot_code
|
self.robot_code = robot_code
|
||||||
self.access_token_expiry_time = ''
|
self.access_token_expiry_time = ''
|
||||||
|
self.markdown_card = markdown_card
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -128,7 +129,10 @@ class DingTalkClient:
|
|||||||
|
|
||||||
|
|
||||||
async def send_message(self,content:str,incoming_message):
|
async def send_message(self,content:str,incoming_message):
|
||||||
self.EchoTextHandler.reply_text(content,incoming_message)
|
if self.markdown_card:
|
||||||
|
self.EchoTextHandler.reply_markdown(title=self.robot_name+'的回答',text=content,incoming_message=incoming_message)
|
||||||
|
else:
|
||||||
|
self.EchoTextHandler.reply_text(content,incoming_message)
|
||||||
|
|
||||||
|
|
||||||
async def get_incoming_message(self):
|
async def get_incoming_message(self):
|
||||||
@@ -157,6 +161,7 @@ class DingTalkClient:
|
|||||||
|
|
||||||
async def get_message(self,incoming_message:dingtalk_stream.chatbot.ChatbotMessage):
|
async def get_message(self,incoming_message:dingtalk_stream.chatbot.ChatbotMessage):
|
||||||
try:
|
try:
|
||||||
|
|
||||||
# print(json.dumps(incoming_message.to_dict(), indent=4, ensure_ascii=False))
|
# print(json.dumps(incoming_message.to_dict(), indent=4, ensure_ascii=False))
|
||||||
message_data = {
|
message_data = {
|
||||||
"IncomingMessage":incoming_message,
|
"IncomingMessage":incoming_message,
|
||||||
@@ -197,6 +202,53 @@ class DingTalkClient:
|
|||||||
traceback.print_exc()
|
traceback.print_exc()
|
||||||
|
|
||||||
return message_data
|
return message_data
|
||||||
|
|
||||||
|
async def send_proactive_message_to_one(self,target_id:str,content:str):
|
||||||
|
if not await self.check_access_token():
|
||||||
|
await self.get_access_token()
|
||||||
|
|
||||||
|
url = 'https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend'
|
||||||
|
|
||||||
|
headers ={
|
||||||
|
"x-acs-dingtalk-access-token":self.access_token,
|
||||||
|
"Content-Type":"application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
data ={
|
||||||
|
"robotCode":self.robot_code,
|
||||||
|
"userIds":[target_id],
|
||||||
|
"msgKey": "sampleText",
|
||||||
|
"msgParam": json.dumps({"content":content}),
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.post(url,headers=headers,json=data)
|
||||||
|
except Exception:
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
|
||||||
|
async def send_proactive_message_to_group(self,target_id:str,content:str):
|
||||||
|
if not await self.check_access_token():
|
||||||
|
await self.get_access_token()
|
||||||
|
|
||||||
|
url = 'https://api.dingtalk.com/v1.0/robot/groupMessages/send'
|
||||||
|
|
||||||
|
headers ={
|
||||||
|
"x-acs-dingtalk-access-token":self.access_token,
|
||||||
|
"Content-Type":"application/json",
|
||||||
|
}
|
||||||
|
|
||||||
|
data ={
|
||||||
|
"robotCode":self.robot_code,
|
||||||
|
"openConversationId":target_id,
|
||||||
|
"msgKey": "sampleText",
|
||||||
|
"msgParam": json.dumps({"content":content}),
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.post(url,headers=headers,json=data)
|
||||||
|
except Exception:
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
async def start(self):
|
async def start(self):
|
||||||
"""启动 WebSocket 连接,监听消息"""
|
"""启动 WebSocket 连接,监听消息"""
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
# 微信公众号的加解密算法与企业微信一样,所以直接使用企业微信的加解密算法文件
|
# 微信公众号的加解密算法与企业微信一样,所以直接使用企业微信的加解密算法文件
|
||||||
|
from collections import deque
|
||||||
import time
|
import time
|
||||||
import traceback
|
import traceback
|
||||||
from ..wecom_api.WXBizMsgCrypt3 import WXBizMsgCrypt
|
from ..wecom_api.WXBizMsgCrypt3 import WXBizMsgCrypt
|
||||||
@@ -12,6 +13,7 @@ import httpx
|
|||||||
import asyncio
|
import asyncio
|
||||||
import time
|
import time
|
||||||
import xml.etree.ElementTree as ET
|
import xml.etree.ElementTree as ET
|
||||||
|
from pkg.platform.sources import officialaccount as oa
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -25,6 +27,7 @@ xml_template = """
|
|||||||
</xml>
|
</xml>
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class OAClient():
|
class OAClient():
|
||||||
|
|
||||||
def __init__(self,token:str,EncodingAESKey:str,AppID:str,Appsecret:str):
|
def __init__(self,token:str,EncodingAESKey:str,AppID:str,Appsecret:str):
|
||||||
@@ -41,6 +44,7 @@ class OAClient():
|
|||||||
}
|
}
|
||||||
self.access_token_expiry_time = None
|
self.access_token_expiry_time = None
|
||||||
self.msg_id_map = {}
|
self.msg_id_map = {}
|
||||||
|
self.generated_content = {}
|
||||||
|
|
||||||
async def handle_callback_request(self):
|
async def handle_callback_request(self):
|
||||||
|
|
||||||
@@ -83,12 +87,10 @@ class OAClient():
|
|||||||
from_user = root.find("FromUserName").text # 发送者
|
from_user = root.find("FromUserName").text # 发送者
|
||||||
to_user = root.find("ToUserName").text # 机器人
|
to_user = root.find("ToUserName").text # 机器人
|
||||||
|
|
||||||
from pkg.platform.sources import officialaccount
|
|
||||||
|
|
||||||
timeout = 4.80
|
timeout = 4.80
|
||||||
interval = 0.1
|
interval = 0.1
|
||||||
while True:
|
while True:
|
||||||
content = officialaccount.generated_content.pop(message_data["MsgId"], None)
|
content = self.generated_content.pop(message_data["MsgId"], None)
|
||||||
if content:
|
if content:
|
||||||
response_xml = xml_template.format(
|
response_xml = xml_template.format(
|
||||||
to_user=from_user,
|
to_user=from_user,
|
||||||
@@ -168,6 +170,168 @@ class OAClient():
|
|||||||
for handler in self._message_handlers[msg_type]:
|
for handler in self._message_handlers[msg_type]:
|
||||||
await handler(event)
|
await handler(event)
|
||||||
|
|
||||||
|
async def set_message(self,msg_id:int,content:str):
|
||||||
|
self.generated_content[msg_id] = content
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class OAClientForLongerResponse():
|
||||||
|
|
||||||
|
def __init__(self,token:str,EncodingAESKey:str,AppID:str,Appsecret:str,LoadingMessage:str):
|
||||||
|
self.token = token
|
||||||
|
self.aes = EncodingAESKey
|
||||||
|
self.appid = AppID
|
||||||
|
self.appsecret = Appsecret
|
||||||
|
self.base_url = 'https://api.weixin.qq.com'
|
||||||
|
self.access_token = ''
|
||||||
|
self.app = Quart(__name__)
|
||||||
|
self.app.add_url_rule('/callback/command', 'handle_callback', self.handle_callback_request, methods=['GET', 'POST'])
|
||||||
|
self._message_handlers = {
|
||||||
|
"example":[],
|
||||||
|
}
|
||||||
|
self.access_token_expiry_time = None
|
||||||
|
self.loading_message = LoadingMessage
|
||||||
|
self.msg_queue = {}
|
||||||
|
self.user_msg_queue = {}
|
||||||
|
|
||||||
|
async def handle_callback_request(self):
|
||||||
|
try:
|
||||||
|
start_time = time.time()
|
||||||
|
signature = request.args.get("signature", "")
|
||||||
|
timestamp = request.args.get("timestamp", "")
|
||||||
|
nonce = request.args.get("nonce", "")
|
||||||
|
echostr = request.args.get("echostr", "")
|
||||||
|
msg_signature = request.args.get("msg_signature", "")
|
||||||
|
|
||||||
|
if msg_signature is None:
|
||||||
|
raise Exception("msg_signature不在请求体中")
|
||||||
|
|
||||||
|
if request.method == 'GET':
|
||||||
|
check_str = "".join(sorted([self.token, timestamp, nonce]))
|
||||||
|
check_signature = hashlib.sha1(check_str.encode("utf-8")).hexdigest()
|
||||||
|
return echostr if check_signature == signature else "拒绝请求"
|
||||||
|
|
||||||
|
elif request.method == "POST":
|
||||||
|
encryt_msg = await request.data
|
||||||
|
wxcpt = WXBizMsgCrypt(self.token, self.aes, self.appid)
|
||||||
|
ret, xml_msg = wxcpt.DecryptMsg(encryt_msg, msg_signature, timestamp, nonce)
|
||||||
|
xml_msg = xml_msg.decode('utf-8')
|
||||||
|
|
||||||
|
if ret != 0:
|
||||||
|
raise Exception("消息解密失败")
|
||||||
|
|
||||||
|
# 解析 XML
|
||||||
|
root = ET.fromstring(xml_msg)
|
||||||
|
from_user = root.find("FromUserName").text
|
||||||
|
to_user = root.find("ToUserName").text
|
||||||
|
|
||||||
|
|
||||||
|
if self.msg_queue.get(from_user) and self.msg_queue[from_user][0]["content"]:
|
||||||
|
|
||||||
|
queue_top = self.msg_queue[from_user].pop(0)
|
||||||
|
queue_content = queue_top["content"]
|
||||||
|
|
||||||
|
# 弹出用户消息
|
||||||
|
if self.user_msg_queue.get(from_user) and self.user_msg_queue[from_user]:
|
||||||
|
self.user_msg_queue[from_user].pop(0)
|
||||||
|
|
||||||
|
response_xml = xml_template.format(
|
||||||
|
to_user=from_user,
|
||||||
|
from_user=to_user,
|
||||||
|
create_time=int(time.time()),
|
||||||
|
content=queue_content
|
||||||
|
)
|
||||||
|
return response_xml
|
||||||
|
|
||||||
|
else:
|
||||||
|
response_xml = xml_template.format(
|
||||||
|
to_user=from_user,
|
||||||
|
from_user=to_user,
|
||||||
|
create_time=int(time.time()),
|
||||||
|
content=self.loading_message
|
||||||
|
)
|
||||||
|
|
||||||
|
if self.user_msg_queue.get(from_user) and self.user_msg_queue[from_user][0]["content"]:
|
||||||
|
return response_xml
|
||||||
|
else:
|
||||||
|
message_data = await self.get_message(xml_msg)
|
||||||
|
|
||||||
|
if message_data:
|
||||||
|
event = OAEvent.from_payload(message_data)
|
||||||
|
if event:
|
||||||
|
self.user_msg_queue.setdefault(from_user,[]).append(
|
||||||
|
{
|
||||||
|
"content":event.message,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
await self._handle_message(event)
|
||||||
|
|
||||||
|
return response_xml
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def get_message(self, xml_msg: str):
|
||||||
|
|
||||||
|
root = ET.fromstring(xml_msg)
|
||||||
|
|
||||||
|
message_data = {
|
||||||
|
"ToUserName": root.find("ToUserName").text,
|
||||||
|
"FromUserName": root.find("FromUserName").text,
|
||||||
|
"CreateTime": int(root.find("CreateTime").text),
|
||||||
|
"MsgType": root.find("MsgType").text,
|
||||||
|
"Content": root.find("Content").text if root.find("Content") is not None else None,
|
||||||
|
"MsgId": int(root.find("MsgId").text) if root.find("MsgId") is not None else None,
|
||||||
|
}
|
||||||
|
|
||||||
|
return message_data
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def run_task(self, host: str, port: int, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
启动 Quart 应用。
|
||||||
|
"""
|
||||||
|
await self.app.run_task(host=host, port=port, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def on_message(self, msg_type: str):
|
||||||
|
"""
|
||||||
|
注册消息类型处理器。
|
||||||
|
"""
|
||||||
|
def decorator(func: Callable[[OAEvent], None]):
|
||||||
|
if msg_type not in self._message_handlers:
|
||||||
|
self._message_handlers[msg_type] = []
|
||||||
|
self._message_handlers[msg_type].append(func)
|
||||||
|
return func
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
async def _handle_message(self, event: OAEvent):
|
||||||
|
"""
|
||||||
|
处理消息事件。
|
||||||
|
"""
|
||||||
|
|
||||||
|
msg_type = event.type
|
||||||
|
if msg_type in self._message_handlers:
|
||||||
|
for handler in self._message_handlers[msg_type]:
|
||||||
|
await handler(event)
|
||||||
|
|
||||||
|
async def set_message(self,from_user:int,message_id:int,content:str):
|
||||||
|
if from_user not in self.msg_queue:
|
||||||
|
self.msg_queue[from_user] = []
|
||||||
|
|
||||||
|
self.msg_queue[from_user].append(
|
||||||
|
{
|
||||||
|
"msg_id":message_id,
|
||||||
|
"content":content,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
0
libs/slack_api/__init__.py
Normal file
0
libs/slack_api/__init__.py
Normal file
111
libs/slack_api/api.py
Normal file
111
libs/slack_api/api.py
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import json
|
||||||
|
from quart import Quart, jsonify,request
|
||||||
|
from slack_sdk.web.async_client import AsyncWebClient
|
||||||
|
from .slackevent import SlackEvent
|
||||||
|
from typing import Callable, Dict, Any
|
||||||
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
|
|
||||||
|
class SlackClient():
|
||||||
|
|
||||||
|
def __init__(self,bot_token:str,signing_secret:str):
|
||||||
|
|
||||||
|
self.bot_token = bot_token
|
||||||
|
self.signing_secret = signing_secret
|
||||||
|
self.app = Quart(__name__)
|
||||||
|
self.client = AsyncWebClient(self.bot_token)
|
||||||
|
self.app.add_url_rule('/callback/command', 'handle_callback', self.handle_callback_request, methods=['GET', 'POST'])
|
||||||
|
self._message_handlers = {
|
||||||
|
"example":[],
|
||||||
|
}
|
||||||
|
self.bot_user_id = None # 避免机器人回复自己的消息
|
||||||
|
|
||||||
|
async def handle_callback_request(self):
|
||||||
|
try:
|
||||||
|
body = await request.get_data()
|
||||||
|
data = json.loads(body)
|
||||||
|
if 'type' in data:
|
||||||
|
if data['type'] == 'url_verification':
|
||||||
|
return data['challenge']
|
||||||
|
|
||||||
|
bot_user_id = data.get("event",{}).get("bot_id","")
|
||||||
|
|
||||||
|
if self.bot_user_id and bot_user_id == self.bot_user_id:
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
|
||||||
|
# 处理私信
|
||||||
|
if data and data.get("event", {}).get("channel_type") in ["im"]:
|
||||||
|
event = SlackEvent.from_payload(data)
|
||||||
|
await self._handle_message(event)
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
#处理群聊
|
||||||
|
if data.get("event",{}).get("type") == 'app_mention':
|
||||||
|
data.setdefault("event", {})["channel_type"] = "channel"
|
||||||
|
event = SlackEvent.from_payload(data)
|
||||||
|
await self._handle_message(event)
|
||||||
|
return jsonify({'status':'ok'})
|
||||||
|
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
raise(e)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def _handle_message(self, event: SlackEvent):
|
||||||
|
"""
|
||||||
|
处理消息事件。
|
||||||
|
"""
|
||||||
|
msg_type = event.type
|
||||||
|
if msg_type in self._message_handlers:
|
||||||
|
for handler in self._message_handlers[msg_type]:
|
||||||
|
await handler(event)
|
||||||
|
|
||||||
|
def on_message(self, msg_type: str):
|
||||||
|
"""注册消息类型处理器"""
|
||||||
|
def decorator(func: Callable[[platform_events.Event], None]):
|
||||||
|
if msg_type not in self._message_handlers:
|
||||||
|
self._message_handlers[msg_type] = []
|
||||||
|
self._message_handlers[msg_type].append(func)
|
||||||
|
return func
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
async def send_message_to_channel(self,text:str,channel_id:str):
|
||||||
|
try:
|
||||||
|
response = await self.client.chat_postMessage(
|
||||||
|
channel=channel_id,
|
||||||
|
text=text
|
||||||
|
)
|
||||||
|
if self.bot_user_id is None and response.get("ok"):
|
||||||
|
self.bot_user_id = response["message"]["bot_id"]
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
raise e
|
||||||
|
|
||||||
|
async def send_message_to_one(self,text:str,user_id:str):
|
||||||
|
try:
|
||||||
|
response = await self.client.chat_postMessage(
|
||||||
|
channel = '@'+user_id,
|
||||||
|
text= text
|
||||||
|
)
|
||||||
|
if self.bot_user_id is None and response.get("ok"):
|
||||||
|
self.bot_user_id = response["message"]["bot_id"]
|
||||||
|
|
||||||
|
return
|
||||||
|
except Exception as e:
|
||||||
|
raise e
|
||||||
|
|
||||||
|
async def run_task(self, host: str, port: int, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
启动 Quart 应用。
|
||||||
|
"""
|
||||||
|
await self.app.run_task(host=host, port=port, *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
91
libs/slack_api/slackevent.py
Normal file
91
libs/slack_api/slackevent.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
from typing import Dict, Any, Optional
|
||||||
|
|
||||||
|
class SlackEvent(dict):
|
||||||
|
@staticmethod
|
||||||
|
def from_payload(payload: Dict[str, Any]) -> Optional["SlackEvent"]:
|
||||||
|
try:
|
||||||
|
event = SlackEvent(payload)
|
||||||
|
return event
|
||||||
|
except KeyError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def text(self) -> str:
|
||||||
|
|
||||||
|
if self.get("event", {}).get("channel_type") == "im":
|
||||||
|
blocks = self.get("event", {}).get("blocks", [])
|
||||||
|
if not blocks:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
elements = blocks[0].get("elements", [])
|
||||||
|
if not elements:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
elements = elements[0].get("elements", [])
|
||||||
|
text = ""
|
||||||
|
|
||||||
|
for el in elements:
|
||||||
|
if el.get("type") == "text":
|
||||||
|
text += el.get("text", "")
|
||||||
|
elif el.get("type") == "link":
|
||||||
|
text += el.get("url", "")
|
||||||
|
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
if self.get("event",{}).get("channel_type") == 'channel':
|
||||||
|
message_text = ""
|
||||||
|
for block in self.get("event", {}).get("blocks", []):
|
||||||
|
if block.get("type") == "rich_text":
|
||||||
|
for element in block.get("elements", []):
|
||||||
|
if element.get("type") == "rich_text_section":
|
||||||
|
parts = []
|
||||||
|
for el in element.get("elements", []):
|
||||||
|
if el.get("type") == "text":
|
||||||
|
parts.append(el["text"])
|
||||||
|
elif el.get("type") == "link":
|
||||||
|
parts.append(el["url"])
|
||||||
|
message_text = "".join(parts)
|
||||||
|
|
||||||
|
return message_text
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@property
|
||||||
|
def user_id(self) -> Optional[str]:
|
||||||
|
return self.get("event", {}).get("user","")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def channel_id(self) -> Optional[str]:
|
||||||
|
return self.get("event", {}).get("channel","")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> str:
|
||||||
|
""" message对应私聊,app_mention对应频道at """
|
||||||
|
return self.get("event", {}).get("channel_type", "")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def message_id(self) -> str:
|
||||||
|
return self.get("event_id","")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pic_url(self) -> str:
|
||||||
|
"""提取 Slack 事件中的图片 URL"""
|
||||||
|
files = self.get("event", {}).get("files", [])
|
||||||
|
if files:
|
||||||
|
return files[0].get("url_private", "")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@property
|
||||||
|
def sender_name(self) -> str:
|
||||||
|
return self.get("event", {}).get("user","")
|
||||||
|
|
||||||
|
def __getattr__(self, key: str) -> Optional[Any]:
|
||||||
|
return self.get(key)
|
||||||
|
|
||||||
|
def __setattr__(self, key: str, value: Any) -> None:
|
||||||
|
self[key] = value
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"<SlackEvent {super().__repr__()}>"
|
||||||
@@ -66,7 +66,7 @@ class WecomClient():
|
|||||||
else:
|
else:
|
||||||
raise Exception("未获取用户")
|
raise Exception("未获取用户")
|
||||||
|
|
||||||
async def send_to_all(self,content:str):
|
async def send_to_all(self,content:str,agent_id:int):
|
||||||
if not self.check_access_token_for_contacts():
|
if not self.check_access_token_for_contacts():
|
||||||
self.access_token_for_contacts = await self.get_access_token(self.secret_for_contacts)
|
self.access_token_for_contacts = await self.get_access_token(self.secret_for_contacts)
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ class WecomClient():
|
|||||||
params = {
|
params = {
|
||||||
"touser" : user_ids_string,
|
"touser" : user_ids_string,
|
||||||
"msgtype" : "text",
|
"msgtype" : "text",
|
||||||
"agentid" : 1000002,
|
"agentid" : agent_id,
|
||||||
"text" : {
|
"text" : {
|
||||||
"content" : content,
|
"content" : content,
|
||||||
},
|
},
|
||||||
|
|||||||
0
libs/wecom_customer_service_api/__init__.py
Normal file
0
libs/wecom_customer_service_api/__init__.py
Normal file
337
libs/wecom_customer_service_api/api.py
Normal file
337
libs/wecom_customer_service_api/api.py
Normal file
@@ -0,0 +1,337 @@
|
|||||||
|
from quart import request
|
||||||
|
from ..wecom_api.WXBizMsgCrypt3 import WXBizMsgCrypt
|
||||||
|
import base64
|
||||||
|
import binascii
|
||||||
|
import httpx
|
||||||
|
import traceback
|
||||||
|
from quart import Quart
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from typing import Callable, Dict, Any
|
||||||
|
from .wecomcsevent import WecomCSEvent
|
||||||
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
|
import aiofiles
|
||||||
|
|
||||||
|
|
||||||
|
class WecomCSClient():
|
||||||
|
def __init__(self,corpid:str,secret:str,token:str,EncodingAESKey:str):
|
||||||
|
self.corpid = corpid
|
||||||
|
self.secret = secret
|
||||||
|
self.access_token_for_contacts =''
|
||||||
|
self.token = token
|
||||||
|
self.aes = EncodingAESKey
|
||||||
|
self.base_url = 'https://qyapi.weixin.qq.com/cgi-bin'
|
||||||
|
self.access_token = ''
|
||||||
|
self.app = Quart(__name__)
|
||||||
|
self.wxcpt = WXBizMsgCrypt(self.token, self.aes, self.corpid)
|
||||||
|
self.app.add_url_rule('/callback/command', 'handle_callback', self.handle_callback_request, methods=['GET', 'POST'])
|
||||||
|
self._message_handlers = {
|
||||||
|
"example":[],
|
||||||
|
}
|
||||||
|
|
||||||
|
async def get_pic_url(self, media_id: str):
|
||||||
|
if not await self.check_access_token():
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
|
||||||
|
url = f"{self.base_url}/media/get?access_token={self.access_token}&media_id={media_id}"
|
||||||
|
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.get(url)
|
||||||
|
if response.headers.get("Content-Type", "").startswith("application/json"):
|
||||||
|
data = response.json()
|
||||||
|
if data.get('errcode') in [40014, 42001]:
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
return await self.get_pic_url(media_id)
|
||||||
|
else:
|
||||||
|
raise Exception("Failed to get image: " + str(data))
|
||||||
|
|
||||||
|
# 否则是图片,转成 base64
|
||||||
|
image_bytes = response.content
|
||||||
|
content_type = response.headers.get("Content-Type", "")
|
||||||
|
base64_str = base64.b64encode(image_bytes).decode("utf-8")
|
||||||
|
base64_str = f"data:{content_type};base64,{base64_str}"
|
||||||
|
return base64_str
|
||||||
|
|
||||||
|
|
||||||
|
#access——token操作
|
||||||
|
async def check_access_token(self):
|
||||||
|
return bool(self.access_token and self.access_token.strip())
|
||||||
|
|
||||||
|
async def check_access_token_for_contacts(self):
|
||||||
|
return bool(self.access_token_for_contacts and self.access_token_for_contacts.strip())
|
||||||
|
|
||||||
|
async def get_access_token(self,secret):
|
||||||
|
url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corpid}&corpsecret={secret}'
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.get(url)
|
||||||
|
data = response.json()
|
||||||
|
if 'access_token' in data:
|
||||||
|
return data['access_token']
|
||||||
|
else:
|
||||||
|
raise Exception(f"未获取access token: {data}")
|
||||||
|
|
||||||
|
async def get_detailed_message_list(self,xml_msg:str):
|
||||||
|
# 在本方法中解析消息,并且获得消息的具体内容
|
||||||
|
root = ET.fromstring(xml_msg)
|
||||||
|
token = root.find("Token").text
|
||||||
|
open_kfid = root.find("OpenKfId").text
|
||||||
|
|
||||||
|
# if open_kfid in self.openkfid_list:
|
||||||
|
# return None
|
||||||
|
# else:
|
||||||
|
# self.openkfid_list.append(open_kfid)
|
||||||
|
|
||||||
|
if not await self.check_access_token():
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
|
||||||
|
url = self.base_url+'/kf/sync_msg?access_token='+ self.access_token
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
params = {
|
||||||
|
"token": token,
|
||||||
|
"voice_format": 0,
|
||||||
|
"open_kfid": open_kfid,
|
||||||
|
}
|
||||||
|
response = await client.post(url,json=params)
|
||||||
|
data = response.json()
|
||||||
|
if data['errcode'] != 0:
|
||||||
|
raise Exception("Failed to get message")
|
||||||
|
if data['errcode'] == 40014 or data['errcode'] == 42001:
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
return await self.get_detailed_message_list(xml_msg)
|
||||||
|
last_msg_data = data['msg_list'][-1]
|
||||||
|
open_kfid = last_msg_data.get("open_kfid")
|
||||||
|
# 进行获取图片操作
|
||||||
|
if last_msg_data.get("msgtype") == "image":
|
||||||
|
media_id = last_msg_data.get("image").get("media_id")
|
||||||
|
picurl = await self.get_pic_url(media_id)
|
||||||
|
last_msg_data["picurl"] = picurl
|
||||||
|
# await self.change_service_status(userid=external_userid,openkfid=open_kfid,servicer=servicer)
|
||||||
|
return last_msg_data
|
||||||
|
|
||||||
|
|
||||||
|
async def change_service_status(self,userid:str,openkfid:str,servicer:str):
|
||||||
|
if not await self.check_access_token():
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
url = self.base_url+"/kf/service_state/get?access_token="+self.access_token
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
params = {
|
||||||
|
"open_kfid" : openkfid,
|
||||||
|
"external_userid" : userid,
|
||||||
|
"service_state" : 1,
|
||||||
|
"servicer_userid" : servicer,
|
||||||
|
}
|
||||||
|
response = await client.post(url,json=params)
|
||||||
|
data = response.json()
|
||||||
|
if data['errcode'] == 40014 or data['errcode'] == 42001:
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
return await self.change_service_status(userid,openkfid)
|
||||||
|
if data['errcode'] != 0:
|
||||||
|
raise Exception("Failed to change service status: "+str(data))
|
||||||
|
|
||||||
|
|
||||||
|
async def send_image(self,user_id:str,agent_id:int,media_id:str):
|
||||||
|
if not await self.check_access_token():
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
url = self.base_url+'/media/upload?access_token='+self.access_token
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
params = {
|
||||||
|
"touser" : user_id,
|
||||||
|
"toparty" : "",
|
||||||
|
"totag":"",
|
||||||
|
"agentid" : agent_id,
|
||||||
|
"msgtype" : "image",
|
||||||
|
"image" : {
|
||||||
|
"media_id" : media_id,
|
||||||
|
},
|
||||||
|
"safe":0,
|
||||||
|
"enable_id_trans": 0,
|
||||||
|
"enable_duplicate_check": 0,
|
||||||
|
"duplicate_check_interval": 1800
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
response = await client.post(url,json=params)
|
||||||
|
data = response.json()
|
||||||
|
except Exception as e:
|
||||||
|
raise Exception("Failed to send image: "+str(e))
|
||||||
|
|
||||||
|
# 企业微信错误码40014和42001,代表accesstoken问题
|
||||||
|
if data['errcode'] == 40014 or data['errcode'] == 42001:
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
return await self.send_image(user_id,agent_id,media_id)
|
||||||
|
|
||||||
|
if data['errcode'] != 0:
|
||||||
|
raise Exception("Failed to send image: "+str(data))
|
||||||
|
|
||||||
|
|
||||||
|
async def send_text_msg(self, open_kfid: str, external_userid: str, msgid: str,content:str):
|
||||||
|
if not await self.check_access_token():
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
|
||||||
|
url = f"https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token={self.access_token}"
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"touser": external_userid,
|
||||||
|
"open_kfid": open_kfid,
|
||||||
|
"msgid": msgid,
|
||||||
|
"msgtype": "text",
|
||||||
|
"text": {
|
||||||
|
"content": content,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.post(url, json=payload)
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
if data.get("errcode") != 0:
|
||||||
|
raise Exception(f"消息发送失败: {data}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_callback_request(self):
|
||||||
|
"""
|
||||||
|
处理回调请求,包括 GET 验证和 POST 消息接收。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
|
||||||
|
msg_signature = request.args.get("msg_signature")
|
||||||
|
timestamp = request.args.get("timestamp")
|
||||||
|
nonce = request.args.get("nonce")
|
||||||
|
|
||||||
|
if request.method == "GET":
|
||||||
|
echostr = request.args.get("echostr")
|
||||||
|
ret, reply_echo_str = self.wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
|
||||||
|
if ret != 0:
|
||||||
|
raise Exception(f"验证失败,错误码: {ret}")
|
||||||
|
return reply_echo_str
|
||||||
|
|
||||||
|
elif request.method == "POST":
|
||||||
|
encrypt_msg = await request.data
|
||||||
|
ret, xml_msg = self.wxcpt.DecryptMsg(encrypt_msg, msg_signature, timestamp, nonce)
|
||||||
|
if ret != 0:
|
||||||
|
raise Exception(f"消息解密失败,错误码: {ret}")
|
||||||
|
|
||||||
|
# 解析消息并处理
|
||||||
|
message_data = await self.get_detailed_message_list(xml_msg)
|
||||||
|
if message_data is not None:
|
||||||
|
event = WecomCSEvent.from_payload(message_data)
|
||||||
|
if event:
|
||||||
|
await self._handle_message(event)
|
||||||
|
|
||||||
|
return "success"
|
||||||
|
except Exception as e:
|
||||||
|
traceback.print_exc()
|
||||||
|
return f"Error processing request: {str(e)}", 400
|
||||||
|
|
||||||
|
async def run_task(self, host: str, port: int, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
启动 Quart 应用。
|
||||||
|
"""
|
||||||
|
await self.app.run_task(host=host, port=port, *args, **kwargs)
|
||||||
|
|
||||||
|
def on_message(self, msg_type: str):
|
||||||
|
"""
|
||||||
|
注册消息类型处理器。
|
||||||
|
"""
|
||||||
|
def decorator(func: Callable[[WecomCSEvent], None]):
|
||||||
|
if msg_type not in self._message_handlers:
|
||||||
|
self._message_handlers[msg_type] = []
|
||||||
|
self._message_handlers[msg_type].append(func)
|
||||||
|
return func
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
async def _handle_message(self, event: WecomCSEvent):
|
||||||
|
"""
|
||||||
|
处理消息事件。
|
||||||
|
"""
|
||||||
|
msg_type = event.type
|
||||||
|
if msg_type in self._message_handlers:
|
||||||
|
for handler in self._message_handlers[msg_type]:
|
||||||
|
await handler(event)
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def get_image_type(image_bytes: bytes) -> str:
|
||||||
|
"""
|
||||||
|
通过图片的magic numbers判断图片类型
|
||||||
|
"""
|
||||||
|
magic_numbers = {
|
||||||
|
b'\xFF\xD8\xFF': 'jpg',
|
||||||
|
b'\x89\x50\x4E\x47': 'png',
|
||||||
|
b'\x47\x49\x46': 'gif',
|
||||||
|
b'\x42\x4D': 'bmp',
|
||||||
|
b'\x00\x00\x01\x00': 'ico'
|
||||||
|
}
|
||||||
|
|
||||||
|
for magic, ext in magic_numbers.items():
|
||||||
|
if image_bytes.startswith(magic):
|
||||||
|
return ext
|
||||||
|
return 'jpg' # 默认返回jpg
|
||||||
|
|
||||||
|
|
||||||
|
async def upload_to_work(self, image: platform_message.Image):
|
||||||
|
"""
|
||||||
|
获取 media_id
|
||||||
|
"""
|
||||||
|
if not await self.check_access_token():
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
|
||||||
|
url = self.base_url + '/media/upload?access_token=' + self.access_token + '&type=file'
|
||||||
|
file_bytes = None
|
||||||
|
file_name = "uploaded_file.txt"
|
||||||
|
|
||||||
|
# 获取文件的二进制数据
|
||||||
|
if image.path:
|
||||||
|
async with aiofiles.open(image.path, 'rb') as f:
|
||||||
|
file_bytes = await f.read()
|
||||||
|
file_name = image.path.split('/')[-1]
|
||||||
|
elif image.url:
|
||||||
|
file_bytes = await self.download_image_to_bytes(image.url)
|
||||||
|
file_name = image.url.split('/')[-1]
|
||||||
|
elif image.base64:
|
||||||
|
try:
|
||||||
|
base64_data = image.base64
|
||||||
|
if ',' in base64_data:
|
||||||
|
base64_data = base64_data.split(',', 1)[1]
|
||||||
|
padding = 4 - (len(base64_data) % 4) if len(base64_data) % 4 else 0
|
||||||
|
padded_base64 = base64_data + '=' * padding
|
||||||
|
file_bytes = base64.b64decode(padded_base64)
|
||||||
|
except binascii.Error as e:
|
||||||
|
raise ValueError(f"Invalid base64 string: {str(e)}")
|
||||||
|
else:
|
||||||
|
raise ValueError("image对象出错")
|
||||||
|
|
||||||
|
# 设置 multipart/form-data 格式的文件
|
||||||
|
boundary = "-------------------------acebdf13572468"
|
||||||
|
headers = {
|
||||||
|
'Content-Type': f'multipart/form-data; boundary={boundary}'
|
||||||
|
}
|
||||||
|
body = (
|
||||||
|
f"--{boundary}\r\n"
|
||||||
|
f"Content-Disposition: form-data; name=\"media\"; filename=\"{file_name}\"; filelength={len(file_bytes)}\r\n"
|
||||||
|
f"Content-Type: application/octet-stream\r\n\r\n"
|
||||||
|
).encode('utf-8') + file_bytes + f"\r\n--{boundary}--\r\n".encode('utf-8')
|
||||||
|
|
||||||
|
# 上传文件
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.post(url, headers=headers, content=body)
|
||||||
|
data = response.json()
|
||||||
|
if data['errcode'] == 40014 or data['errcode'] == 42001:
|
||||||
|
self.access_token = await self.get_access_token(self.secret)
|
||||||
|
media_id = await self.upload_to_work(image)
|
||||||
|
if data.get('errcode', 0) != 0:
|
||||||
|
raise Exception("failed to upload file")
|
||||||
|
|
||||||
|
media_id = data.get('media_id')
|
||||||
|
return media_id
|
||||||
|
|
||||||
|
async def download_image_to_bytes(self,url:str) -> bytes:
|
||||||
|
async with httpx.AsyncClient() as client:
|
||||||
|
response = await client.get(url)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.content
|
||||||
|
|
||||||
|
#进行media_id的获取
|
||||||
|
async def get_media_id(self, image: platform_message.Image):
|
||||||
|
|
||||||
|
media_id = await self.upload_to_work(image=image)
|
||||||
|
return media_id
|
||||||
134
libs/wecom_customer_service_api/wecomcsevent.py
Normal file
134
libs/wecom_customer_service_api/wecomcsevent.py
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
from typing import Dict, Any, Optional
|
||||||
|
|
||||||
|
|
||||||
|
class WecomCSEvent(dict):
|
||||||
|
"""
|
||||||
|
封装从企业微信收到的事件数据对象(字典),提供属性以获取其中的字段。
|
||||||
|
|
||||||
|
除 `type` 和 `detail_type` 属性对于任何事件都有效外,其它属性是否存在(若不存在则返回 `None`)依事件类型不同而不同。
|
||||||
|
"""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def from_payload(payload: Dict[str, Any]) -> Optional["WecomCSEvent"]:
|
||||||
|
"""
|
||||||
|
从企业微信(客服会话)事件数据构造 `WecomEvent` 对象。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
payload (Dict[str, Any]): 解密后的企业微信事件数据。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[WecomEvent]: 如果事件数据合法,则返回 WecomEvent 对象;否则返回 None。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
event = WecomCSEvent(payload)
|
||||||
|
_ = event.type,
|
||||||
|
return event
|
||||||
|
except KeyError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def type(self) -> str:
|
||||||
|
"""
|
||||||
|
事件类型,例如 "message"、"event"、"text" 等。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 事件类型。
|
||||||
|
"""
|
||||||
|
return self.get("msgtype", "")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def user_id(self) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
用户 ID,例如消息的发送者或事件的触发者。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[str]: 用户 ID。
|
||||||
|
"""
|
||||||
|
return self.get("external_userid")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def receiver_id(self) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
接收者 ID,例如机器人自身的企业微信 ID。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[str]: 接收者 ID。
|
||||||
|
"""
|
||||||
|
return self.get("open_kfid","")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def picurl(self) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
图片 URL,仅在图片消息中存在。
|
||||||
|
base64格式
|
||||||
|
Returns:
|
||||||
|
Optional[str]: 图片 URL。
|
||||||
|
"""
|
||||||
|
|
||||||
|
return self.get("picurl","")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def message_id(self) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
消息 ID,仅在消息类型事件中存在。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[str]: 消息 ID。
|
||||||
|
"""
|
||||||
|
return self.get("msgid")
|
||||||
|
|
||||||
|
@property
|
||||||
|
def message(self) -> Optional[str]:
|
||||||
|
"""
|
||||||
|
消息内容,仅在消息类型事件中存在。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[str]: 消息内容。
|
||||||
|
"""
|
||||||
|
if self.get("msgtype") == 'text':
|
||||||
|
return self.get("text").get("content","")
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@property
|
||||||
|
def timestamp(self) -> Optional[int]:
|
||||||
|
"""
|
||||||
|
事件发生的时间戳。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[int]: 时间戳。
|
||||||
|
"""
|
||||||
|
return self.get("send_time")
|
||||||
|
|
||||||
|
|
||||||
|
def __getattr__(self, key: str) -> Optional[Any]:
|
||||||
|
"""
|
||||||
|
允许通过属性访问数据中的任意字段。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key (str): 字段名。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Optional[Any]: 字段值。
|
||||||
|
"""
|
||||||
|
return self.get(key)
|
||||||
|
|
||||||
|
def __setattr__(self, key: str, value: Any) -> None:
|
||||||
|
"""
|
||||||
|
允许通过属性设置数据中的任意字段。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
key (str): 字段名。
|
||||||
|
value (Any): 字段值。
|
||||||
|
"""
|
||||||
|
self[key] = value
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
"""
|
||||||
|
生成事件对象的字符串表示。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
str: 字符串表示。
|
||||||
|
"""
|
||||||
|
return f"<WecomEvent {super().__repr__()}>"
|
||||||
@@ -66,8 +66,42 @@ class HTTPController:
|
|||||||
|
|
||||||
@self.quart_app.route("/")
|
@self.quart_app.route("/")
|
||||||
async def index():
|
async def index():
|
||||||
return await quart.send_from_directory(frontend_path, "index.html")
|
return await quart.send_from_directory(
|
||||||
|
frontend_path,
|
||||||
|
"index.html",
|
||||||
|
mimetype="text/html"
|
||||||
|
)
|
||||||
|
|
||||||
@self.quart_app.route("/<path:path>")
|
@self.quart_app.route("/<path:path>")
|
||||||
async def static_file(path: str):
|
async def static_file(path: str):
|
||||||
return await quart.send_from_directory(frontend_path, path)
|
|
||||||
|
mimetype = None
|
||||||
|
|
||||||
|
if path.endswith(".html"):
|
||||||
|
mimetype = "text/html"
|
||||||
|
elif path.endswith(".js"):
|
||||||
|
mimetype = "application/javascript"
|
||||||
|
elif path.endswith(".css"):
|
||||||
|
mimetype = "text/css"
|
||||||
|
elif path.endswith(".png"):
|
||||||
|
mimetype = "image/png"
|
||||||
|
elif path.endswith(".jpg"):
|
||||||
|
mimetype = "image/jpeg"
|
||||||
|
elif path.endswith(".jpeg"):
|
||||||
|
mimetype = "image/jpeg"
|
||||||
|
elif path.endswith(".gif"):
|
||||||
|
mimetype = "image/gif"
|
||||||
|
elif path.endswith(".svg"):
|
||||||
|
mimetype = "image/svg+xml"
|
||||||
|
elif path.endswith(".ico"):
|
||||||
|
mimetype = "image/x-icon"
|
||||||
|
elif path.endswith(".json"):
|
||||||
|
mimetype = "application/json"
|
||||||
|
elif path.endswith(".txt"):
|
||||||
|
mimetype = "text/plain"
|
||||||
|
|
||||||
|
return await quart.send_from_directory(
|
||||||
|
frontend_path,
|
||||||
|
path,
|
||||||
|
mimetype=mimetype
|
||||||
|
)
|
||||||
@@ -16,7 +16,6 @@ class FuncOperator(operator.CommandOperator):
|
|||||||
|
|
||||||
all_functions = await self.ap.tool_mgr.get_all_functions(
|
all_functions = await self.ap.tool_mgr.get_all_functions(
|
||||||
plugin_enabled=True,
|
plugin_enabled=True,
|
||||||
plugin_status=plugin_context.RuntimeContainerStatus.INITIALIZED,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
for func in all_functions:
|
for func in all_functions:
|
||||||
|
|||||||
@@ -204,6 +204,8 @@ class Application:
|
|||||||
case core_entities.LifecycleControlScope.PROVIDER.value:
|
case core_entities.LifecycleControlScope.PROVIDER.value:
|
||||||
self.logger.info("执行热重载 scope="+scope)
|
self.logger.info("执行热重载 scope="+scope)
|
||||||
|
|
||||||
|
await self.tool_mgr.shutdown()
|
||||||
|
|
||||||
latest_llm_model_config = await config.load_json_config("data/metadata/llm-models.json", "templates/metadata/llm-models.json")
|
latest_llm_model_config = await config.load_json_config("data/metadata/llm-models.json", "templates/metadata/llm-models.json")
|
||||||
self.llm_models_meta = latest_llm_model_config
|
self.llm_models_meta = latest_llm_model_config
|
||||||
llm_model_mgr_inst = llm_model_mgr.ModelManager(self)
|
llm_model_mgr_inst = llm_model_mgr.ModelManager(self)
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ required_deps = {
|
|||||||
"dingtalk_stream": "dingtalk_stream",
|
"dingtalk_stream": "dingtalk_stream",
|
||||||
"dashscope": "dashscope",
|
"dashscope": "dashscope",
|
||||||
"telegram": "python-telegram-bot",
|
"telegram": "python-telegram-bot",
|
||||||
|
"certifi": "certifi",
|
||||||
|
"mcp": "mcp",
|
||||||
|
"telegramify_markdown":"telegramify-markdown",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -72,6 +72,9 @@ class Query(pydantic.BaseModel):
|
|||||||
user_message: typing.Optional[llm_entities.Message] = None
|
user_message: typing.Optional[llm_entities.Message] = None
|
||||||
"""此次请求的用户消息对象,由前置处理器阶段设置"""
|
"""此次请求的用户消息对象,由前置处理器阶段设置"""
|
||||||
|
|
||||||
|
variables: typing.Optional[dict[str, typing.Any]] = None
|
||||||
|
"""变量,由前置处理器阶段设置。在prompt中嵌入或由 Runner 传递到 LLMOps 平台。"""
|
||||||
|
|
||||||
use_model: typing.Optional[entities.LLMModelInfo] = None
|
use_model: typing.Optional[entities.LLMModelInfo] = None
|
||||||
"""使用的模型,由前置处理器阶段设置"""
|
"""使用的模型,由前置处理器阶段设置"""
|
||||||
|
|
||||||
@@ -86,10 +89,31 @@ class Query(pydantic.BaseModel):
|
|||||||
|
|
||||||
# ======= 内部保留 =======
|
# ======= 内部保留 =======
|
||||||
current_stage: "pkg.pipeline.stagemgr.StageInstContainer" = None
|
current_stage: "pkg.pipeline.stagemgr.StageInstContainer" = None
|
||||||
|
"""当前所处阶段"""
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
arbitrary_types_allowed = True
|
arbitrary_types_allowed = True
|
||||||
|
|
||||||
|
# ========== 插件可调用的 API(请求 API) ==========
|
||||||
|
|
||||||
|
def set_variable(self, key: str, value: typing.Any):
|
||||||
|
"""设置变量"""
|
||||||
|
if self.variables is None:
|
||||||
|
self.variables = {}
|
||||||
|
self.variables[key] = value
|
||||||
|
|
||||||
|
def get_variable(self, key: str) -> typing.Any:
|
||||||
|
"""获取变量"""
|
||||||
|
if self.variables is None:
|
||||||
|
return None
|
||||||
|
return self.variables.get(key)
|
||||||
|
|
||||||
|
def get_variables(self) -> dict[str, typing.Any]:
|
||||||
|
"""获取所有变量"""
|
||||||
|
if self.variables is None:
|
||||||
|
return {}
|
||||||
|
return self.variables
|
||||||
|
|
||||||
|
|
||||||
class Conversation(pydantic.BaseModel):
|
class Conversation(pydantic.BaseModel):
|
||||||
"""对话,包含于 Session 中,一个 Session 可以有多个历史 Conversation,但只有一个当前使用的 Conversation"""
|
"""对话,包含于 Session 中,一个 Session 可以有多个历史 Conversation,但只有一个当前使用的 Conversation"""
|
||||||
|
|||||||
26
pkg/core/migrations/m035_wxoa_mode.py
Normal file
26
pkg/core/migrations/m035_wxoa_mode.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .. import migration
|
||||||
|
|
||||||
|
|
||||||
|
@migration.migration_class("wxoa-mode", 35)
|
||||||
|
class WxoaModeMigration(migration.Migration):
|
||||||
|
"""迁移"""
|
||||||
|
|
||||||
|
async def need_migrate(self) -> bool:
|
||||||
|
"""判断当前环境是否需要运行此迁移"""
|
||||||
|
|
||||||
|
for adapter in self.ap.platform_cfg.data['platform-adapters']:
|
||||||
|
if adapter['adapter'] == 'officialaccount':
|
||||||
|
if 'Mode' not in adapter:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行迁移"""
|
||||||
|
for adapter in self.ap.platform_cfg.data['platform-adapters']:
|
||||||
|
if adapter['adapter'] == 'officialaccount':
|
||||||
|
if 'Mode' not in adapter:
|
||||||
|
adapter['Mode'] = 'drop'
|
||||||
|
|
||||||
|
await self.ap.platform_cfg.dump_config()
|
||||||
26
pkg/core/migrations/m036_wxoa_loading_message.py
Normal file
26
pkg/core/migrations/m036_wxoa_loading_message.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .. import migration
|
||||||
|
|
||||||
|
|
||||||
|
@migration.migration_class("wxoa-loading-message", 36)
|
||||||
|
class WxoaLoadingMessageMigration(migration.Migration):
|
||||||
|
"""迁移"""
|
||||||
|
|
||||||
|
async def need_migrate(self) -> bool:
|
||||||
|
"""判断当前环境是否需要运行此迁移"""
|
||||||
|
|
||||||
|
for adapter in self.ap.platform_cfg.data['platform-adapters']:
|
||||||
|
if adapter['adapter'] == 'officialaccount':
|
||||||
|
if 'LoadingMessage' not in adapter:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行迁移"""
|
||||||
|
for adapter in self.ap.platform_cfg.data['platform-adapters']:
|
||||||
|
if adapter['adapter'] == 'officialaccount':
|
||||||
|
if 'LoadingMessage' not in adapter:
|
||||||
|
adapter['LoadingMessage'] = 'AI正在思考中,请发送任意内容获取回复。'
|
||||||
|
|
||||||
|
await self.ap.platform_cfg.dump_config()
|
||||||
20
pkg/core/migrations/m037_mcp_config.py
Normal file
20
pkg/core/migrations/m037_mcp_config.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .. import migration
|
||||||
|
|
||||||
|
|
||||||
|
@migration.migration_class("mcp-config", 37)
|
||||||
|
class MCPConfigMigration(migration.Migration):
|
||||||
|
"""迁移"""
|
||||||
|
|
||||||
|
async def need_migrate(self) -> bool:
|
||||||
|
"""判断当前环境是否需要运行此迁移"""
|
||||||
|
return 'mcp' not in self.ap.provider_cfg.data
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行迁移"""
|
||||||
|
self.ap.provider_cfg.data['mcp'] = {
|
||||||
|
"servers": []
|
||||||
|
}
|
||||||
|
|
||||||
|
await self.ap.provider_cfg.dump_config()
|
||||||
26
pkg/core/migrations/m038_tg_dingtalk_markdown.py
Normal file
26
pkg/core/migrations/m038_tg_dingtalk_markdown.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .. import migration
|
||||||
|
|
||||||
|
|
||||||
|
@migration.migration_class("tg-dingtalk-markdown", 38)
|
||||||
|
class TgDingtalkMarkdownMigration(migration.Migration):
|
||||||
|
"""迁移"""
|
||||||
|
|
||||||
|
async def need_migrate(self) -> bool:
|
||||||
|
"""判断当前环境是否需要运行此迁移"""
|
||||||
|
|
||||||
|
for adapter in self.ap.platform_cfg.data['platform-adapters']:
|
||||||
|
if adapter['adapter'] in ['dingtalk','telegram']:
|
||||||
|
if 'markdown_card' not in adapter:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行迁移"""
|
||||||
|
for adapter in self.ap.platform_cfg.data['platform-adapters']:
|
||||||
|
if adapter['adapter'] in ['dingtalk','telegram']:
|
||||||
|
if 'markdown_card' not in adapter:
|
||||||
|
adapter['markdown_card'] = False
|
||||||
|
await self.ap.platform_cfg.dump_config()
|
||||||
|
|
||||||
30
pkg/core/migrations/m039_modelscope_cfg_completion.py
Normal file
30
pkg/core/migrations/m039_modelscope_cfg_completion.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .. import migration
|
||||||
|
|
||||||
|
|
||||||
|
@migration.migration_class("modelscope-config-completion", 39)
|
||||||
|
class ModelScopeConfigCompletionMigration(migration.Migration):
|
||||||
|
"""ModelScope配置迁移
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def need_migrate(self) -> bool:
|
||||||
|
"""判断当前环境是否需要运行此迁移
|
||||||
|
"""
|
||||||
|
return 'modelscope-chat-completions' not in self.ap.provider_cfg.data['requester'] \
|
||||||
|
or 'modelscope' not in self.ap.provider_cfg.data['keys']
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行迁移
|
||||||
|
"""
|
||||||
|
if 'modelscope-chat-completions' not in self.ap.provider_cfg.data['requester']:
|
||||||
|
self.ap.provider_cfg.data['requester']['modelscope-chat-completions'] = {
|
||||||
|
'base-url': 'https://api-inference.modelscope.cn/v1',
|
||||||
|
'args': {},
|
||||||
|
'timeout': 120,
|
||||||
|
}
|
||||||
|
|
||||||
|
if 'modelscope' not in self.ap.provider_cfg.data['keys']:
|
||||||
|
self.ap.provider_cfg.data['keys']['modelscope'] = []
|
||||||
|
|
||||||
|
await self.ap.provider_cfg.dump_config()
|
||||||
30
pkg/core/migrations/m040_ppio_config.py
Normal file
30
pkg/core/migrations/m040_ppio_config.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .. import migration
|
||||||
|
|
||||||
|
|
||||||
|
@migration.migration_class("ppio-config", 40)
|
||||||
|
class PPIOConfigMigration(migration.Migration):
|
||||||
|
"""PPIO配置迁移
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def need_migrate(self) -> bool:
|
||||||
|
"""判断当前环境是否需要运行此迁移
|
||||||
|
"""
|
||||||
|
return 'ppio-chat-completions' not in self.ap.provider_cfg.data['requester'] \
|
||||||
|
or 'ppio' not in self.ap.provider_cfg.data['keys']
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""执行迁移
|
||||||
|
"""
|
||||||
|
if 'ppio-chat-completions' not in self.ap.provider_cfg.data['requester']:
|
||||||
|
self.ap.provider_cfg.data['requester']['ppio-chat-completions'] = {
|
||||||
|
'base-url': 'https://api.ppinfra.com/v3/openai',
|
||||||
|
'args': {},
|
||||||
|
'timeout': 120,
|
||||||
|
}
|
||||||
|
|
||||||
|
if 'ppio' not in self.ap.provider_cfg.data['keys']:
|
||||||
|
self.ap.provider_cfg.data['keys']['ppio'] = []
|
||||||
|
|
||||||
|
await self.ap.provider_cfg.dump_config()
|
||||||
@@ -11,7 +11,9 @@ from ..migrations import m015_gitee_ai_config, m016_dify_service_api, m017_dify_
|
|||||||
from ..migrations import m020_wecom_config, m021_lark_config, m022_lmstudio_config, m023_siliconflow_config, m024_discord_config, m025_gewechat_config
|
from ..migrations import m020_wecom_config, m021_lark_config, m022_lmstudio_config, m023_siliconflow_config, m024_discord_config, m025_gewechat_config
|
||||||
from ..migrations import m026_qqofficial_config, m027_wx_official_account_config, m028_aliyun_requester_config
|
from ..migrations import m026_qqofficial_config, m027_wx_official_account_config, m028_aliyun_requester_config
|
||||||
from ..migrations import m029_dashscope_app_api_config, m030_lark_config_cmpl, m031_dingtalk_config, m032_volcark_config
|
from ..migrations import m029_dashscope_app_api_config, m030_lark_config_cmpl, m031_dingtalk_config, m032_volcark_config
|
||||||
from ..migrations import m033_dify_thinking_config, m034_gewechat_file_url_config
|
from ..migrations import m033_dify_thinking_config, m034_gewechat_file_url_config, m035_wxoa_mode, m036_wxoa_loading_message
|
||||||
|
from ..migrations import m037_mcp_config, m038_tg_dingtalk_markdown, m039_modelscope_cfg_completion, m040_ppio_config
|
||||||
|
|
||||||
|
|
||||||
@stage.stage_class("MigrationStage")
|
@stage.stage_class("MigrationStage")
|
||||||
class MigrationStage(stage.BootingStage):
|
class MigrationStage(stage.BootingStage):
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
|
||||||
from .. import stage, entities, stagemgr
|
from .. import stage, entities, stagemgr
|
||||||
from ...core import entities as core_entities
|
from ...core import entities as core_entities
|
||||||
@@ -34,7 +35,7 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
|
|
||||||
conversation = await self.ap.sess_mgr.get_conversation(session)
|
conversation = await self.ap.sess_mgr.get_conversation(session)
|
||||||
|
|
||||||
# 从会话取出消息和情景预设到query
|
# 设置query
|
||||||
query.session = session
|
query.session = session
|
||||||
query.prompt = conversation.prompt.copy()
|
query.prompt = conversation.prompt.copy()
|
||||||
query.messages = conversation.messages.copy()
|
query.messages = conversation.messages.copy()
|
||||||
@@ -43,6 +44,11 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
|
|
||||||
query.use_funcs = conversation.use_funcs if query.use_model.tool_call_supported else None
|
query.use_funcs = conversation.use_funcs if query.use_model.tool_call_supported else None
|
||||||
|
|
||||||
|
query.variables = {
|
||||||
|
"session_id": f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
||||||
|
"conversation_id": conversation.uuid,
|
||||||
|
"msg_create_time": int(query.message_event.time) if query.message_event.time else int(datetime.datetime.now().timestamp()),
|
||||||
|
}
|
||||||
|
|
||||||
# 检查vision是否启用,没启用就删除所有图片
|
# 检查vision是否启用,没启用就删除所有图片
|
||||||
if not self.ap.provider_cfg.data['enable-vision'] or (self.ap.provider_cfg.data['runner'] == 'local-agent' and not query.use_model.vision_supported):
|
if not self.ap.provider_cfg.data['enable-vision'] or (self.ap.provider_cfg.data['runner'] == 'local-agent' and not query.use_model.vision_supported):
|
||||||
@@ -54,11 +60,14 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
|
|
||||||
content_list = []
|
content_list = []
|
||||||
|
|
||||||
|
plain_text = ""
|
||||||
|
|
||||||
for me in query.message_chain:
|
for me in query.message_chain:
|
||||||
if isinstance(me, platform_message.Plain):
|
if isinstance(me, platform_message.Plain):
|
||||||
content_list.append(
|
content_list.append(
|
||||||
llm_entities.ContentElement.from_text(me.text)
|
llm_entities.ContentElement.from_text(me.text)
|
||||||
)
|
)
|
||||||
|
plain_text += me.text
|
||||||
elif isinstance(me, platform_message.Image):
|
elif isinstance(me, platform_message.Image):
|
||||||
if self.ap.provider_cfg.data['enable-vision'] and (self.ap.provider_cfg.data['runner'] != 'local-agent' or query.use_model.vision_supported):
|
if self.ap.provider_cfg.data['enable-vision'] and (self.ap.provider_cfg.data['runner'] != 'local-agent' or query.use_model.vision_supported):
|
||||||
if me.base64 is not None:
|
if me.base64 is not None:
|
||||||
@@ -66,6 +75,8 @@ class PreProcessor(stage.PipelineStage):
|
|||||||
llm_entities.ContentElement.from_image_base64(me.base64)
|
llm_entities.ContentElement.from_image_base64(me.base64)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
query.variables['user_message_text'] = plain_text
|
||||||
|
|
||||||
query.user_message = llm_entities.Message(
|
query.user_message = llm_entities.Message(
|
||||||
role='user',
|
role='user',
|
||||||
content=content_list
|
content=content_list
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ class PlatformManager:
|
|||||||
if len(self.adapters) == 0:
|
if len(self.adapters) == 0:
|
||||||
self.ap.logger.warning('未运行平台适配器,请根据文档配置并启用平台适配器。')
|
self.ap.logger.warning('未运行平台适配器,请根据文档配置并启用平台适配器。')
|
||||||
|
|
||||||
async def write_back_config(self, adapter_name: str, adapter_inst: msadapter.MessagePlatformAdapter, config: dict):
|
def write_back_config(self, adapter_name: str, adapter_inst: msadapter.MessagePlatformAdapter, config: dict):
|
||||||
index = -2
|
index = -2
|
||||||
|
|
||||||
for i, adapter in enumerate(self.adapters):
|
for i, adapter in enumerate(self.adapters):
|
||||||
@@ -137,7 +137,7 @@ class PlatformManager:
|
|||||||
**config
|
**config
|
||||||
}
|
}
|
||||||
self.ap.platform_cfg.data['platform-adapters'][real_index] = new_cfg
|
self.ap.platform_cfg.data['platform-adapters'][real_index] = new_cfg
|
||||||
await self.ap.platform_cfg.dump_config()
|
self.ap.platform_cfg.dump_config_sync()
|
||||||
|
|
||||||
async def send(self, event: platform_events.MessageEvent, msg: platform_message.MessageChain, adapter: msadapter.MessagePlatformAdapter):
|
async def send(self, event: platform_events.MessageEvent, msg: platform_message.MessageChain, adapter: msadapter.MessagePlatformAdapter):
|
||||||
|
|
||||||
@@ -170,7 +170,8 @@ class PlatformManager:
|
|||||||
self.ap.logger.debug(f"Traceback: {traceback.format_exc()}")
|
self.ap.logger.debug(f"Traceback: {traceback.format_exc()}")
|
||||||
|
|
||||||
tasks.append(exception_wrapper(adapter))
|
tasks.append(exception_wrapper(adapter))
|
||||||
|
|
||||||
|
|
||||||
for task in tasks:
|
for task in tasks:
|
||||||
self.ap.task_mgr.create_task(
|
self.ap.task_mgr.create_task(
|
||||||
task,
|
task,
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ class AiocqhttpMessageConverter(adapter.MessageConverter):
|
|||||||
elif msg.path:
|
elif msg.path:
|
||||||
arg = msg.path
|
arg = msg.path
|
||||||
msg_list.append(aiocqhttp.MessageSegment.record(msg.path))
|
msg_list.append(aiocqhttp.MessageSegment.record(msg.path))
|
||||||
elif type(msg) is forward.Forward:
|
elif type(msg) is platform_message.Forward:
|
||||||
|
|
||||||
for node in msg.node_list:
|
for node in msg.node_list:
|
||||||
msg_list.extend((await AiocqhttpMessageConverter.yiri2target(node.message_chain))[0])
|
msg_list.extend((await AiocqhttpMessageConverter.yiri2target(node.message_chain))[0])
|
||||||
@@ -101,69 +101,8 @@ class AiocqhttpMessageConverter(adapter.MessageConverter):
|
|||||||
class AiocqhttpEventConverter(adapter.EventConverter):
|
class AiocqhttpEventConverter(adapter.EventConverter):
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def yiri2target(event: platform_events.Event, bot_account_id: int):
|
async def yiri2target(event: platform_events.MessageEvent, bot_account_id: int):
|
||||||
|
return event.source_platform_object
|
||||||
msg, msg_id, msg_time = await AiocqhttpMessageConverter.yiri2target(event.message_chain)
|
|
||||||
|
|
||||||
if type(event) is platform_events.GroupMessage:
|
|
||||||
role = "member"
|
|
||||||
|
|
||||||
if event.sender.permission == "ADMINISTRATOR":
|
|
||||||
role = "admin"
|
|
||||||
elif event.sender.permission == "OWNER":
|
|
||||||
role = "owner"
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
"post_type": "message",
|
|
||||||
"message_type": "group",
|
|
||||||
"time": int(msg_time.timestamp()),
|
|
||||||
"self_id": bot_account_id,
|
|
||||||
"sub_type": "normal",
|
|
||||||
"anonymous": None,
|
|
||||||
"font": 0,
|
|
||||||
"message": str(msg),
|
|
||||||
"raw_message": str(msg),
|
|
||||||
"sender": {
|
|
||||||
"age": 0,
|
|
||||||
"area": "",
|
|
||||||
"card": "",
|
|
||||||
"level": "",
|
|
||||||
"nickname": event.sender.member_name,
|
|
||||||
"role": role,
|
|
||||||
"sex": "unknown",
|
|
||||||
"title": "",
|
|
||||||
"user_id": event.sender.id,
|
|
||||||
},
|
|
||||||
"user_id": event.sender.id,
|
|
||||||
"message_id": msg_id,
|
|
||||||
"group_id": event.group.id,
|
|
||||||
"message_seq": 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
return aiocqhttp.Event.from_payload(payload)
|
|
||||||
elif type(event) is platform_events.FriendMessage:
|
|
||||||
|
|
||||||
payload = {
|
|
||||||
"post_type": "message",
|
|
||||||
"message_type": "private",
|
|
||||||
"time": int(msg_time.timestamp()),
|
|
||||||
"self_id": bot_account_id,
|
|
||||||
"sub_type": "friend",
|
|
||||||
"target_id": bot_account_id,
|
|
||||||
"message": str(msg),
|
|
||||||
"raw_message": str(msg),
|
|
||||||
"font": 0,
|
|
||||||
"sender": {
|
|
||||||
"age": 0,
|
|
||||||
"nickname": event.sender.nickname,
|
|
||||||
"sex": "unknown",
|
|
||||||
"user_id": event.sender.id,
|
|
||||||
},
|
|
||||||
"message_id": msg_id,
|
|
||||||
"user_id": event.sender.id,
|
|
||||||
}
|
|
||||||
|
|
||||||
return aiocqhttp.Event.from_payload(payload)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def target2yiri(event: aiocqhttp.Event):
|
async def target2yiri(event: aiocqhttp.Event):
|
||||||
@@ -196,6 +135,7 @@ class AiocqhttpEventConverter(adapter.EventConverter):
|
|||||||
),
|
),
|
||||||
message_chain=yiri_chain,
|
message_chain=yiri_chain,
|
||||||
time=event.time,
|
time=event.time,
|
||||||
|
source_platform_object=event
|
||||||
)
|
)
|
||||||
return converted_event
|
return converted_event
|
||||||
elif event.message_type == "private":
|
elif event.message_type == "private":
|
||||||
@@ -207,6 +147,7 @@ class AiocqhttpEventConverter(adapter.EventConverter):
|
|||||||
),
|
),
|
||||||
message_chain=yiri_chain,
|
message_chain=yiri_chain,
|
||||||
time=event.time,
|
time=event.time,
|
||||||
|
source_platform_object=event
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ class DingTalkEventConverter(adapter.EventConverter):
|
|||||||
remark=""
|
remark=""
|
||||||
),
|
),
|
||||||
message_chain = message_chain,
|
message_chain = message_chain,
|
||||||
time = datetime.datetime.now(),
|
time = event.incoming_message.create_at,
|
||||||
source_platform_object=event,
|
source_platform_object=event,
|
||||||
)
|
)
|
||||||
elif event.conversation == 'GroupMessage':
|
elif event.conversation == 'GroupMessage':
|
||||||
@@ -95,7 +95,7 @@ class DingTalkEventConverter(adapter.EventConverter):
|
|||||||
last_speak_timestamp=0,
|
last_speak_timestamp=0,
|
||||||
mute_time_remaining=0
|
mute_time_remaining=0
|
||||||
)
|
)
|
||||||
time = datetime.datetime.now(),
|
time = event.incoming_message.create_at
|
||||||
return platform_events.GroupMessage(
|
return platform_events.GroupMessage(
|
||||||
sender =sender,
|
sender =sender,
|
||||||
message_chain = message_chain,
|
message_chain = message_chain,
|
||||||
@@ -131,7 +131,8 @@ class DingTalkAdapter(adapter.MessagePlatformAdapter):
|
|||||||
client_id=config["client_id"],
|
client_id=config["client_id"],
|
||||||
client_secret=config["client_secret"],
|
client_secret=config["client_secret"],
|
||||||
robot_name = config["robot_name"],
|
robot_name = config["robot_name"],
|
||||||
robot_code=config["robot_code"]
|
robot_code=config["robot_code"],
|
||||||
|
markdown_card=config["markdown_card"]
|
||||||
)
|
)
|
||||||
|
|
||||||
async def reply_message(
|
async def reply_message(
|
||||||
@@ -152,7 +153,11 @@ class DingTalkAdapter(adapter.MessagePlatformAdapter):
|
|||||||
async def send_message(
|
async def send_message(
|
||||||
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
||||||
):
|
):
|
||||||
pass
|
content = await DingTalkMessageConverter.yiri2target(message)
|
||||||
|
if target_type == 'person':
|
||||||
|
await self.bot.send_proactive_message_to_one(target_id,content)
|
||||||
|
if target_type == 'group':
|
||||||
|
await self.bot.send_proactive_message_to_group(target_id,content)
|
||||||
|
|
||||||
def register_listener(
|
def register_listener(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ from ..types import message as platform_message
|
|||||||
from ..types import events as platform_events
|
from ..types import events as platform_events
|
||||||
from ..types import entities as platform_entities
|
from ..types import entities as platform_entities
|
||||||
from ...utils import image
|
from ...utils import image
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
|
||||||
|
|
||||||
class GewechatMessageConverter(adapter.MessageConverter):
|
class GewechatMessageConverter(adapter.MessageConverter):
|
||||||
@@ -46,6 +47,17 @@ class GewechatMessageConverter(adapter.MessageConverter):
|
|||||||
if not component.url:
|
if not component.url:
|
||||||
pass
|
pass
|
||||||
content_list.append({"type": "image", "image": component.url})
|
content_list.append({"type": "image", "image": component.url})
|
||||||
|
elif isinstance(component, platform_message.WeChatMiniPrograms):
|
||||||
|
content_list.append({"type": 'WeChatMiniPrograms', 'mini_app_id': component.mini_app_id, 'display_name': component.display_name,
|
||||||
|
'page_path': component.page_path, 'cover_img_url': component.image_url, 'title': component.title,
|
||||||
|
'user_name': component.user_name})
|
||||||
|
elif isinstance(component, platform_message.WeChatForwardMiniPrograms):
|
||||||
|
content_list.append({"type": 'WeChatForwardMiniPrograms', 'xml_data': component.xml_data, 'image_url': component.image_url})
|
||||||
|
elif isinstance(component, platform_message.WeChatEmoji):
|
||||||
|
content_list.append({'type': 'WeChatEmoji', 'emoji_md5': component.emoji_md5, 'emoji_size': component.emoji_size})
|
||||||
|
elif isinstance(component, platform_message.WeChatLink):
|
||||||
|
content_list.append({'type': 'WeChatLink', 'link_title': component.link_title, 'link_desc': component.link_desc,
|
||||||
|
'link_thumb_url': component.link_thumb_url, 'link_url': component.link_url})
|
||||||
|
|
||||||
|
|
||||||
elif isinstance(component, platform_message.Voice):
|
elif isinstance(component, platform_message.Voice):
|
||||||
@@ -62,20 +74,33 @@ class GewechatMessageConverter(adapter.MessageConverter):
|
|||||||
bot_account_id: str
|
bot_account_id: str
|
||||||
) -> platform_message.MessageChain:
|
) -> platform_message.MessageChain:
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if message["Data"]["MsgType"] == 1:
|
if message["Data"]["MsgType"] == 1:
|
||||||
# 检查消息开头,如果有 wxid_sbitaz0mt65n22:\n 则删掉
|
# 检查消息开头,如果有 wxid_sbitaz0mt65n22:\n 则删掉
|
||||||
regex = re.compile(r"^wxid_.*:")
|
regex = re.compile(r"^wxid_.*:")
|
||||||
|
# print(message)
|
||||||
|
|
||||||
line_split = message["Data"]["Content"]["string"].split("\n")
|
line_split = message["Data"]["Content"]["string"].split("\n")
|
||||||
|
|
||||||
if len(line_split) > 0 and regex.match(line_split[0]):
|
if len(line_split) > 0 and regex.match(line_split[0]):
|
||||||
message["Data"]["Content"]["string"] = "\n".join(line_split[1:])
|
message["Data"]["Content"]["string"] = "\n".join(line_split[1:])
|
||||||
|
|
||||||
at_string = f'@{bot_account_id}'
|
|
||||||
|
# 正则表达式模式,匹配'@'后跟任意数量的非空白字符
|
||||||
|
pattern = r'@\S+'
|
||||||
|
at_string = f"@{bot_account_id}"
|
||||||
content_list = []
|
content_list = []
|
||||||
if at_string in message["Data"]["Content"]["string"]:
|
if at_string in message["Data"]["Content"]["string"]:
|
||||||
content_list.append(platform_message.At(target=bot_account_id))
|
content_list.append(platform_message.At(target=bot_account_id))
|
||||||
content_list.append(platform_message.Plain(message["Data"]["Content"]["string"].replace(at_string, "", 1)))
|
content_list.append(platform_message.Plain(message["Data"]["Content"]["string"].replace(at_string, '', 1)))
|
||||||
|
# 更优雅的替换改名后@机器人,仅仅限于单独AT的情况
|
||||||
|
elif "PushContent" in message['Data'] and '在群聊中@了你' in message["Data"]["PushContent"]:
|
||||||
|
if '@所有人' in message["Data"]["Content"]["string"]: # at全员时候传入atll不当作at自己
|
||||||
|
content_list.append(platform_message.AtAll())
|
||||||
|
else:
|
||||||
|
content_list.append(platform_message.At(target=bot_account_id))
|
||||||
|
content_list.append(platform_message.Plain(re.sub(pattern, '', message["Data"]["Content"]["string"])))
|
||||||
else:
|
else:
|
||||||
content_list = [platform_message.Plain(message["Data"]["Content"]["string"])]
|
content_list = [platform_message.Plain(message["Data"]["Content"]["string"])]
|
||||||
|
|
||||||
@@ -118,17 +143,78 @@ class GewechatMessageConverter(adapter.MessageConverter):
|
|||||||
# 支持微信聊天记录的消息类型,将 XML 内容转换为 MessageChain 传递
|
# 支持微信聊天记录的消息类型,将 XML 内容转换为 MessageChain 传递
|
||||||
try:
|
try:
|
||||||
content = message["Data"]["Content"]["string"]
|
content = message["Data"]["Content"]["string"]
|
||||||
|
# 有三种可能的消息结构weid开头,私聊直接<?xml>和直接<msg>
|
||||||
|
if content.startswith('wxid'):
|
||||||
|
xml_list = content.split('\n')[2:]
|
||||||
|
xml_data = '\n'.join(xml_list)
|
||||||
|
elif content.startswith('<?xml'):
|
||||||
|
xml_list = content.split('\n')[1:]
|
||||||
|
xml_data = '\n'.join(xml_list)
|
||||||
|
else:
|
||||||
|
xml_data = content
|
||||||
|
|
||||||
try:
|
content_data = ET.fromstring(xml_data)
|
||||||
content_bytes = content.encode('utf-8')
|
# print(xml_data)
|
||||||
decoded_content = base64.b64decode(content_bytes)
|
# 拿到细分消息类型,按照gewe接口中描述
|
||||||
|
'''
|
||||||
|
小程序:33/36
|
||||||
|
引用消息:57
|
||||||
|
转账消息:2000
|
||||||
|
红包消息:2001
|
||||||
|
视频号消息:51
|
||||||
|
'''
|
||||||
|
appmsg_data = content_data.find('.//appmsg')
|
||||||
|
data_type = appmsg_data.find('.//type').text
|
||||||
|
if data_type == '57':
|
||||||
|
user_data = appmsg_data.find('.//title').text # 拿到用户消息
|
||||||
|
quote_data = appmsg_data.find('.//refermsg').find('.//content').text # 引用原文
|
||||||
|
sender_id = appmsg_data.find('.//refermsg').find('.//chatusr').text # 引用用户id
|
||||||
|
from_name = message['Data']['FromUserName']['string']
|
||||||
|
message_list =[]
|
||||||
|
if message['Wxid'] == sender_id and from_name.endswith('@chatroom'): # 因为引用机制暂时无法响应用户,所以当引用用户是机器人是构建一个at激活机器人
|
||||||
|
message_list.append(platform_message.At(target=bot_account_id))
|
||||||
|
message_list.append(platform_message.Quote(
|
||||||
|
sender_id=sender_id,
|
||||||
|
origin=platform_message.MessageChain(
|
||||||
|
[platform_message.Plain(quote_data)]
|
||||||
|
)))
|
||||||
|
message_list.append(platform_message.Plain(user_data))
|
||||||
|
return platform_message.MessageChain(message_list)
|
||||||
|
elif data_type == '51':
|
||||||
return platform_message.MessageChain(
|
return platform_message.MessageChain(
|
||||||
[platform_message.Unknown(content=decoded_content)]
|
[platform_message.Plain(text=f'[视频号消息]')]
|
||||||
)
|
)
|
||||||
except Exception as e:
|
# print(content_data)
|
||||||
|
elif data_type == '2000':
|
||||||
return platform_message.MessageChain(
|
return platform_message.MessageChain(
|
||||||
[platform_message.Plain(text=content)]
|
[platform_message.Plain(text=f'[转账消息]')]
|
||||||
)
|
)
|
||||||
|
elif data_type == '2001':
|
||||||
|
return platform_message.MessageChain(
|
||||||
|
[platform_message.Plain(text=f'[红包消息]')]
|
||||||
|
)
|
||||||
|
elif data_type == '5':
|
||||||
|
return platform_message.MessageChain(
|
||||||
|
[platform_message.Plain(text=f'[公众号消息]')]
|
||||||
|
)
|
||||||
|
elif data_type == '33' or data_type == '36':
|
||||||
|
return platform_message.MessageChain(
|
||||||
|
[platform_message.Plain(text=f'[小程序消息]')]
|
||||||
|
)
|
||||||
|
# print(data_type.text)
|
||||||
|
else:
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
content_bytes = content.encode('utf-8')
|
||||||
|
decoded_content = base64.b64decode(content_bytes)
|
||||||
|
return platform_message.MessageChain(
|
||||||
|
[platform_message.Unknown(content=decoded_content)]
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
return platform_message.MessageChain(
|
||||||
|
[platform_message.Plain(text=content)]
|
||||||
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"Error processing type 49 message: {str(e)}")
|
print(f"Error processing type 49 message: {str(e)}")
|
||||||
return platform_message.MessageChain(
|
return platform_message.MessageChain(
|
||||||
@@ -152,6 +238,14 @@ class GewechatEventConverter(adapter.EventConverter):
|
|||||||
event: dict,
|
event: dict,
|
||||||
bot_account_id: str
|
bot_account_id: str
|
||||||
) -> platform_events.MessageEvent:
|
) -> platform_events.MessageEvent:
|
||||||
|
# print(event)
|
||||||
|
# 排除自己发消息回调回答问题
|
||||||
|
if event['Wxid'] == event['Data']['FromUserName']['string']:
|
||||||
|
return None
|
||||||
|
# 排除公众号以及微信团队消息
|
||||||
|
if event['Data']['FromUserName']['string'].startswith('gh_')\
|
||||||
|
or event['Data']['FromUserName']['string'].startswith('weixin'):
|
||||||
|
return None
|
||||||
message_chain = await self.message_converter.target2yiri(copy.deepcopy(event), bot_account_id)
|
message_chain = await self.message_converter.target2yiri(copy.deepcopy(event), bot_account_id)
|
||||||
|
|
||||||
if not message_chain:
|
if not message_chain:
|
||||||
@@ -227,6 +321,16 @@ class GeWeChatAdapter(adapter.MessagePlatformAdapter):
|
|||||||
async def gewechat_callback():
|
async def gewechat_callback():
|
||||||
data = await quart.request.json
|
data = await quart.request.json
|
||||||
# print(json.dumps(data, indent=4, ensure_ascii=False))
|
# print(json.dumps(data, indent=4, ensure_ascii=False))
|
||||||
|
self.ap.logger.debug(
|
||||||
|
f"Gewechat callback event: {data}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if 'data' in data:
|
||||||
|
data['Data'] = data['data']
|
||||||
|
if 'type_name' in data:
|
||||||
|
data['TypeName'] = data['type_name']
|
||||||
|
# print(json.dumps(data, indent=4, ensure_ascii=False))
|
||||||
|
|
||||||
|
|
||||||
if 'testMsg' in data:
|
if 'testMsg' in data:
|
||||||
return 'ok'
|
return 'ok'
|
||||||
@@ -248,17 +352,42 @@ class GeWeChatAdapter(adapter.MessagePlatformAdapter):
|
|||||||
target_id: str,
|
target_id: str,
|
||||||
message: platform_message.MessageChain
|
message: platform_message.MessageChain
|
||||||
):
|
):
|
||||||
geweap_msg = await GewechatMessageConverter.yiri2target(message)
|
geweap_msg = await self.message_converter.yiri2target(message)
|
||||||
# 此处加上群消息at处理
|
# 此处加上群消息at处理
|
||||||
# ats = [item["target"] for item in geweap_msg if item["type"] == "at"]
|
ats = [item["target"] for item in geweap_msg if item["type"] == "at"]
|
||||||
|
|
||||||
|
|
||||||
for msg in geweap_msg:
|
for msg in geweap_msg:
|
||||||
|
# at主动发送消息
|
||||||
if msg['type'] == 'text':
|
if msg['type'] == 'text':
|
||||||
await self.bot.post_text(app_id=self.config['app_id'], to_wxid=target_id, content=msg['content'])
|
if ats:
|
||||||
|
member_info = self.bot.get_chatroom_member_detail(
|
||||||
|
self.config["app_id"],
|
||||||
|
target_id,
|
||||||
|
ats[::-1]
|
||||||
|
)["data"]
|
||||||
|
|
||||||
|
for member in member_info:
|
||||||
|
msg['content'] = f'@{member["nickName"]} {msg["content"]}'
|
||||||
|
self.bot.post_text(app_id=self.config['app_id'], to_wxid=target_id, content=msg['content'],
|
||||||
|
ats=",".join(ats))
|
||||||
|
|
||||||
elif msg['type'] == 'image':
|
elif msg['type'] == 'image':
|
||||||
|
|
||||||
await self.bot.post_image(app_id=self.config['app_id'], to_wxid=target_id, img_url=msg["image"])
|
self.bot.post_image(app_id=self.config['app_id'], to_wxid=target_id, img_url=msg["image"])
|
||||||
|
elif msg['type'] == 'WeChatMiniPrograms':
|
||||||
|
self.bot.post_mini_app(app_id=self.config['app_id'], to_wxid=target_id, mini_app_id=msg['mini_app_id']
|
||||||
|
, display_name=msg['display_name'], page_path=msg['page_path']
|
||||||
|
, cover_img_url=msg['cover_img_url'], title=msg['title'], user_name=msg['user_name'])
|
||||||
|
elif msg['type'] == 'WeChatForwardMiniPrograms':
|
||||||
|
self.bot.forward_mini_app(app_id=self.config['app_id'], to_wxid=target_id, xml=msg['xml_data'], cover_img_url=msg['image_url'])
|
||||||
|
elif msg['type'] == 'WeChatEmoji':
|
||||||
|
self.bot.post_emoji(app_id=self.config['app_id'], to_wxid=target_id,
|
||||||
|
emoji_md5=msg['emoji_md5'], emoji_size=msg['emoji_size'])
|
||||||
|
elif msg['type'] == 'WeChatLink':
|
||||||
|
self.bot.post_link(app_id=self.config['app_id'], to_wxid=target_id
|
||||||
|
,title=msg['link_title'], desc=msg['link_desc']
|
||||||
|
, link_url=msg['link_url'], thumb_url=msg['link_thumb_url'])
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -271,6 +400,7 @@ class GeWeChatAdapter(adapter.MessagePlatformAdapter):
|
|||||||
content_list = await self.message_converter.yiri2target(message)
|
content_list = await self.message_converter.yiri2target(message)
|
||||||
|
|
||||||
ats = [item["target"] for item in content_list if item["type"] == "at"]
|
ats = [item["target"] for item in content_list if item["type"] == "at"]
|
||||||
|
target_id = message_source.source_platform_object["Data"]["FromUserName"]["string"]
|
||||||
|
|
||||||
for msg in content_list:
|
for msg in content_list:
|
||||||
if msg["type"] == "text":
|
if msg["type"] == "text":
|
||||||
@@ -289,8 +419,24 @@ class GeWeChatAdapter(adapter.MessagePlatformAdapter):
|
|||||||
app_id=self.config["app_id"],
|
app_id=self.config["app_id"],
|
||||||
to_wxid=message_source.source_platform_object["Data"]["FromUserName"]["string"],
|
to_wxid=message_source.source_platform_object["Data"]["FromUserName"]["string"],
|
||||||
content=msg["content"],
|
content=msg["content"],
|
||||||
ats=','.join(ats)
|
ats=",".join(ats)
|
||||||
)
|
)
|
||||||
|
elif msg['type'] == 'image':
|
||||||
|
|
||||||
|
self.bot.post_image(app_id=self.config['app_id'], to_wxid=target_id, img_url=msg["image"])
|
||||||
|
elif msg['type'] == 'WeChatMiniPrograms':
|
||||||
|
self.bot.post_mini_app(app_id=self.config['app_id'], to_wxid=target_id, mini_app_id=msg['mini_app_id']
|
||||||
|
, display_name=msg['display_name'], page_path=msg['page_path']
|
||||||
|
, cover_img_url=msg['cover_img_url'], title=msg['title'], user_name=msg['user_name'])
|
||||||
|
elif msg['type'] == 'WeChatForwardMiniPrograms':
|
||||||
|
self.bot.forward_mini_app(app_id=self.config['app_id'], to_wxid=target_id, xml=msg['xml_data'], cover_img_url=msg['image_url'])
|
||||||
|
elif msg['type'] == 'WeChatEmoji':
|
||||||
|
self.bot.post_emoji(app_id=self.config['app_id'], to_wxid=target_id,
|
||||||
|
emoji_md5=msg['emoji_md5'], emoji_size=msg['emoji_size'])
|
||||||
|
elif msg['type'] == 'WeChatLink':
|
||||||
|
self.bot.post_link(app_id=self.config['app_id'], to_wxid=target_id
|
||||||
|
, title=msg['link_title'], desc=msg['link_desc']
|
||||||
|
, link_url=msg['link_url'], thumb_url=msg['link_thumb_url'])
|
||||||
|
|
||||||
async def is_muted(self, group_id: int) -> bool:
|
async def is_muted(self, group_id: int) -> bool:
|
||||||
pass
|
pass
|
||||||
@@ -326,26 +472,28 @@ class GeWeChatAdapter(adapter.MessagePlatformAdapter):
|
|||||||
self.config["token"]
|
self.config["token"]
|
||||||
)
|
)
|
||||||
|
|
||||||
app_id, error_msg = self.bot.login(self.config["app_id"])
|
def gewechat_login_process():
|
||||||
if error_msg:
|
|
||||||
raise Exception(f"Gewechat 登录失败: {error_msg}")
|
|
||||||
|
|
||||||
self.config["app_id"] = app_id
|
app_id, error_msg = self.bot.login(self.config["app_id"])
|
||||||
|
if error_msg:
|
||||||
|
raise Exception(f"Gewechat 登录失败: {error_msg}")
|
||||||
|
|
||||||
self.ap.logger.info(f"Gewechat 登录成功,app_id: {app_id}")
|
self.config["app_id"] = app_id
|
||||||
|
|
||||||
await self.ap.platform_mgr.write_back_config('gewechat', self, self.config)
|
self.ap.logger.info(f"Gewechat 登录成功,app_id: {app_id}")
|
||||||
|
|
||||||
# 获取 nickname
|
self.ap.platform_mgr.write_back_config('gewechat', self, self.config)
|
||||||
profile = self.bot.get_profile(self.config["app_id"])
|
|
||||||
self.bot_account_id = profile["data"]["nickName"]
|
# 获取 nickname
|
||||||
|
profile = self.bot.get_profile(self.config["app_id"])
|
||||||
|
self.bot_account_id = profile["data"]["nickName"]
|
||||||
|
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
def thread_set_callback():
|
|
||||||
time.sleep(3)
|
|
||||||
ret = self.bot.set_callback(self.config["token"], self.config["callback_url"])
|
ret = self.bot.set_callback(self.config["token"], self.config["callback_url"])
|
||||||
print('设置 Gewechat 回调:', ret)
|
print('设置 Gewechat 回调:', ret)
|
||||||
|
|
||||||
threading.Thread(target=thread_set_callback).start()
|
threading.Thread(target=gewechat_login_process).start()
|
||||||
|
|
||||||
async def shutdown_trigger_placeholder():
|
async def shutdown_trigger_placeholder():
|
||||||
while True:
|
while True:
|
||||||
|
|||||||
@@ -328,6 +328,10 @@ class LarkAdapter(adapter.MessagePlatformAdapter):
|
|||||||
try:
|
try:
|
||||||
data = await quart.request.json
|
data = await quart.request.json
|
||||||
|
|
||||||
|
self.ap.logger.debug(
|
||||||
|
f"Lark callback event: {data}"
|
||||||
|
)
|
||||||
|
|
||||||
if 'encrypt' in data:
|
if 'encrypt' in data:
|
||||||
cipher = AESCipher(self.config['encrypt-key'])
|
cipher = AESCipher(self.config['encrypt-key'])
|
||||||
data = cipher.decrypt_string(data['encrypt'])
|
data = cipher.decrypt_string(data['encrypt'])
|
||||||
@@ -339,7 +343,6 @@ class LarkAdapter(adapter.MessagePlatformAdapter):
|
|||||||
type = context.header.event_type
|
type = context.header.event_type
|
||||||
|
|
||||||
if 'url_verification' == type:
|
if 'url_verification' == type:
|
||||||
print(data.get("challenge"))
|
|
||||||
# todo 验证verification token
|
# todo 验证verification token
|
||||||
return {
|
return {
|
||||||
"challenge": data.get("challenge")
|
"challenge": data.get("challenge")
|
||||||
|
|||||||
@@ -2,21 +2,19 @@ from __future__ import annotations
|
|||||||
import typing
|
import typing
|
||||||
import asyncio
|
import asyncio
|
||||||
import traceback
|
import traceback
|
||||||
import time
|
|
||||||
import datetime
|
import datetime
|
||||||
from pkg.core import app
|
from pkg.core import app
|
||||||
from pkg.platform.adapter import MessagePlatformAdapter
|
from pkg.platform.adapter import MessagePlatformAdapter
|
||||||
from pkg.platform.types import events as platform_events, message as platform_message
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
|
from collections import deque
|
||||||
import aiocqhttp
|
|
||||||
import aiohttp
|
|
||||||
from libs.official_account_api.oaevent import OAEvent
|
from libs.official_account_api.oaevent import OAEvent
|
||||||
from pkg.platform.adapter import MessagePlatformAdapter
|
from pkg.platform.adapter import MessagePlatformAdapter
|
||||||
from pkg.platform.types import events as platform_events, message as platform_message
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
from libs.official_account_api.api import OAClient
|
from libs.official_account_api.api import OAClient
|
||||||
|
from libs.official_account_api.api import OAClientForLongerResponse
|
||||||
from pkg.core import app
|
from pkg.core import app
|
||||||
from .. import adapter
|
from .. import adapter
|
||||||
from ...pipeline.longtext.strategies import forward
|
|
||||||
from ...core import app
|
from ...core import app
|
||||||
from ..types import message as platform_message
|
from ..types import message as platform_message
|
||||||
from ..types import events as platform_events
|
from ..types import events as platform_events
|
||||||
@@ -24,9 +22,6 @@ from ..types import entities as platform_entities
|
|||||||
from ...command.errors import ParamNotEnoughError
|
from ...command.errors import ParamNotEnoughError
|
||||||
|
|
||||||
|
|
||||||
# 生成的ai回答
|
|
||||||
generated_content = {}
|
|
||||||
|
|
||||||
class OAMessageConverter(adapter.MessageConverter):
|
class OAMessageConverter(adapter.MessageConverter):
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def yiri2target(message_chain: platform_message.MessageChain):
|
async def yiri2target(message_chain: platform_message.MessageChain):
|
||||||
@@ -70,7 +65,7 @@ class OAEventConverter(adapter.EventConverter):
|
|||||||
|
|
||||||
class OfficialAccountAdapter(adapter.MessagePlatformAdapter):
|
class OfficialAccountAdapter(adapter.MessagePlatformAdapter):
|
||||||
|
|
||||||
bot : OAClient
|
bot : OAClient | OAClientForLongerResponse
|
||||||
ap : app.Application
|
ap : app.Application
|
||||||
bot_account_id: str
|
bot_account_id: str
|
||||||
message_converter: OAMessageConverter = OAMessageConverter()
|
message_converter: OAMessageConverter = OAMessageConverter()
|
||||||
@@ -88,27 +83,44 @@ class OfficialAccountAdapter(adapter.MessagePlatformAdapter):
|
|||||||
"EncodingAESKey",
|
"EncodingAESKey",
|
||||||
"AppSecret",
|
"AppSecret",
|
||||||
"AppID",
|
"AppID",
|
||||||
|
"Mode",
|
||||||
]
|
]
|
||||||
missing_keys = [key for key in required_keys if key not in config]
|
missing_keys = [key for key in required_keys if key not in config]
|
||||||
if missing_keys:
|
if missing_keys:
|
||||||
raise ParamNotEnoughError("企业微信缺少相关配置项,请查看文档或联系管理员")
|
raise ParamNotEnoughError("微信公众号缺少相关配置项,请查看文档或联系管理员")
|
||||||
|
|
||||||
self.bot = OAClient(
|
|
||||||
token=config['token'],
|
if self.config['Mode'] == "drop":
|
||||||
EncodingAESKey=config['EncodingAESKey'],
|
self.bot = OAClient(
|
||||||
Appsecret=config['AppSecret'],
|
token=config['token'],
|
||||||
AppID=config['AppID'],
|
EncodingAESKey=config['EncodingAESKey'],
|
||||||
)
|
Appsecret=config['AppSecret'],
|
||||||
|
AppID=config['AppID'],
|
||||||
|
)
|
||||||
|
elif self.config['Mode'] == "passive":
|
||||||
|
self.bot = OAClientForLongerResponse(
|
||||||
|
token=config['token'],
|
||||||
|
EncodingAESKey=config['EncodingAESKey'],
|
||||||
|
Appsecret=config['AppSecret'],
|
||||||
|
AppID=config['AppID'],
|
||||||
|
LoadingMessage=config['LoadingMessage']
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise KeyError("请设置微信公众号通信模式")
|
||||||
|
|
||||||
|
|
||||||
async def reply_message(self, message_source: platform_events.FriendMessage, message: platform_message.MessageChain, quote_origin: bool = False):
|
async def reply_message(self, message_source: platform_events.FriendMessage, message: platform_message.MessageChain, quote_origin: bool = False):
|
||||||
global generated_content
|
|
||||||
|
|
||||||
content = await OAMessageConverter.yiri2target(
|
content = await OAMessageConverter.yiri2target(
|
||||||
message
|
message
|
||||||
)
|
)
|
||||||
|
if type(self.bot) == OAClient:
|
||||||
|
await self.bot.set_message(message_source.message_chain.message_id,content)
|
||||||
|
if type(self.bot) == OAClientForLongerResponse:
|
||||||
|
from_user = message_source.sender.id
|
||||||
|
await self.bot.set_message(from_user,message_source.message_chain.message_id,content)
|
||||||
|
|
||||||
generated_content[message_source.message_chain.message_id] = content
|
|
||||||
|
|
||||||
async def send_message(
|
async def send_message(
|
||||||
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -2,15 +2,14 @@ from __future__ import annotations
|
|||||||
import typing
|
import typing
|
||||||
import asyncio
|
import asyncio
|
||||||
import traceback
|
import traceback
|
||||||
import time
|
|
||||||
import datetime
|
import datetime
|
||||||
import aiocqhttp
|
|
||||||
import aiohttp
|
|
||||||
from pkg.platform.adapter import MessagePlatformAdapter
|
from pkg.platform.adapter import MessagePlatformAdapter
|
||||||
from pkg.platform.types import events as platform_events, message as platform_message
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
from pkg.core import app
|
from pkg.core import app
|
||||||
from .. import adapter
|
from .. import adapter
|
||||||
from ...pipeline.longtext.strategies import forward
|
|
||||||
from ...core import app
|
from ...core import app
|
||||||
from ..types import message as platform_message
|
from ..types import message as platform_message
|
||||||
from ..types import events as platform_events
|
from ..types import events as platform_events
|
||||||
@@ -74,7 +73,11 @@ class QQOfficialEventConverter(adapter.EventConverter):
|
|||||||
remark = "",
|
remark = "",
|
||||||
)
|
)
|
||||||
return platform_events.FriendMessage(
|
return platform_events.FriendMessage(
|
||||||
sender = friend,message_chain = yiri_chain,time = event.timestamp,
|
sender = friend,message_chain = yiri_chain,time = int(
|
||||||
|
datetime.datetime.strptime(
|
||||||
|
event.timestamp, "%Y-%m-%dT%H:%M:%S%z"
|
||||||
|
).timestamp()
|
||||||
|
),
|
||||||
source_platform_object=event
|
source_platform_object=event
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -96,7 +99,7 @@ class QQOfficialEventConverter(adapter.EventConverter):
|
|||||||
member_name= event.t,
|
member_name= event.t,
|
||||||
permission= 'MEMBER',
|
permission= 'MEMBER',
|
||||||
group = platform_entities.Group(
|
group = platform_entities.Group(
|
||||||
id = 0,
|
id = event.group_openid,
|
||||||
name = 'MEMBER',
|
name = 'MEMBER',
|
||||||
permission= platform_entities.Permission.Member
|
permission= platform_entities.Permission.Member
|
||||||
),
|
),
|
||||||
@@ -105,7 +108,11 @@ class QQOfficialEventConverter(adapter.EventConverter):
|
|||||||
last_speak_timestamp=0,
|
last_speak_timestamp=0,
|
||||||
mute_time_remaining=0
|
mute_time_remaining=0
|
||||||
)
|
)
|
||||||
time = event.timestamp
|
time = int(
|
||||||
|
datetime.datetime.strptime(
|
||||||
|
event.timestamp, "%Y-%m-%dT%H:%M:%S%z"
|
||||||
|
).timestamp()
|
||||||
|
)
|
||||||
return platform_events.GroupMessage(
|
return platform_events.GroupMessage(
|
||||||
sender = sender,
|
sender = sender,
|
||||||
message_chain=yiri_chain,
|
message_chain=yiri_chain,
|
||||||
@@ -119,7 +126,7 @@ class QQOfficialEventConverter(adapter.EventConverter):
|
|||||||
member_name=event.t,
|
member_name=event.t,
|
||||||
permission= 'MEMBER',
|
permission= 'MEMBER',
|
||||||
group = platform_entities.Group(
|
group = platform_entities.Group(
|
||||||
id = 0,
|
id = event.channel_id,
|
||||||
name = 'MEMBER',
|
name = 'MEMBER',
|
||||||
permission=platform_entities.Permission.Member
|
permission=platform_entities.Permission.Member
|
||||||
),
|
),
|
||||||
@@ -128,7 +135,11 @@ class QQOfficialEventConverter(adapter.EventConverter):
|
|||||||
last_speak_timestamp=0,
|
last_speak_timestamp=0,
|
||||||
mute_time_remaining=0
|
mute_time_remaining=0
|
||||||
)
|
)
|
||||||
time = event.timestamp,
|
time = int(
|
||||||
|
datetime.datetime.strptime(
|
||||||
|
event.timestamp, "%Y-%m-%dT%H:%M:%S%z"
|
||||||
|
).timestamp()
|
||||||
|
)
|
||||||
return platform_events.GroupMessage(
|
return platform_events.GroupMessage(
|
||||||
sender =sender,
|
sender =sender,
|
||||||
message_chain = yiri_chain,
|
message_chain = yiri_chain,
|
||||||
|
|||||||
204
pkg/platform/sources/slack.py
Normal file
204
pkg/platform/sources/slack.py
Normal file
@@ -0,0 +1,204 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import typing
|
||||||
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
from libs.slack_api.api import SlackClient
|
||||||
|
from pkg.platform.adapter import MessagePlatformAdapter
|
||||||
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
|
from libs.slack_api.slackevent import SlackEvent
|
||||||
|
from pkg.core import app
|
||||||
|
from .. import adapter
|
||||||
|
from ...core import app
|
||||||
|
from ..types import message as platform_message
|
||||||
|
from ..types import events as platform_events
|
||||||
|
from ..types import entities as platform_entities
|
||||||
|
from ...command.errors import ParamNotEnoughError
|
||||||
|
from ...utils import image
|
||||||
|
|
||||||
|
class SlackMessageConverter(adapter.MessageConverter):
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(message_chain:platform_message.MessageChain):
|
||||||
|
content_list = []
|
||||||
|
for msg in message_chain:
|
||||||
|
if type(msg) is platform_message.Plain:
|
||||||
|
content_list.append({
|
||||||
|
"content":msg.text,
|
||||||
|
})
|
||||||
|
|
||||||
|
return content_list
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri(message:str,message_id:str,pic_url:str,bot:SlackClient):
|
||||||
|
yiri_msg_list = []
|
||||||
|
yiri_msg_list.append(
|
||||||
|
platform_message.Source(id=message_id,time=datetime.datetime.now())
|
||||||
|
)
|
||||||
|
if pic_url is not None:
|
||||||
|
base64_url = await image.get_slack_image_to_base64(pic_url=pic_url,bot_token=bot.bot_token)
|
||||||
|
yiri_msg_list.append(
|
||||||
|
platform_message.Image(base64=base64_url)
|
||||||
|
)
|
||||||
|
|
||||||
|
yiri_msg_list.append(platform_message.Plain(text=message))
|
||||||
|
chain = platform_message.MessageChain(yiri_msg_list)
|
||||||
|
return chain
|
||||||
|
|
||||||
|
|
||||||
|
class SlackEventConverter(adapter.EventConverter):
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(event:platform_events.MessageEvent) -> SlackEvent:
|
||||||
|
return event.source_platform_object
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri(event:SlackEvent,bot:SlackClient):
|
||||||
|
yiri_chain = await SlackMessageConverter.target2yiri(
|
||||||
|
message=event.text,message_id=event.message_id,pic_url=event.pic_url,bot=bot
|
||||||
|
)
|
||||||
|
|
||||||
|
if event.type == 'channel':
|
||||||
|
yiri_chain.insert(0, platform_message.At(target="SlackBot"))
|
||||||
|
|
||||||
|
sender = platform_entities.GroupMember(
|
||||||
|
id = event.user_id,
|
||||||
|
member_name= str(event.sender_name),
|
||||||
|
permission= 'MEMBER',
|
||||||
|
group = platform_entities.Group(
|
||||||
|
id = event.channel_id,
|
||||||
|
name = 'MEMBER',
|
||||||
|
permission= platform_entities.Permission.Member
|
||||||
|
),
|
||||||
|
special_title='',
|
||||||
|
join_timestamp=0,
|
||||||
|
last_speak_timestamp=0,
|
||||||
|
mute_time_remaining=0
|
||||||
|
)
|
||||||
|
time = int(datetime.datetime.utcnow().timestamp())
|
||||||
|
return platform_events.GroupMessage(
|
||||||
|
sender = sender,
|
||||||
|
message_chain=yiri_chain,
|
||||||
|
time = time,
|
||||||
|
source_platform_object=event
|
||||||
|
)
|
||||||
|
|
||||||
|
if event.type == 'im':
|
||||||
|
return platform_events.FriendMessage(
|
||||||
|
sender=platform_entities.Friend(
|
||||||
|
id=event.user_id,
|
||||||
|
nickname = event.sender_name,
|
||||||
|
remark=""
|
||||||
|
),
|
||||||
|
message_chain = yiri_chain,
|
||||||
|
time = float(datetime.datetime.now().timestamp()),
|
||||||
|
source_platform_object=event,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class SlackAdapter(adapter.MessagePlatformAdapter):
|
||||||
|
bot: SlackClient
|
||||||
|
ap: app.Application
|
||||||
|
bot_account_id: str
|
||||||
|
message_converter: SlackMessageConverter = SlackMessageConverter()
|
||||||
|
event_converter: SlackEventConverter = SlackEventConverter()
|
||||||
|
config: dict
|
||||||
|
|
||||||
|
def __init__(self,config:dict,ap:app.Application):
|
||||||
|
self.config = config
|
||||||
|
self.ap = ap
|
||||||
|
required_keys = [
|
||||||
|
"bot_token",
|
||||||
|
"signing_secret",
|
||||||
|
]
|
||||||
|
missing_keys = [key for key in required_keys if key not in config]
|
||||||
|
if missing_keys:
|
||||||
|
raise ParamNotEnoughError("Slack机器人缺少相关配置项,请查看文档或联系管理员")
|
||||||
|
|
||||||
|
self.bot = SlackClient(
|
||||||
|
bot_token=self.config["bot_token"],
|
||||||
|
signing_secret=self.config["signing_secret"]
|
||||||
|
)
|
||||||
|
|
||||||
|
async def reply_message(
|
||||||
|
self,
|
||||||
|
message_source: platform_events.MessageEvent,
|
||||||
|
message: platform_message.MessageChain,
|
||||||
|
quote_origin: bool = False,
|
||||||
|
):
|
||||||
|
slack_event = await SlackEventConverter.yiri2target(
|
||||||
|
message_source
|
||||||
|
)
|
||||||
|
|
||||||
|
content_list = await SlackMessageConverter.yiri2target(message)
|
||||||
|
|
||||||
|
for content in content_list:
|
||||||
|
if slack_event.type == 'channel':
|
||||||
|
await self.bot.send_message_to_channel(
|
||||||
|
content['content'],slack_event.channel_id
|
||||||
|
)
|
||||||
|
if slack_event.type == 'im':
|
||||||
|
await self.bot.send_message_to_one(
|
||||||
|
content['content'],slack_event.user_id
|
||||||
|
)
|
||||||
|
|
||||||
|
async def send_message(self, target_type: str, target_id: str, message: platform_message.MessageChain):
|
||||||
|
content_list = await SlackMessageConverter.yiri2target(message)
|
||||||
|
for content in content_list:
|
||||||
|
if target_type == 'person':
|
||||||
|
await self.bot.send_message_to_one(content['content'],target_id)
|
||||||
|
if target_type == 'group':
|
||||||
|
await self.bot.send_message_to_channel(content['content'],target_id)
|
||||||
|
|
||||||
|
|
||||||
|
def register_listener(
|
||||||
|
self,
|
||||||
|
event_type: typing.Type[platform_events.Event],
|
||||||
|
callback: typing.Callable[
|
||||||
|
[platform_events.Event, adapter.MessagePlatformAdapter], None
|
||||||
|
],
|
||||||
|
):
|
||||||
|
async def on_message(event:SlackEvent):
|
||||||
|
self.bot_account_id = 'SlackBot'
|
||||||
|
try:
|
||||||
|
return await callback(
|
||||||
|
await self.event_converter.target2yiri(event,self.bot),self
|
||||||
|
)
|
||||||
|
except:
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
if event_type == platform_events.FriendMessage:
|
||||||
|
self.bot.on_message("im")(on_message)
|
||||||
|
elif event_type == platform_events.GroupMessage:
|
||||||
|
self.bot.on_message("channel")(on_message)
|
||||||
|
|
||||||
|
|
||||||
|
async def run_async(self):
|
||||||
|
async def shutdown_trigger_placeholder():
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
await self.bot.run_task(
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=self.config["port"],
|
||||||
|
shutdown_trigger=shutdown_trigger_placeholder,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def kill(self) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def unregister_listener(
|
||||||
|
self,
|
||||||
|
event_type: type,
|
||||||
|
callback: typing.Callable[[platform_events.Event, MessagePlatformAdapter], None],
|
||||||
|
):
|
||||||
|
return super().unregister_listener(event_type, callback)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
37
pkg/platform/sources/slack.yaml
Normal file
37
pkg/platform/sources/slack.yaml
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: MessagePlatformAdapter
|
||||||
|
metadata:
|
||||||
|
name: slack
|
||||||
|
label:
|
||||||
|
en_US: Slack API
|
||||||
|
zh_CN: Slack API
|
||||||
|
description:
|
||||||
|
en_US: Slack API
|
||||||
|
zh_CN: Slack API
|
||||||
|
spec:
|
||||||
|
config:
|
||||||
|
- name: bot_token
|
||||||
|
label:
|
||||||
|
en_US: Bot Token
|
||||||
|
zh_CN: 机器人令牌
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: signing_secret
|
||||||
|
label:
|
||||||
|
en_US: signing_secret
|
||||||
|
zh_CN: 密钥
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: port
|
||||||
|
label:
|
||||||
|
en_US: Port
|
||||||
|
zh_CN: 监听端口
|
||||||
|
type: int
|
||||||
|
required: true
|
||||||
|
default: 2288
|
||||||
|
execution:
|
||||||
|
python:
|
||||||
|
path: ./slack.py
|
||||||
|
attr: SlackAdapter
|
||||||
@@ -4,7 +4,7 @@ import telegram
|
|||||||
import telegram.ext
|
import telegram.ext
|
||||||
from telegram import Update
|
from telegram import Update
|
||||||
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
|
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
|
||||||
|
import telegramify_markdown
|
||||||
import typing
|
import typing
|
||||||
import asyncio
|
import asyncio
|
||||||
import traceback
|
import traceback
|
||||||
@@ -86,9 +86,10 @@ class TelegramMessageConverter(adapter.MessageConverter):
|
|||||||
if message.text:
|
if message.text:
|
||||||
message_text = message.text
|
message_text = message.text
|
||||||
message_components.extend(parse_message_text(message_text))
|
message_components.extend(parse_message_text(message_text))
|
||||||
|
|
||||||
if message.photo:
|
if message.photo:
|
||||||
message_components.extend(parse_message_text(message.caption))
|
if message.caption:
|
||||||
|
message_components.extend(parse_message_text(message.caption))
|
||||||
|
|
||||||
file = await message.photo[-1].get_file()
|
file = await message.photo[-1].get_file()
|
||||||
|
|
||||||
@@ -126,7 +127,7 @@ class TelegramEventConverter(adapter.EventConverter):
|
|||||||
time=event.message.date.timestamp(),
|
time=event.message.date.timestamp(),
|
||||||
source_platform_object=event
|
source_platform_object=event
|
||||||
)
|
)
|
||||||
elif event.effective_chat.type == 'group':
|
elif event.effective_chat.type == 'group' or 'supergroup' :
|
||||||
return platform_events.GroupMessage(
|
return platform_events.GroupMessage(
|
||||||
sender=platform_entities.GroupMember(
|
sender=platform_entities.GroupMember(
|
||||||
id=event.effective_chat.id,
|
id=event.effective_chat.id,
|
||||||
@@ -201,16 +202,23 @@ class TelegramAdapter(adapter.MessagePlatformAdapter):
|
|||||||
|
|
||||||
for component in components:
|
for component in components:
|
||||||
if component['type'] == 'text':
|
if component['type'] == 'text':
|
||||||
|
if self.config['markdown_card'] is True:
|
||||||
|
content = telegramify_markdown.markdownify(
|
||||||
|
content= component['text'],
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
content = component['text']
|
||||||
args = {
|
args = {
|
||||||
"chat_id": message_source.source_platform_object.effective_chat.id,
|
"chat_id": message_source.source_platform_object.effective_chat.id,
|
||||||
"text": component['text'],
|
"text": content,
|
||||||
}
|
}
|
||||||
|
if self.config['markdown_card'] is True:
|
||||||
|
args["parse_mode"] = "MarkdownV2"
|
||||||
|
if quote_origin:
|
||||||
|
args['reply_to_message_id'] = message_source.source_platform_object.message.id
|
||||||
|
|
||||||
if quote_origin:
|
await self.bot.send_message(**args)
|
||||||
args['reply_to_message_id'] = message_source.source_platform_object.message.id
|
|
||||||
|
|
||||||
await self.bot.send_message(**args)
|
|
||||||
|
|
||||||
async def is_muted(self, group_id: int) -> bool:
|
async def is_muted(self, group_id: int) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -2,18 +2,15 @@ from __future__ import annotations
|
|||||||
import typing
|
import typing
|
||||||
import asyncio
|
import asyncio
|
||||||
import traceback
|
import traceback
|
||||||
import time
|
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
import aiocqhttp
|
|
||||||
import aiohttp
|
|
||||||
from libs.wecom_api.api import WecomClient
|
from libs.wecom_api.api import WecomClient
|
||||||
from pkg.platform.adapter import MessagePlatformAdapter
|
from pkg.platform.adapter import MessagePlatformAdapter
|
||||||
from pkg.platform.types import events as platform_events, message as platform_message
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
from libs.wecom_api.wecomevent import WecomEvent
|
from libs.wecom_api.wecomevent import WecomEvent
|
||||||
from pkg.core import app
|
from pkg.core import app
|
||||||
from .. import adapter
|
from .. import adapter
|
||||||
from ...pipeline.longtext.strategies import forward
|
|
||||||
from ...core import app
|
from ...core import app
|
||||||
from ..types import message as platform_message
|
from ..types import message as platform_message
|
||||||
from ..types import events as platform_events
|
from ..types import events as platform_events
|
||||||
@@ -200,7 +197,19 @@ class WecomAdapter(adapter.MessagePlatformAdapter):
|
|||||||
async def send_message(
|
async def send_message(
|
||||||
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
||||||
):
|
):
|
||||||
pass
|
"""企业微信目前只有发送给个人的方法,
|
||||||
|
构造target_id的方式为前半部分为账户id,后半部分为agent_id,中间使用“|”符号隔开。
|
||||||
|
"""
|
||||||
|
content_list = await WecomMessageConverter.yiri2target(message, self.bot)
|
||||||
|
parts = target_id.split("|")
|
||||||
|
user_id = parts[0]
|
||||||
|
agent_id = int(parts[1])
|
||||||
|
if target_type == 'person':
|
||||||
|
for content in content_list:
|
||||||
|
if content["type"] == "text":
|
||||||
|
await self.bot.send_private_msg(user_id,agent_id,content["content"])
|
||||||
|
if content["type"] == "image":
|
||||||
|
await self.bot.send_image(user_id,agent_id,content["media"])
|
||||||
|
|
||||||
def register_listener(
|
def register_listener(
|
||||||
self,
|
self,
|
||||||
|
|||||||
223
pkg/platform/sources/wecomcs.py
Normal file
223
pkg/platform/sources/wecomcs.py
Normal file
@@ -0,0 +1,223 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
import typing
|
||||||
|
import asyncio
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
from libs.wecom_customer_service_api.api import WecomCSClient
|
||||||
|
from pkg.platform.adapter import MessagePlatformAdapter
|
||||||
|
from pkg.platform.types import events as platform_events, message as platform_message
|
||||||
|
from libs.wecom_customer_service_api.wecomcsevent import WecomCSEvent
|
||||||
|
from pkg.core import app
|
||||||
|
from .. import adapter
|
||||||
|
from ...core import app
|
||||||
|
from ..types import message as platform_message
|
||||||
|
from ..types import events as platform_events
|
||||||
|
from ..types import entities as platform_entities
|
||||||
|
from ...command.errors import ParamNotEnoughError
|
||||||
|
from ...utils import image
|
||||||
|
|
||||||
|
class WecomMessageConverter(adapter.MessageConverter):
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(
|
||||||
|
message_chain: platform_message.MessageChain, bot: WecomCSClient
|
||||||
|
):
|
||||||
|
content_list = []
|
||||||
|
|
||||||
|
for msg in message_chain:
|
||||||
|
if type(msg) is platform_message.Plain:
|
||||||
|
content_list.append({
|
||||||
|
"type": "text",
|
||||||
|
"content": msg.text,
|
||||||
|
})
|
||||||
|
elif type(msg) is platform_message.Image:
|
||||||
|
content_list.append({
|
||||||
|
"type": "image",
|
||||||
|
"media_id": await bot.get_media_id(msg),
|
||||||
|
})
|
||||||
|
elif type(msg) is platform_message.Forward:
|
||||||
|
for node in msg.node_list:
|
||||||
|
content_list.extend((await WecomMessageConverter.yiri2target(node.message_chain, bot)))
|
||||||
|
else:
|
||||||
|
content_list.append({
|
||||||
|
"type": "text",
|
||||||
|
"content": str(msg),
|
||||||
|
})
|
||||||
|
|
||||||
|
return content_list
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri(message: str, message_id: int = -1):
|
||||||
|
yiri_msg_list = []
|
||||||
|
yiri_msg_list.append(
|
||||||
|
platform_message.Source(id=message_id, time=datetime.datetime.now())
|
||||||
|
)
|
||||||
|
|
||||||
|
yiri_msg_list.append(platform_message.Plain(text=message))
|
||||||
|
chain = platform_message.MessageChain(yiri_msg_list)
|
||||||
|
|
||||||
|
return chain
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri_image(picurl: str, message_id: int = -1):
|
||||||
|
yiri_msg_list = []
|
||||||
|
yiri_msg_list.append(
|
||||||
|
platform_message.Source(id=message_id, time=datetime.datetime.now())
|
||||||
|
)
|
||||||
|
yiri_msg_list.append(platform_message.Image(base64=picurl))
|
||||||
|
chain = platform_message.MessageChain(yiri_msg_list)
|
||||||
|
|
||||||
|
return chain
|
||||||
|
|
||||||
|
|
||||||
|
class WecomEventConverter:
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def yiri2target(
|
||||||
|
event: platform_events.Event, bot_account_id: int, bot: WecomCSClient
|
||||||
|
) -> WecomCSEvent:
|
||||||
|
# only for extracting user information
|
||||||
|
|
||||||
|
if type(event) is platform_events.GroupMessage:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if type(event) is platform_events.FriendMessage:
|
||||||
|
return event.source_platform_object
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def target2yiri(event: WecomCSEvent):
|
||||||
|
"""
|
||||||
|
将 WecomEvent 转换为平台的 FriendMessage 对象。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
event (WecomEvent): 企业微信客服事件。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
platform_events.FriendMessage: 转换后的 FriendMessage 对象。
|
||||||
|
"""
|
||||||
|
# 转换消息链
|
||||||
|
if event.type == "text":
|
||||||
|
yiri_chain = await WecomMessageConverter.target2yiri(
|
||||||
|
event.message, event.message_id
|
||||||
|
)
|
||||||
|
friend = platform_entities.Friend(
|
||||||
|
id=f"u{event.user_id}",
|
||||||
|
nickname=str(event.user_id),
|
||||||
|
remark="",
|
||||||
|
)
|
||||||
|
|
||||||
|
return platform_events.FriendMessage(
|
||||||
|
sender=friend, message_chain=yiri_chain, time=event.timestamp, source_platform_object=event
|
||||||
|
)
|
||||||
|
elif event.type == "image":
|
||||||
|
friend = platform_entities.Friend(
|
||||||
|
id=f"u{event.user_id}",
|
||||||
|
nickname=str(event.user_id),
|
||||||
|
remark="",
|
||||||
|
)
|
||||||
|
|
||||||
|
yiri_chain = await WecomMessageConverter.target2yiri_image(
|
||||||
|
picurl=event.picurl, message_id=event.message_id
|
||||||
|
)
|
||||||
|
|
||||||
|
return platform_events.FriendMessage(
|
||||||
|
sender=friend, message_chain=yiri_chain, time=event.timestamp, source_platform_object=event
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class WecomCSAdapter(adapter.MessagePlatformAdapter):
|
||||||
|
|
||||||
|
bot: WecomCSClient
|
||||||
|
ap: app.Application
|
||||||
|
bot_account_id: str
|
||||||
|
message_converter: WecomMessageConverter = WecomMessageConverter()
|
||||||
|
event_converter: WecomEventConverter = WecomEventConverter()
|
||||||
|
config: dict
|
||||||
|
|
||||||
|
def __init__(self, config: dict, ap: app.Application):
|
||||||
|
self.config = config
|
||||||
|
|
||||||
|
self.ap = ap
|
||||||
|
|
||||||
|
required_keys = [
|
||||||
|
"corpid",
|
||||||
|
"secret",
|
||||||
|
"token",
|
||||||
|
"EncodingAESKey",
|
||||||
|
]
|
||||||
|
missing_keys = [key for key in required_keys if key not in config]
|
||||||
|
if missing_keys:
|
||||||
|
raise ParamNotEnoughError("企业微信客服缺少相关配置项,请查看文档或联系管理员")
|
||||||
|
|
||||||
|
self.bot = WecomCSClient(
|
||||||
|
corpid=config["corpid"],
|
||||||
|
secret=config["secret"],
|
||||||
|
token=config["token"],
|
||||||
|
EncodingAESKey=config["EncodingAESKey"],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def reply_message(
|
||||||
|
self,
|
||||||
|
message_source: platform_events.MessageEvent,
|
||||||
|
message: platform_message.MessageChain,
|
||||||
|
quote_origin: bool = False,
|
||||||
|
):
|
||||||
|
|
||||||
|
Wecom_event = await WecomEventConverter.yiri2target(
|
||||||
|
message_source, self.bot_account_id, self.bot
|
||||||
|
)
|
||||||
|
content_list = await WecomMessageConverter.yiri2target(message, self.bot)
|
||||||
|
|
||||||
|
for content in content_list:
|
||||||
|
if content["type"] == "text":
|
||||||
|
await self.bot.send_text_msg(open_kfid=Wecom_event.receiver_id,external_userid=Wecom_event.user_id,msgid=Wecom_event.message_id,content=content["content"])
|
||||||
|
|
||||||
|
async def send_message(
|
||||||
|
self, target_type: str, target_id: str, message: platform_message.MessageChain
|
||||||
|
):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def register_listener(
|
||||||
|
self,
|
||||||
|
event_type: typing.Type[platform_events.Event],
|
||||||
|
callback: typing.Callable[
|
||||||
|
[platform_events.Event, adapter.MessagePlatformAdapter], None
|
||||||
|
],
|
||||||
|
):
|
||||||
|
async def on_message(event: WecomCSEvent):
|
||||||
|
self.bot_account_id = event.receiver_id
|
||||||
|
try:
|
||||||
|
return await callback(
|
||||||
|
await self.event_converter.target2yiri(event), self
|
||||||
|
)
|
||||||
|
except:
|
||||||
|
traceback.print_exc()
|
||||||
|
|
||||||
|
if event_type == platform_events.FriendMessage:
|
||||||
|
self.bot.on_message("text")(on_message)
|
||||||
|
self.bot.on_message("image")(on_message)
|
||||||
|
elif event_type == platform_events.GroupMessage:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def run_async(self):
|
||||||
|
async def shutdown_trigger_placeholder():
|
||||||
|
while True:
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
|
||||||
|
await self.bot.run_task(
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=self.config["port"],
|
||||||
|
shutdown_trigger=shutdown_trigger_placeholder,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def kill(self) -> bool:
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def unregister_listener(
|
||||||
|
self,
|
||||||
|
event_type: type,
|
||||||
|
callback: typing.Callable[[platform_events.Event, MessagePlatformAdapter], None],
|
||||||
|
):
|
||||||
|
return super().unregister_listener(event_type, callback)
|
||||||
51
pkg/platform/sources/wecomcs.yaml
Normal file
51
pkg/platform/sources/wecomcs.yaml
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: MessagePlatformAdapter
|
||||||
|
metadata:
|
||||||
|
name: wecomcs
|
||||||
|
label:
|
||||||
|
en_US: WeComCustomerService
|
||||||
|
zh_CN: 企业微信客服
|
||||||
|
description:
|
||||||
|
en_US: WeComCSAdapter
|
||||||
|
zh_CN: 企业微信客服适配器
|
||||||
|
spec:
|
||||||
|
config:
|
||||||
|
- name: port
|
||||||
|
label:
|
||||||
|
en_US: Port
|
||||||
|
zh_CN: 监听端口
|
||||||
|
type: int
|
||||||
|
required: true
|
||||||
|
default: 2289
|
||||||
|
- name: corpid
|
||||||
|
label:
|
||||||
|
en_US: Corpid
|
||||||
|
zh_CN: 企业ID
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: secret
|
||||||
|
label:
|
||||||
|
en_US: Secret
|
||||||
|
zh_CN: 密钥
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: token
|
||||||
|
label:
|
||||||
|
en_US: Token
|
||||||
|
zh_CN: 令牌
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
- name: EncodingAESKey
|
||||||
|
label:
|
||||||
|
en_US: EncodingAESKey
|
||||||
|
zh_CN: 消息加解密密钥
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: ""
|
||||||
|
execution:
|
||||||
|
python:
|
||||||
|
path: ./wecomcs.py
|
||||||
|
attr: WecomCSAdapter
|
||||||
@@ -57,6 +57,9 @@ class MessageEvent(Event):
|
|||||||
message_chain: platform_message.MessageChain
|
message_chain: platform_message.MessageChain
|
||||||
"""消息内容。"""
|
"""消息内容。"""
|
||||||
|
|
||||||
|
time: float | None = None
|
||||||
|
"""消息发送时间戳。"""
|
||||||
|
|
||||||
source_platform_object: typing.Optional[typing.Any] = None
|
source_platform_object: typing.Optional[typing.Any] = None
|
||||||
"""原消息平台对象。
|
"""原消息平台对象。
|
||||||
供消息平台适配器开发者使用,如果回复用户时需要使用原消息事件对象的信息,
|
供消息平台适配器开发者使用,如果回复用户时需要使用原消息事件对象的信息,
|
||||||
|
|||||||
@@ -807,6 +807,56 @@ class File(MessageComponent):
|
|||||||
"""文件名称。"""
|
"""文件名称。"""
|
||||||
size: int
|
size: int
|
||||||
"""文件大小。"""
|
"""文件大小。"""
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return f'[文件]{self.name}'
|
return f'[文件]{self.name}'
|
||||||
|
|
||||||
|
# ================ 个人微信专用组件 ================
|
||||||
|
|
||||||
|
class WeChatMiniPrograms(MessageComponent):
|
||||||
|
"""小程序。个人微信专用组件。"""
|
||||||
|
type: str = 'WeChatMiniPrograms'
|
||||||
|
"""小程序id"""
|
||||||
|
mini_app_id: str
|
||||||
|
"""小程序归属用户id"""
|
||||||
|
user_name: str
|
||||||
|
"""小程序名称"""
|
||||||
|
display_name: typing.Optional[str] = ''
|
||||||
|
"""打开地址"""
|
||||||
|
page_path: typing.Optional[str] = ''
|
||||||
|
"""小程序标题"""
|
||||||
|
title: typing.Optional[str] = ''
|
||||||
|
"""首页图片"""
|
||||||
|
image_url: typing.Optional[str] = ''
|
||||||
|
|
||||||
|
|
||||||
|
class WeChatForwardMiniPrograms(MessageComponent):
|
||||||
|
"""转发小程序。个人微信专用组件。"""
|
||||||
|
type: str = 'WeChatForwardMiniPrograms'
|
||||||
|
"""xml数据"""
|
||||||
|
xml_data: str
|
||||||
|
"""首页图片"""
|
||||||
|
image_url: typing.Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class WeChatEmoji(MessageComponent):
|
||||||
|
"""emoji表情。个人微信专用组件。"""
|
||||||
|
type: str = 'WeChatEmoji'
|
||||||
|
"""emojimd5"""
|
||||||
|
emoji_md5: str
|
||||||
|
"""emoji大小"""
|
||||||
|
emoji_size: int
|
||||||
|
|
||||||
|
|
||||||
|
class WeChatLink(MessageComponent):
|
||||||
|
"""发送链接。个人微信专用组件。"""
|
||||||
|
type: str = 'WeChatLink'
|
||||||
|
"""标题"""
|
||||||
|
link_title: str = ''
|
||||||
|
"""链接描述"""
|
||||||
|
link_desc: str = ''
|
||||||
|
"""链接地址"""
|
||||||
|
link_url: str = ''
|
||||||
|
"""链接略缩图"""
|
||||||
|
link_thumb_url: str = ''
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import re
|
|||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import zipfile
|
import zipfile
|
||||||
|
import ssl
|
||||||
|
import certifi
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
import aiofiles
|
import aiofiles
|
||||||
@@ -21,44 +23,39 @@ class GitHubRepoInstaller(installer.PluginInstaller):
|
|||||||
|
|
||||||
def get_github_plugin_repo_label(self, repo_url: str) -> list[str]:
|
def get_github_plugin_repo_label(self, repo_url: str) -> list[str]:
|
||||||
"""获取username, repo"""
|
"""获取username, repo"""
|
||||||
|
|
||||||
# 提取 username/repo , 正则表达式
|
|
||||||
repo = re.findall(
|
repo = re.findall(
|
||||||
r"(?:https?://github\.com/|git@github\.com:)([^/]+/[^/]+?)(?:\.git|/|$)",
|
r"(?:https?://github\.com/|git@github\.com:)([^/]+/[^/]+?)(?:\.git|/|$)",
|
||||||
repo_url,
|
repo_url,
|
||||||
)
|
)
|
||||||
|
if len(repo) > 0:
|
||||||
if len(repo) > 0: # github
|
|
||||||
return repo[0].split("/")
|
return repo[0].split("/")
|
||||||
else:
|
else:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def download_plugin_source_code(self, repo_url: str, target_path: str, task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder()) -> str:
|
async def download_plugin_source_code(self, repo_url: str, target_path: str, task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder()) -> str:
|
||||||
"""下载插件源码(全异步)"""
|
"""下载插件源码(全异步)"""
|
||||||
|
|
||||||
# 提取 username/repo , 正则表达式
|
|
||||||
repo = self.get_github_plugin_repo_label(repo_url)
|
repo = self.get_github_plugin_repo_label(repo_url)
|
||||||
|
|
||||||
target_path += repo[1]
|
|
||||||
|
|
||||||
if repo is None:
|
if repo is None:
|
||||||
raise errors.PluginInstallerError('仅支持GitHub仓库地址')
|
raise errors.PluginInstallerError('仅支持GitHub仓库地址')
|
||||||
|
|
||||||
|
target_path += repo[1]
|
||||||
self.ap.logger.debug("正在下载源码...")
|
self.ap.logger.debug("正在下载源码...")
|
||||||
task_context.trace("下载源码...", "download-plugin-source-code")
|
task_context.trace("下载源码...", "download-plugin-source-code")
|
||||||
|
|
||||||
zipball_url = f"https://api.github.com/repos/{'/'.join(repo)}/zipball/HEAD"
|
zipball_url = f"https://api.github.com/repos/{'/'.join(repo)}/zipball/HEAD"
|
||||||
|
|
||||||
zip_resp: bytes = None
|
zip_resp: bytes = None
|
||||||
|
|
||||||
|
# 创建自定义SSL上下文,使用certifi提供的根证书
|
||||||
|
ssl_context = ssl.create_default_context(cafile=certifi.where())
|
||||||
|
|
||||||
async with aiohttp.ClientSession(trust_env=True) as session:
|
async with aiohttp.ClientSession(trust_env=True) as session:
|
||||||
async with session.get(
|
async with session.get(
|
||||||
url=zipball_url,
|
url=zipball_url,
|
||||||
timeout=aiohttp.ClientTimeout(total=300)
|
timeout=aiohttp.ClientTimeout(total=300),
|
||||||
|
ssl=ssl_context # 使用自定义SSL上下文来验证证书
|
||||||
) as resp:
|
) as resp:
|
||||||
if resp.status != 200:
|
if resp.status != 200:
|
||||||
raise errors.PluginInstallerError(f"下载源码失败: {resp.text}")
|
raise errors.PluginInstallerError(f"下载源码失败: {await resp.text()}")
|
||||||
|
|
||||||
zip_resp = await resp.read()
|
zip_resp = await resp.read()
|
||||||
|
|
||||||
if await aiofiles_os.path.exists("temp/" + target_path):
|
if await aiofiles_os.path.exists("temp/" + target_path):
|
||||||
@@ -80,15 +77,11 @@ class GitHubRepoInstaller(installer.PluginInstaller):
|
|||||||
await aiofiles_os.remove("temp/" + target_path + "/source.zip")
|
await aiofiles_os.remove("temp/" + target_path + "/source.zip")
|
||||||
|
|
||||||
import glob
|
import glob
|
||||||
|
|
||||||
unzip_dir = glob.glob("temp/" + target_path + "/*")[0]
|
unzip_dir = glob.glob("temp/" + target_path + "/*")[0]
|
||||||
|
|
||||||
await aioshutil.copytree(unzip_dir, target_path + "/")
|
await aioshutil.copytree(unzip_dir, target_path + "/")
|
||||||
|
|
||||||
await aioshutil.rmtree(unzip_dir)
|
await aioshutil.rmtree(unzip_dir)
|
||||||
|
|
||||||
self.ap.logger.debug("源码下载完成。")
|
self.ap.logger.debug("源码下载完成。")
|
||||||
|
|
||||||
return repo[1]
|
return repo[1]
|
||||||
|
|
||||||
async def install_requirements(self, path: str):
|
async def install_requirements(self, path: str):
|
||||||
@@ -100,20 +93,14 @@ class GitHubRepoInstaller(installer.PluginInstaller):
|
|||||||
plugin_source: str,
|
plugin_source: str,
|
||||||
task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder(),
|
task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder(),
|
||||||
):
|
):
|
||||||
"""安装插件
|
"""安装插件"""
|
||||||
"""
|
|
||||||
task_context.trace("下载插件源码...", "install-plugin")
|
task_context.trace("下载插件源码...", "install-plugin")
|
||||||
|
|
||||||
repo_label = await self.download_plugin_source_code(plugin_source, "plugins/", task_context)
|
repo_label = await self.download_plugin_source_code(plugin_source, "plugins/", task_context)
|
||||||
|
|
||||||
task_context.trace("安装插件依赖...", "install-plugin")
|
task_context.trace("安装插件依赖...", "install-plugin")
|
||||||
|
|
||||||
await self.install_requirements("plugins/" + repo_label)
|
await self.install_requirements("plugins/" + repo_label)
|
||||||
|
|
||||||
task_context.trace("完成.", "install-plugin")
|
task_context.trace("完成.", "install-plugin")
|
||||||
|
|
||||||
await self.ap.plugin_mgr.setting.record_installed_plugin_source(
|
await self.ap.plugin_mgr.setting.record_installed_plugin_source(
|
||||||
"plugins/"+repo_label+'/', plugin_source
|
"plugins/" + repo_label + '/', plugin_source
|
||||||
)
|
)
|
||||||
|
|
||||||
async def uninstall_plugin(
|
async def uninstall_plugin(
|
||||||
@@ -121,10 +108,8 @@ class GitHubRepoInstaller(installer.PluginInstaller):
|
|||||||
plugin_name: str,
|
plugin_name: str,
|
||||||
task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder(),
|
task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder(),
|
||||||
):
|
):
|
||||||
"""卸载插件
|
"""卸载插件"""
|
||||||
"""
|
|
||||||
plugin_container = self.ap.plugin_mgr.get_plugin_by_name(plugin_name)
|
plugin_container = self.ap.plugin_mgr.get_plugin_by_name(plugin_name)
|
||||||
|
|
||||||
if plugin_container is None:
|
if plugin_container is None:
|
||||||
raise errors.PluginInstallerError('插件不存在或未成功加载')
|
raise errors.PluginInstallerError('插件不存在或未成功加载')
|
||||||
else:
|
else:
|
||||||
@@ -135,24 +120,18 @@ class GitHubRepoInstaller(installer.PluginInstaller):
|
|||||||
async def update_plugin(
|
async def update_plugin(
|
||||||
self,
|
self,
|
||||||
plugin_name: str,
|
plugin_name: str,
|
||||||
plugin_source: str=None,
|
plugin_source: str = None,
|
||||||
task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder(),
|
task_context: taskmgr.TaskContext = taskmgr.TaskContext.placeholder(),
|
||||||
):
|
):
|
||||||
"""更新插件
|
"""更新插件"""
|
||||||
"""
|
|
||||||
task_context.trace("更新插件...", "update-plugin")
|
task_context.trace("更新插件...", "update-plugin")
|
||||||
|
|
||||||
plugin_container = self.ap.plugin_mgr.get_plugin_by_name(plugin_name)
|
plugin_container = self.ap.plugin_mgr.get_plugin_by_name(plugin_name)
|
||||||
|
|
||||||
if plugin_container is None:
|
if plugin_container is None:
|
||||||
raise errors.PluginInstallerError('插件不存在或未成功加载')
|
raise errors.PluginInstallerError('插件不存在或未成功加载')
|
||||||
else:
|
else:
|
||||||
if plugin_container.plugin_source:
|
if plugin_container.plugin_source:
|
||||||
plugin_source = plugin_container.plugin_source
|
plugin_source = plugin_container.plugin_source
|
||||||
|
|
||||||
task_context.trace("转交安装任务.", "update-plugin")
|
task_context.trace("转交安装任务.", "update-plugin")
|
||||||
|
|
||||||
await self.install_plugin(plugin_source, task_context)
|
await self.install_plugin(plugin_source, task_context)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise errors.PluginInstallerError('插件无源码信息,无法更新')
|
raise errors.PluginInstallerError('插件无源码信息,无法更新')
|
||||||
@@ -6,7 +6,7 @@ from . import entities, requester
|
|||||||
from ...core import app
|
from ...core import app
|
||||||
from ...discover import engine
|
from ...discover import engine
|
||||||
from . import token
|
from . import token
|
||||||
from .requesters import bailianchatcmpl, chatcmpl, anthropicmsgs, moonshotchatcmpl, deepseekchatcmpl, ollamachat, giteeaichatcmpl, volcarkchatcmpl, xaichatcmpl, zhipuaichatcmpl, lmstudiochatcmpl, siliconflowchatcmpl, volcarkchatcmpl
|
from .requesters import bailianchatcmpl, chatcmpl, anthropicmsgs, moonshotchatcmpl, deepseekchatcmpl, ollamachat, giteeaichatcmpl, volcarkchatcmpl, xaichatcmpl, zhipuaichatcmpl, lmstudiochatcmpl, siliconflowchatcmpl, volcarkchatcmpl, modelscopechatcmpl
|
||||||
|
|
||||||
FETCH_MODEL_LIST_URL = "https://api.qchatgpt.rockchin.top/api/v2/fetch/model_list"
|
FETCH_MODEL_LIST_URL = "https://api.qchatgpt.rockchin.top/api/v2/fetch/model_list"
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import typing
|
|||||||
import json
|
import json
|
||||||
import traceback
|
import traceback
|
||||||
import base64
|
import base64
|
||||||
|
import platform
|
||||||
|
import socket
|
||||||
|
|
||||||
import anthropic
|
import anthropic
|
||||||
import httpx
|
import httpx
|
||||||
@@ -23,9 +25,15 @@ class AnthropicMessages(requester.LLMAPIRequester):
|
|||||||
client: anthropic.AsyncAnthropic
|
client: anthropic.AsyncAnthropic
|
||||||
|
|
||||||
async def initialize(self):
|
async def initialize(self):
|
||||||
|
# 兼容 Windows 缺失 TCP_KEEPINTVL 和 TCP_KEEPCNT 的问题
|
||||||
|
if platform.system() == "Windows":
|
||||||
|
if not hasattr(socket, "TCP_KEEPINTVL"):
|
||||||
|
socket.TCP_KEEPINTVL = 0
|
||||||
|
if not hasattr(socket, "TCP_KEEPCNT"):
|
||||||
|
socket.TCP_KEEPCNT = 0
|
||||||
|
|
||||||
httpx_client = anthropic._base_client.AsyncHttpxClientWrapper(
|
httpx_client = anthropic._base_client.AsyncHttpxClientWrapper(
|
||||||
base_url=self.ap.provider_cfg.data['requester']['anthropic-messages']['base-url'],
|
base_url=self.ap.provider_cfg.data['requester']['anthropic-messages']['base-url'].replace(' ', ''),
|
||||||
# cast to a valid type because mypy doesn't understand our type narrowing
|
# cast to a valid type because mypy doesn't understand our type narrowing
|
||||||
timeout=typing.cast(httpx.Timeout, self.ap.provider_cfg.data['requester']['anthropic-messages']['timeout']),
|
timeout=typing.cast(httpx.Timeout, self.ap.provider_cfg.data['requester']['anthropic-messages']['timeout']),
|
||||||
limits=anthropic._constants.DEFAULT_CONNECTION_LIMITS,
|
limits=anthropic._constants.DEFAULT_CONNECTION_LIMITS,
|
||||||
@@ -59,9 +67,11 @@ class AnthropicMessages(requester.LLMAPIRequester):
|
|||||||
if m.role == "system":
|
if m.role == "system":
|
||||||
system_role_message = m
|
system_role_message = m
|
||||||
|
|
||||||
messages.pop(i)
|
|
||||||
break
|
break
|
||||||
|
|
||||||
|
if system_role_message:
|
||||||
|
messages.pop(i)
|
||||||
|
|
||||||
if isinstance(system_role_message, llm_entities.Message) \
|
if isinstance(system_role_message, llm_entities.Message) \
|
||||||
and isinstance(system_role_message.content, str):
|
and isinstance(system_role_message.content, str):
|
||||||
args['system'] = system_role_message.content
|
args['system'] = system_role_message.content
|
||||||
|
|||||||
@@ -2,12 +2,12 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import openai
|
import openai
|
||||||
|
|
||||||
from . import chatcmpl
|
from . import chatcmpl, modelscopechatcmpl
|
||||||
from .. import requester
|
from .. import requester
|
||||||
from ....core import app
|
from ....core import app
|
||||||
|
|
||||||
|
|
||||||
class BailianChatCompletions(chatcmpl.OpenAIChatCompletions):
|
class BailianChatCompletions(modelscopechatcmpl.ModelScopeChatCompletions):
|
||||||
"""阿里云百炼大模型平台 ChatCompletion API 请求器"""
|
"""阿里云百炼大模型平台 ChatCompletion API 请求器"""
|
||||||
|
|
||||||
client: openai.AsyncClient
|
client: openai.AsyncClient
|
||||||
@@ -18,3 +18,4 @@ class BailianChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
self.ap = ap
|
self.ap = ap
|
||||||
|
|
||||||
self.requester_cfg = self.ap.provider_cfg.data['requester']['bailian-chat-completions']
|
self.requester_cfg = self.ap.provider_cfg.data['requester']['bailian-chat-completions']
|
||||||
|
|
||||||
@@ -36,7 +36,7 @@ class OpenAIChatCompletions(requester.LLMAPIRequester):
|
|||||||
|
|
||||||
self.client = openai.AsyncClient(
|
self.client = openai.AsyncClient(
|
||||||
api_key="",
|
api_key="",
|
||||||
base_url=self.requester_cfg['base-url'],
|
base_url=self.requester_cfg['base-url'].replace(' ', ''),
|
||||||
timeout=self.requester_cfg['timeout'],
|
timeout=self.requester_cfg['timeout'],
|
||||||
http_client=httpx.AsyncClient(
|
http_client=httpx.AsyncClient(
|
||||||
trust_env=True,
|
trust_env=True,
|
||||||
@@ -47,8 +47,9 @@ class OpenAIChatCompletions(requester.LLMAPIRequester):
|
|||||||
async def _req(
|
async def _req(
|
||||||
self,
|
self,
|
||||||
args: dict,
|
args: dict,
|
||||||
|
extra_body: dict = {},
|
||||||
) -> chat_completion.ChatCompletion:
|
) -> chat_completion.ChatCompletion:
|
||||||
return await self.client.chat.completions.create(**args)
|
return await self.client.chat.completions.create(**args, extra_body=extra_body)
|
||||||
|
|
||||||
async def _make_msg(
|
async def _make_msg(
|
||||||
self,
|
self,
|
||||||
@@ -60,6 +61,12 @@ class OpenAIChatCompletions(requester.LLMAPIRequester):
|
|||||||
if 'role' not in chatcmpl_message or chatcmpl_message['role'] is None:
|
if 'role' not in chatcmpl_message or chatcmpl_message['role'] is None:
|
||||||
chatcmpl_message['role'] = 'assistant'
|
chatcmpl_message['role'] = 'assistant'
|
||||||
|
|
||||||
|
reasoning_content = chatcmpl_message['reasoning_content'] if 'reasoning_content' in chatcmpl_message else None
|
||||||
|
|
||||||
|
# deepseek的reasoner模型
|
||||||
|
if reasoning_content is not None:
|
||||||
|
chatcmpl_message['content'] = "<think>\n" + reasoning_content + "\n</think>\n\n"+ chatcmpl_message['content']
|
||||||
|
|
||||||
message = llm_entities.Message(**chatcmpl_message)
|
message = llm_entities.Message(**chatcmpl_message)
|
||||||
|
|
||||||
return message
|
return message
|
||||||
@@ -73,7 +80,7 @@ class OpenAIChatCompletions(requester.LLMAPIRequester):
|
|||||||
) -> llm_entities.Message:
|
) -> llm_entities.Message:
|
||||||
self.client.api_key = use_model.token_mgr.get_token()
|
self.client.api_key = use_model.token_mgr.get_token()
|
||||||
|
|
||||||
args = self.requester_cfg['args'].copy()
|
args = {}
|
||||||
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
||||||
|
|
||||||
if use_funcs:
|
if use_funcs:
|
||||||
@@ -99,7 +106,7 @@ class OpenAIChatCompletions(requester.LLMAPIRequester):
|
|||||||
args["messages"] = messages
|
args["messages"] = messages
|
||||||
|
|
||||||
# 发送请求
|
# 发送请求
|
||||||
resp = await self._req(args)
|
resp = await self._req(args, extra_body=self.requester_cfg['args'])
|
||||||
|
|
||||||
# 处理请求结果
|
# 处理请求结果
|
||||||
message = await self._make_msg(resp)
|
message = await self._make_msg(resp)
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ class DeepseekChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
) -> llm_entities.Message:
|
) -> llm_entities.Message:
|
||||||
self.client.api_key = use_model.token_mgr.get_token()
|
self.client.api_key = use_model.token_mgr.get_token()
|
||||||
|
|
||||||
args = self.requester_cfg['args'].copy()
|
args = {}
|
||||||
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
||||||
|
|
||||||
if use_funcs:
|
if use_funcs:
|
||||||
@@ -43,7 +43,7 @@ class DeepseekChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
args["messages"] = messages
|
args["messages"] = messages
|
||||||
|
|
||||||
# 发送请求
|
# 发送请求
|
||||||
resp = await self._req(args)
|
resp = await self._req(args, extra_body=self.requester_cfg['args'])
|
||||||
|
|
||||||
if resp is None:
|
if resp is None:
|
||||||
raise errors.RequesterError('接口返回为空,请确定模型提供商服务是否正常')
|
raise errors.RequesterError('接口返回为空,请确定模型提供商服务是否正常')
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ class GiteeAIChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
) -> llm_entities.Message:
|
) -> llm_entities.Message:
|
||||||
self.client.api_key = use_model.token_mgr.get_token()
|
self.client.api_key = use_model.token_mgr.get_token()
|
||||||
|
|
||||||
args = self.requester_cfg['args'].copy()
|
args = {}
|
||||||
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
||||||
|
|
||||||
if use_funcs:
|
if use_funcs:
|
||||||
@@ -46,7 +46,7 @@ class GiteeAIChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
|
|
||||||
args["messages"] = req_messages
|
args["messages"] = req_messages
|
||||||
|
|
||||||
resp = await self._req(args)
|
resp = await self._req(args, extra_body=self.requester_cfg['args'])
|
||||||
|
|
||||||
message = await self._make_msg(resp)
|
message = await self._make_msg(resp)
|
||||||
|
|
||||||
|
|||||||
207
pkg/provider/modelmgr/requesters/modelscopechatcmpl.py
Normal file
207
pkg/provider/modelmgr/requesters/modelscopechatcmpl.py
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import typing
|
||||||
|
import json
|
||||||
|
import base64
|
||||||
|
from typing import AsyncGenerator
|
||||||
|
|
||||||
|
import openai
|
||||||
|
import openai.types.chat.chat_completion as chat_completion
|
||||||
|
import openai.types.chat.chat_completion_message_tool_call as chat_completion_message_tool_call
|
||||||
|
import httpx
|
||||||
|
import aiohttp
|
||||||
|
import async_lru
|
||||||
|
|
||||||
|
from .. import entities, errors, requester
|
||||||
|
from ....core import entities as core_entities, app
|
||||||
|
from ... import entities as llm_entities
|
||||||
|
from ...tools import entities as tools_entities
|
||||||
|
from ....utils import image
|
||||||
|
|
||||||
|
|
||||||
|
class ModelScopeChatCompletions(requester.LLMAPIRequester):
|
||||||
|
"""ModelScope ChatCompletion API 请求器"""
|
||||||
|
|
||||||
|
client: openai.AsyncClient
|
||||||
|
|
||||||
|
requester_cfg: dict
|
||||||
|
|
||||||
|
def __init__(self, ap: app.Application):
|
||||||
|
self.ap = ap
|
||||||
|
|
||||||
|
self.requester_cfg = self.ap.provider_cfg.data['requester']['modelscope-chat-completions']
|
||||||
|
|
||||||
|
async def initialize(self):
|
||||||
|
|
||||||
|
self.client = openai.AsyncClient(
|
||||||
|
api_key="",
|
||||||
|
base_url=self.requester_cfg['base-url'],
|
||||||
|
timeout=self.requester_cfg['timeout'],
|
||||||
|
http_client=httpx.AsyncClient(
|
||||||
|
trust_env=True,
|
||||||
|
timeout=self.requester_cfg['timeout']
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _req(
|
||||||
|
self,
|
||||||
|
args: dict,
|
||||||
|
) -> chat_completion.ChatCompletion:
|
||||||
|
args["stream"] = True
|
||||||
|
|
||||||
|
chunk = None
|
||||||
|
|
||||||
|
pending_content = ""
|
||||||
|
|
||||||
|
tool_calls = []
|
||||||
|
|
||||||
|
resp_gen: openai.AsyncStream = await self.client.chat.completions.create(**args)
|
||||||
|
|
||||||
|
async for chunk in resp_gen:
|
||||||
|
# print(chunk)
|
||||||
|
if not chunk or not chunk.id or not chunk.choices or not chunk.choices[0] or not chunk.choices[0].delta:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if chunk.choices[0].delta.content is not None:
|
||||||
|
pending_content += chunk.choices[0].delta.content
|
||||||
|
|
||||||
|
if chunk.choices[0].delta.tool_calls is not None:
|
||||||
|
for tool_call in chunk.choices[0].delta.tool_calls:
|
||||||
|
for tc in tool_calls:
|
||||||
|
if tc.index == tool_call.index:
|
||||||
|
tc.function.arguments += tool_call.function.arguments
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
tool_calls.append(tool_call)
|
||||||
|
|
||||||
|
if chunk.choices[0].finish_reason is not None:
|
||||||
|
break
|
||||||
|
|
||||||
|
real_tool_calls = []
|
||||||
|
|
||||||
|
for tc in tool_calls:
|
||||||
|
function = chat_completion_message_tool_call.Function(
|
||||||
|
name=tc.function.name,
|
||||||
|
arguments=tc.function.arguments
|
||||||
|
)
|
||||||
|
real_tool_calls.append(chat_completion_message_tool_call.ChatCompletionMessageToolCall(
|
||||||
|
id=tc.id,
|
||||||
|
function=function,
|
||||||
|
type="function"
|
||||||
|
))
|
||||||
|
|
||||||
|
return chat_completion.ChatCompletion(
|
||||||
|
id=chunk.id,
|
||||||
|
object="chat.completion",
|
||||||
|
created=chunk.created,
|
||||||
|
choices=[
|
||||||
|
chat_completion.Choice(
|
||||||
|
index=0,
|
||||||
|
message=chat_completion.ChatCompletionMessage(
|
||||||
|
role="assistant",
|
||||||
|
content=pending_content,
|
||||||
|
tool_calls=real_tool_calls if len(real_tool_calls) > 0 else None
|
||||||
|
),
|
||||||
|
finish_reason=chunk.choices[0].finish_reason if hasattr(chunk.choices[0], 'finish_reason') and chunk.choices[0].finish_reason is not None else 'stop',
|
||||||
|
logprobs=chunk.choices[0].logprobs,
|
||||||
|
)
|
||||||
|
],
|
||||||
|
model=chunk.model,
|
||||||
|
service_tier=chunk.service_tier if hasattr(chunk, 'service_tier') else None,
|
||||||
|
system_fingerprint=chunk.system_fingerprint if hasattr(chunk, 'system_fingerprint') else None,
|
||||||
|
usage=chunk.usage if hasattr(chunk, 'usage') else None
|
||||||
|
) if chunk else None
|
||||||
|
return await self.client.chat.completions.create(**args)
|
||||||
|
|
||||||
|
async def _make_msg(
|
||||||
|
self,
|
||||||
|
chat_completion: chat_completion.ChatCompletion,
|
||||||
|
) -> llm_entities.Message:
|
||||||
|
chatcmpl_message = chat_completion.choices[0].message.dict()
|
||||||
|
|
||||||
|
# 确保 role 字段存在且不为 None
|
||||||
|
if 'role' not in chatcmpl_message or chatcmpl_message['role'] is None:
|
||||||
|
chatcmpl_message['role'] = 'assistant'
|
||||||
|
|
||||||
|
message = llm_entities.Message(**chatcmpl_message)
|
||||||
|
|
||||||
|
return message
|
||||||
|
|
||||||
|
async def _closure(
|
||||||
|
self,
|
||||||
|
query: core_entities.Query,
|
||||||
|
req_messages: list[dict],
|
||||||
|
use_model: entities.LLMModelInfo,
|
||||||
|
use_funcs: list[tools_entities.LLMFunction] = None,
|
||||||
|
) -> llm_entities.Message:
|
||||||
|
self.client.api_key = use_model.token_mgr.get_token()
|
||||||
|
|
||||||
|
args = self.requester_cfg['args'].copy()
|
||||||
|
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
||||||
|
|
||||||
|
if use_funcs:
|
||||||
|
tools = await self.ap.tool_mgr.generate_tools_for_openai(use_funcs)
|
||||||
|
|
||||||
|
if tools:
|
||||||
|
args["tools"] = tools
|
||||||
|
|
||||||
|
# 设置此次请求中的messages
|
||||||
|
messages = req_messages.copy()
|
||||||
|
|
||||||
|
# 检查vision
|
||||||
|
for msg in messages:
|
||||||
|
if 'content' in msg and isinstance(msg["content"], list):
|
||||||
|
for me in msg["content"]:
|
||||||
|
if me["type"] == "image_base64":
|
||||||
|
me["image_url"] = {
|
||||||
|
"url": me["image_base64"]
|
||||||
|
}
|
||||||
|
me["type"] = "image_url"
|
||||||
|
del me["image_base64"]
|
||||||
|
|
||||||
|
args["messages"] = messages
|
||||||
|
|
||||||
|
# 发送请求
|
||||||
|
resp = await self._req(args)
|
||||||
|
|
||||||
|
# 处理请求结果
|
||||||
|
message = await self._make_msg(resp)
|
||||||
|
|
||||||
|
return message
|
||||||
|
|
||||||
|
async def call(
|
||||||
|
self,
|
||||||
|
query: core_entities.Query,
|
||||||
|
model: entities.LLMModelInfo,
|
||||||
|
messages: typing.List[llm_entities.Message],
|
||||||
|
funcs: typing.List[tools_entities.LLMFunction] = None,
|
||||||
|
) -> llm_entities.Message:
|
||||||
|
req_messages = [] # req_messages 仅用于类内,外部同步由 query.messages 进行
|
||||||
|
for m in messages:
|
||||||
|
msg_dict = m.dict(exclude_none=True)
|
||||||
|
content = msg_dict.get("content")
|
||||||
|
if isinstance(content, list):
|
||||||
|
# 检查 content 列表中是否每个部分都是文本
|
||||||
|
if all(isinstance(part, dict) and part.get("type") == "text" for part in content):
|
||||||
|
# 将所有文本部分合并为一个字符串
|
||||||
|
msg_dict["content"] = "\n".join(part["text"] for part in content)
|
||||||
|
req_messages.append(msg_dict)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return await self._closure(query=query, req_messages=req_messages, use_model=model, use_funcs=funcs)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
raise errors.RequesterError('请求超时')
|
||||||
|
except openai.BadRequestError as e:
|
||||||
|
if 'context_length_exceeded' in e.message:
|
||||||
|
raise errors.RequesterError(f'上文过长,请重置会话: {e.message}')
|
||||||
|
else:
|
||||||
|
raise errors.RequesterError(f'请求参数错误: {e.message}')
|
||||||
|
except openai.AuthenticationError as e:
|
||||||
|
raise errors.RequesterError(f'无效的 api-key: {e.message}')
|
||||||
|
except openai.NotFoundError as e:
|
||||||
|
raise errors.RequesterError(f'请求路径错误: {e.message}')
|
||||||
|
except openai.RateLimitError as e:
|
||||||
|
raise errors.RequesterError(f'请求过于频繁或余额不足: {e.message}')
|
||||||
|
except openai.APIError as e:
|
||||||
|
raise errors.RequesterError(f'请求错误: {e.message}')
|
||||||
34
pkg/provider/modelmgr/requesters/modelscopechatcmpl.yaml
Normal file
34
pkg/provider/modelmgr/requesters/modelscopechatcmpl.yaml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: LLMAPIRequester
|
||||||
|
metadata:
|
||||||
|
name: modelscope-chat-completions
|
||||||
|
label:
|
||||||
|
en_US: ModelScope
|
||||||
|
zh_CN: 魔搭社区
|
||||||
|
spec:
|
||||||
|
config:
|
||||||
|
- name: base-url
|
||||||
|
label:
|
||||||
|
en_US: Base URL
|
||||||
|
zh_CN: 基础 URL
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: "https://api-inference.modelscope.cn/v1"
|
||||||
|
- name: args
|
||||||
|
label:
|
||||||
|
en_US: Args
|
||||||
|
zh_CN: 附加参数
|
||||||
|
type: object
|
||||||
|
required: true
|
||||||
|
default: {}
|
||||||
|
- name: timeout
|
||||||
|
label:
|
||||||
|
en_US: Timeout
|
||||||
|
zh_CN: 超时时间
|
||||||
|
type: int
|
||||||
|
required: true
|
||||||
|
default: 120
|
||||||
|
execution:
|
||||||
|
python:
|
||||||
|
path: ./modelscopechatcmpl.py
|
||||||
|
attr: ModelScopeChatCompletions
|
||||||
@@ -25,7 +25,7 @@ class MoonshotChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
) -> llm_entities.Message:
|
) -> llm_entities.Message:
|
||||||
self.client.api_key = use_model.token_mgr.get_token()
|
self.client.api_key = use_model.token_mgr.get_token()
|
||||||
|
|
||||||
args = self.requester_cfg['args'].copy()
|
args = {}
|
||||||
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
args["model"] = use_model.name if use_model.model_name is None else use_model.model_name
|
||||||
|
|
||||||
if use_funcs:
|
if use_funcs:
|
||||||
@@ -42,13 +42,13 @@ class MoonshotChatCompletions(chatcmpl.OpenAIChatCompletions):
|
|||||||
if 'content' in m and isinstance(m["content"], list):
|
if 'content' in m and isinstance(m["content"], list):
|
||||||
m["content"] = " ".join([c["text"] for c in m["content"]])
|
m["content"] = " ".join([c["text"] for c in m["content"]])
|
||||||
|
|
||||||
# 删除空的
|
# 删除空的,不知道干嘛的,直接删了。
|
||||||
messages = [m for m in messages if m["content"].strip() != ""]
|
# messages = [m for m in messages if m["content"].strip() != "" and ('tool_calls' not in m or not m['tool_calls'])]
|
||||||
|
|
||||||
args["messages"] = messages
|
args["messages"] = messages
|
||||||
|
|
||||||
# 发送请求
|
# 发送请求
|
||||||
resp = await self._req(args)
|
resp = await self._req(args, extra_body=self.requester_cfg['args'])
|
||||||
|
|
||||||
# 处理请求结果
|
# 处理请求结果
|
||||||
message = await self._make_msg(resp)
|
message = await self._make_msg(resp)
|
||||||
|
|||||||
20
pkg/provider/modelmgr/requesters/ppiochatcmpl.py
Normal file
20
pkg/provider/modelmgr/requesters/ppiochatcmpl.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import openai
|
||||||
|
|
||||||
|
from . import chatcmpl, modelscopechatcmpl
|
||||||
|
from .. import requester
|
||||||
|
from ....core import app
|
||||||
|
|
||||||
|
class PPIOChatCompletions(chatcmpl.OpenAIChatCompletions):
|
||||||
|
"""欧派云 ChatCompletion API 请求器"""
|
||||||
|
|
||||||
|
client: openai.AsyncClient
|
||||||
|
|
||||||
|
requester_cfg: dict
|
||||||
|
|
||||||
|
def __init__(self, ap: app.Application):
|
||||||
|
self.ap = ap
|
||||||
|
|
||||||
|
self.requester_cfg = self.ap.provider_cfg.data['requester']['ppio-chat-completions']
|
||||||
34
pkg/provider/modelmgr/requesters/ppiochatcmpl.yaml
Normal file
34
pkg/provider/modelmgr/requesters/ppiochatcmpl.yaml
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: LLMAPIRequester
|
||||||
|
metadata:
|
||||||
|
name: ppio-chat-completions
|
||||||
|
label:
|
||||||
|
en_US: ppio
|
||||||
|
zh_CN: 派欧云
|
||||||
|
spec:
|
||||||
|
config:
|
||||||
|
- name: base-url
|
||||||
|
label:
|
||||||
|
en_US: Base URL
|
||||||
|
zh_CN: 基础 URL
|
||||||
|
type: string
|
||||||
|
required: true
|
||||||
|
default: "https://api.ppinfra.com/v3/openai"
|
||||||
|
- name: args
|
||||||
|
label:
|
||||||
|
en_US: Args
|
||||||
|
zh_CN: 附加参数
|
||||||
|
type: object
|
||||||
|
required: true
|
||||||
|
default: {}
|
||||||
|
- name: timeout
|
||||||
|
label:
|
||||||
|
en_US: Timeout
|
||||||
|
zh_CN: 超时时间
|
||||||
|
type: int
|
||||||
|
required: true
|
||||||
|
default: 120
|
||||||
|
execution:
|
||||||
|
python:
|
||||||
|
path: ./ppiochatcmpl.py
|
||||||
|
attr: PPIOChatCompletions
|
||||||
@@ -167,6 +167,10 @@ class DashScopeAPIRunner(runner.RequestRunner):
|
|||||||
image_ids = [] # 用户输入的图片ID列表 (暂不支持)
|
image_ids = [] # 用户输入的图片ID列表 (暂不支持)
|
||||||
|
|
||||||
plain_text, image_ids = await self._preprocess_user_message(query)
|
plain_text, image_ids = await self._preprocess_user_message(query)
|
||||||
|
|
||||||
|
biz_params = {}
|
||||||
|
biz_params.update(self.biz_params)
|
||||||
|
biz_params.update(query.variables)
|
||||||
|
|
||||||
#发送对话请求
|
#发送对话请求
|
||||||
response = dashscope.Application.call(
|
response = dashscope.Application.call(
|
||||||
@@ -176,7 +180,7 @@ class DashScopeAPIRunner(runner.RequestRunner):
|
|||||||
stream=True, # 流式输出
|
stream=True, # 流式输出
|
||||||
incremental_output=True, # 增量输出,使用流式输出需要开启增量输出
|
incremental_output=True, # 增量输出,使用流式输出需要开启增量输出
|
||||||
session_id=query.session.using_conversation.uuid, # 会话ID用于,多轮对话
|
session_id=query.session.using_conversation.uuid, # 会话ID用于,多轮对话
|
||||||
biz_params=self.biz_params # 工作流应用的自定义输入参数传递
|
biz_params=biz_params, # 工作流应用的自定义输入参数传递
|
||||||
# rag_options={ # 主要用于文件交互,暂不支持
|
# rag_options={ # 主要用于文件交互,暂不支持
|
||||||
# "session_file_ids": ["FILE_ID1"], # FILE_ID1 替换为实际的临时文件ID,逗号隔开多个
|
# "session_file_ids": ["FILE_ID1"], # FILE_ID1 替换为实际的临时文件ID,逗号隔开多个
|
||||||
# }
|
# }
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import json
|
|||||||
import uuid
|
import uuid
|
||||||
import re
|
import re
|
||||||
import base64
|
import base64
|
||||||
|
import datetime
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
|
||||||
@@ -69,6 +70,7 @@ class DifyServiceAPIRunner(runner.RequestRunner):
|
|||||||
"""
|
"""
|
||||||
plain_text = ""
|
plain_text = ""
|
||||||
image_ids = []
|
image_ids = []
|
||||||
|
|
||||||
if isinstance(query.user_message.content, list):
|
if isinstance(query.user_message.content, list):
|
||||||
for ce in query.user_message.content:
|
for ce in query.user_message.content:
|
||||||
if ce.type == "text":
|
if ce.type == "text":
|
||||||
@@ -109,8 +111,12 @@ class DifyServiceAPIRunner(runner.RequestRunner):
|
|||||||
|
|
||||||
basic_mode_pending_chunk = ''
|
basic_mode_pending_chunk = ''
|
||||||
|
|
||||||
|
inputs = {}
|
||||||
|
|
||||||
|
inputs.update(query.variables)
|
||||||
|
|
||||||
async for chunk in self.dify_client.chat_messages(
|
async for chunk in self.dify_client.chat_messages(
|
||||||
inputs={},
|
inputs=inputs,
|
||||||
query=plain_text,
|
query=plain_text,
|
||||||
user=f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
user=f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
||||||
conversation_id=cov_id,
|
conversation_id=cov_id,
|
||||||
@@ -160,8 +166,12 @@ class DifyServiceAPIRunner(runner.RequestRunner):
|
|||||||
|
|
||||||
ignored_events = ["agent_message"]
|
ignored_events = ["agent_message"]
|
||||||
|
|
||||||
|
inputs = {}
|
||||||
|
|
||||||
|
inputs.update(query.variables)
|
||||||
|
|
||||||
async for chunk in self.dify_client.chat_messages(
|
async for chunk in self.dify_client.chat_messages(
|
||||||
inputs={},
|
inputs=inputs,
|
||||||
query=plain_text,
|
query=plain_text,
|
||||||
user=f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
user=f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
||||||
response_mode="streaming",
|
response_mode="streaming",
|
||||||
@@ -215,6 +225,8 @@ class DifyServiceAPIRunner(runner.RequestRunner):
|
|||||||
role="assistant",
|
role="assistant",
|
||||||
content=[llm_entities.ContentElement.from_image_url(image_url)],
|
content=[llm_entities.ContentElement.from_image_url(image_url)],
|
||||||
)
|
)
|
||||||
|
if chunk['event'] == 'error':
|
||||||
|
raise errors.DifyAPIError("dify 服务错误: " + chunk['message'])
|
||||||
|
|
||||||
query.session.using_conversation.uuid = chunk["conversation_id"]
|
query.session.using_conversation.uuid = chunk["conversation_id"]
|
||||||
|
|
||||||
@@ -225,8 +237,8 @@ class DifyServiceAPIRunner(runner.RequestRunner):
|
|||||||
|
|
||||||
if not query.session.using_conversation.uuid:
|
if not query.session.using_conversation.uuid:
|
||||||
query.session.using_conversation.uuid = str(uuid.uuid4())
|
query.session.using_conversation.uuid = str(uuid.uuid4())
|
||||||
|
|
||||||
cov_id = query.session.using_conversation.uuid
|
query.variables["conversation_id"] = query.session.using_conversation.uuid
|
||||||
|
|
||||||
plain_text, image_ids = await self._preprocess_user_message(query)
|
plain_text, image_ids = await self._preprocess_user_message(query)
|
||||||
|
|
||||||
@@ -241,12 +253,17 @@ class DifyServiceAPIRunner(runner.RequestRunner):
|
|||||||
|
|
||||||
ignored_events = ["text_chunk", "workflow_started"]
|
ignored_events = ["text_chunk", "workflow_started"]
|
||||||
|
|
||||||
|
inputs = { # these variables are legacy variables, we need to keep them for compatibility
|
||||||
|
"langbot_user_message_text": plain_text,
|
||||||
|
"langbot_session_id": query.variables["session_id"],
|
||||||
|
"langbot_conversation_id": query.variables["conversation_id"],
|
||||||
|
"langbot_msg_create_time": query.variables["msg_create_time"],
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs.update(query.variables)
|
||||||
|
|
||||||
async for chunk in self.dify_client.workflow_run(
|
async for chunk in self.dify_client.workflow_run(
|
||||||
inputs={
|
inputs=inputs,
|
||||||
"langbot_user_message_text": plain_text,
|
|
||||||
"langbot_session_id": f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
|
||||||
"langbot_conversation_id": cov_id,
|
|
||||||
},
|
|
||||||
user=f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
user=f"{query.session.launcher_type.value}_{query.session.launcher_id}",
|
||||||
files=files,
|
files=files,
|
||||||
timeout=self.ap.provider_cfg.data["dify-service-api"]["workflow"]["timeout"],
|
timeout=self.ap.provider_cfg.data["dify-service-api"]["workflow"]["timeout"],
|
||||||
|
|||||||
@@ -54,7 +54,6 @@ class SessionManager:
|
|||||||
use_model=await self.ap.model_mgr.get_model_by_name(self.ap.provider_cfg.data['model']),
|
use_model=await self.ap.model_mgr.get_model_by_name(self.ap.provider_cfg.data['model']),
|
||||||
use_funcs=await self.ap.tool_mgr.get_all_functions(
|
use_funcs=await self.ap.tool_mgr.get_all_functions(
|
||||||
plugin_enabled=True,
|
plugin_enabled=True,
|
||||||
plugin_status=plugin_context.RuntimeContainerStatus.INITIALIZED,
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
session.conversations.append(conversation)
|
session.conversations.append(conversation)
|
||||||
|
|||||||
54
pkg/provider/tools/loader.py
Normal file
54
pkg/provider/tools/loader.py
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import abc
|
||||||
|
import typing
|
||||||
|
|
||||||
|
from ...core import app, entities as core_entities
|
||||||
|
from . import entities as tools_entities
|
||||||
|
|
||||||
|
|
||||||
|
preregistered_loaders: list[typing.Type[ToolLoader]] = []
|
||||||
|
|
||||||
|
def loader_class(name: str):
|
||||||
|
"""注册一个工具加载器
|
||||||
|
"""
|
||||||
|
def decorator(cls: typing.Type[ToolLoader]) -> typing.Type[ToolLoader]:
|
||||||
|
cls.name = name
|
||||||
|
preregistered_loaders.append(cls)
|
||||||
|
return cls
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
|
||||||
|
class ToolLoader(abc.ABC):
|
||||||
|
"""工具加载器"""
|
||||||
|
|
||||||
|
name: str = None
|
||||||
|
|
||||||
|
ap: app.Application
|
||||||
|
|
||||||
|
def __init__(self, ap: app.Application):
|
||||||
|
self.ap = ap
|
||||||
|
|
||||||
|
async def initialize(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
async def get_tools(self, enabled: bool=True) -> list[tools_entities.LLMFunction]:
|
||||||
|
"""获取所有工具"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
async def has_tool(self, name: str) -> bool:
|
||||||
|
"""检查工具是否存在"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
async def invoke_tool(self, query: core_entities.Query, name: str, parameters: dict) -> typing.Any:
|
||||||
|
"""执行工具调用"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
async def shutdown(self):
|
||||||
|
"""关闭工具"""
|
||||||
|
pass
|
||||||
0
pkg/provider/tools/loaders/__init__.py
Normal file
0
pkg/provider/tools/loaders/__init__.py
Normal file
161
pkg/provider/tools/loaders/mcp.py
Normal file
161
pkg/provider/tools/loaders/mcp.py
Normal file
@@ -0,0 +1,161 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import typing
|
||||||
|
from contextlib import AsyncExitStack
|
||||||
|
|
||||||
|
from mcp import ClientSession, StdioServerParameters
|
||||||
|
from mcp.client.stdio import stdio_client
|
||||||
|
from mcp.client.sse import sse_client
|
||||||
|
|
||||||
|
from .. import loader, entities as tools_entities
|
||||||
|
from ....core import app, entities as core_entities
|
||||||
|
|
||||||
|
|
||||||
|
class RuntimeMCPSession:
|
||||||
|
"""运行时 MCP 会话"""
|
||||||
|
|
||||||
|
ap: app.Application
|
||||||
|
|
||||||
|
server_name: str
|
||||||
|
|
||||||
|
server_config: dict
|
||||||
|
|
||||||
|
session: ClientSession
|
||||||
|
|
||||||
|
exit_stack: AsyncExitStack
|
||||||
|
|
||||||
|
functions: list[tools_entities.LLMFunction] = []
|
||||||
|
|
||||||
|
def __init__(self, server_name: str, server_config: dict, ap: app.Application):
|
||||||
|
self.server_name = server_name
|
||||||
|
self.server_config = server_config
|
||||||
|
self.ap = ap
|
||||||
|
|
||||||
|
self.session = None
|
||||||
|
|
||||||
|
self.exit_stack = AsyncExitStack()
|
||||||
|
self.functions = []
|
||||||
|
|
||||||
|
async def _init_stdio_python_server(self):
|
||||||
|
server_params = StdioServerParameters(
|
||||||
|
command=self.server_config["command"],
|
||||||
|
args=self.server_config["args"],
|
||||||
|
env=self.server_config["env"],
|
||||||
|
)
|
||||||
|
|
||||||
|
stdio_transport = await self.exit_stack.enter_async_context(
|
||||||
|
stdio_client(server_params)
|
||||||
|
)
|
||||||
|
|
||||||
|
stdio, write = stdio_transport
|
||||||
|
|
||||||
|
self.session = await self.exit_stack.enter_async_context(
|
||||||
|
ClientSession(stdio, write)
|
||||||
|
)
|
||||||
|
|
||||||
|
await self.session.initialize()
|
||||||
|
|
||||||
|
async def _init_sse_server(self):
|
||||||
|
sse_transport = await self.exit_stack.enter_async_context(
|
||||||
|
sse_client(
|
||||||
|
self.server_config["url"],
|
||||||
|
headers=self.server_config.get("headers", {}),
|
||||||
|
timeout=self.server_config.get("timeout", 10),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
sseio, write = sse_transport
|
||||||
|
|
||||||
|
self.session = await self.exit_stack.enter_async_context(
|
||||||
|
ClientSession(sseio, write)
|
||||||
|
)
|
||||||
|
|
||||||
|
await self.session.initialize()
|
||||||
|
|
||||||
|
async def initialize(self):
|
||||||
|
self.ap.logger.debug(f"初始化 MCP 会话: {self.server_name} {self.server_config}")
|
||||||
|
|
||||||
|
if self.server_config["mode"] == "stdio":
|
||||||
|
await self._init_stdio_python_server()
|
||||||
|
elif self.server_config["mode"] == "sse":
|
||||||
|
await self._init_sse_server()
|
||||||
|
else:
|
||||||
|
raise ValueError(f"无法识别 MCP 服务器类型: {self.server_name}: {self.server_config}")
|
||||||
|
|
||||||
|
tools = await self.session.list_tools()
|
||||||
|
|
||||||
|
self.ap.logger.debug(f"获取 MCP 工具: {tools}")
|
||||||
|
|
||||||
|
for tool in tools.tools:
|
||||||
|
|
||||||
|
async def func(query: core_entities.Query, **kwargs):
|
||||||
|
result = await self.session.call_tool(tool.name, kwargs)
|
||||||
|
if result.isError:
|
||||||
|
raise Exception(result.content[0].text)
|
||||||
|
return result.content[0].text
|
||||||
|
|
||||||
|
func.__name__ = tool.name
|
||||||
|
|
||||||
|
self.functions.append(tools_entities.LLMFunction(
|
||||||
|
name=tool.name,
|
||||||
|
human_desc=tool.description,
|
||||||
|
description=tool.description,
|
||||||
|
parameters=tool.inputSchema,
|
||||||
|
func=func,
|
||||||
|
))
|
||||||
|
|
||||||
|
async def shutdown(self):
|
||||||
|
"""关闭工具"""
|
||||||
|
await self.session._exit_stack.aclose()
|
||||||
|
|
||||||
|
@loader.loader_class("mcp")
|
||||||
|
class MCPLoader(loader.ToolLoader):
|
||||||
|
"""MCP 工具加载器。
|
||||||
|
|
||||||
|
在此加载器中管理所有与 MCP Server 的连接。
|
||||||
|
"""
|
||||||
|
|
||||||
|
sessions: dict[str, RuntimeMCPSession] = {}
|
||||||
|
|
||||||
|
_last_listed_functions: list[tools_entities.LLMFunction] = []
|
||||||
|
|
||||||
|
def __init__(self, ap: app.Application):
|
||||||
|
super().__init__(ap)
|
||||||
|
self.sessions = {}
|
||||||
|
self._last_listed_functions = []
|
||||||
|
|
||||||
|
async def initialize(self):
|
||||||
|
|
||||||
|
for server_config in self.ap.provider_cfg.data.get("mcp", {}).get("servers", []):
|
||||||
|
if not server_config["enable"]:
|
||||||
|
continue
|
||||||
|
session = RuntimeMCPSession(server_config["name"], server_config, self.ap)
|
||||||
|
await session.initialize()
|
||||||
|
# self.ap.event_loop.create_task(session.initialize())
|
||||||
|
self.sessions[server_config["name"]] = session
|
||||||
|
|
||||||
|
async def get_tools(self, enabled: bool=True) -> list[tools_entities.LLMFunction]:
|
||||||
|
all_functions = []
|
||||||
|
|
||||||
|
for session in self.sessions.values():
|
||||||
|
all_functions.extend(session.functions)
|
||||||
|
|
||||||
|
self._last_listed_functions = all_functions
|
||||||
|
|
||||||
|
return all_functions
|
||||||
|
|
||||||
|
async def has_tool(self, name: str) -> bool:
|
||||||
|
return name in [f.name for f in self._last_listed_functions]
|
||||||
|
|
||||||
|
async def invoke_tool(self, query: core_entities.Query, name: str, parameters: dict) -> typing.Any:
|
||||||
|
for server_name, session in self.sessions.items():
|
||||||
|
for function in session.functions:
|
||||||
|
if function.name == name:
|
||||||
|
return await function.func(query, **parameters)
|
||||||
|
|
||||||
|
raise ValueError(f"未找到工具: {name}")
|
||||||
|
|
||||||
|
async def shutdown(self):
|
||||||
|
"""关闭工具"""
|
||||||
|
for session in self.sessions.values():
|
||||||
|
await session.shutdown()
|
||||||
92
pkg/provider/tools/loaders/plugin.py
Normal file
92
pkg/provider/tools/loaders/plugin.py
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import typing
|
||||||
|
import traceback
|
||||||
|
|
||||||
|
from .. import loader, entities as tools_entities
|
||||||
|
from ....core import app, entities as core_entities
|
||||||
|
from ....plugin import context as plugin_context
|
||||||
|
|
||||||
|
|
||||||
|
@loader.loader_class("plugin-tool-loader")
|
||||||
|
class PluginToolLoader(loader.ToolLoader):
|
||||||
|
"""插件工具加载器。
|
||||||
|
|
||||||
|
本加载器中不存储工具信息,仅负责从插件系统中获取工具信息。
|
||||||
|
"""
|
||||||
|
|
||||||
|
async def get_tools(self, enabled: bool=True) -> list[tools_entities.LLMFunction]:
|
||||||
|
|
||||||
|
# 从插件系统获取工具(内容函数)
|
||||||
|
all_functions: list[tools_entities.LLMFunction] = []
|
||||||
|
|
||||||
|
for plugin in self.ap.plugin_mgr.plugins(
|
||||||
|
enabled=enabled, status=plugin_context.RuntimeContainerStatus.INITIALIZED
|
||||||
|
):
|
||||||
|
all_functions.extend(plugin.content_functions)
|
||||||
|
|
||||||
|
return all_functions
|
||||||
|
|
||||||
|
async def has_tool(self, name: str) -> bool:
|
||||||
|
"""检查工具是否存在"""
|
||||||
|
for plugin in self.ap.plugin_mgr.plugins(
|
||||||
|
enabled=True, status=plugin_context.RuntimeContainerStatus.INITIALIZED
|
||||||
|
):
|
||||||
|
for function in plugin.content_functions:
|
||||||
|
if function.name == name:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _get_function_and_plugin(
|
||||||
|
self, name: str
|
||||||
|
) -> typing.Tuple[tools_entities.LLMFunction, plugin_context.BasePlugin]:
|
||||||
|
"""获取函数和插件实例"""
|
||||||
|
for plugin in self.ap.plugin_mgr.plugins(
|
||||||
|
enabled=True, status=plugin_context.RuntimeContainerStatus.INITIALIZED
|
||||||
|
):
|
||||||
|
for function in plugin.content_functions:
|
||||||
|
if function.name == name:
|
||||||
|
return function, plugin.plugin_inst
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
async def invoke_tool(self, query: core_entities.Query, name: str, parameters: dict) -> typing.Any:
|
||||||
|
|
||||||
|
try:
|
||||||
|
|
||||||
|
function, plugin = await self._get_function_and_plugin(name)
|
||||||
|
if function is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
parameters = parameters.copy()
|
||||||
|
|
||||||
|
parameters = {"query": query, **parameters}
|
||||||
|
|
||||||
|
return await function.func(plugin, **parameters)
|
||||||
|
except Exception as e:
|
||||||
|
self.ap.logger.error(f"执行函数 {name} 时发生错误: {e}")
|
||||||
|
traceback.print_exc()
|
||||||
|
return f"error occurred when executing function {name}: {e}"
|
||||||
|
finally:
|
||||||
|
plugin = None
|
||||||
|
|
||||||
|
for p in self.ap.plugin_mgr.plugins():
|
||||||
|
if function in p.content_functions:
|
||||||
|
plugin = p
|
||||||
|
break
|
||||||
|
|
||||||
|
if plugin is not None:
|
||||||
|
|
||||||
|
await self.ap.ctr_mgr.usage.post_function_record(
|
||||||
|
plugin={
|
||||||
|
"name": plugin.plugin_name,
|
||||||
|
"remote": plugin.plugin_source,
|
||||||
|
"version": plugin.plugin_version,
|
||||||
|
"author": plugin.plugin_author,
|
||||||
|
},
|
||||||
|
function_name=function.name,
|
||||||
|
function_description=function.description,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def shutdown(self):
|
||||||
|
"""关闭工具"""
|
||||||
|
pass
|
||||||
@@ -4,8 +4,9 @@ import typing
|
|||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
from ...core import app, entities as core_entities
|
from ...core import app, entities as core_entities
|
||||||
from . import entities
|
from . import entities, loader as tools_loader
|
||||||
from ...plugin import context as plugin_context
|
from ...plugin import context as plugin_context
|
||||||
|
from .loaders import plugin, mcp
|
||||||
|
|
||||||
|
|
||||||
class ToolManager:
|
class ToolManager:
|
||||||
@@ -13,33 +14,26 @@ class ToolManager:
|
|||||||
|
|
||||||
ap: app.Application
|
ap: app.Application
|
||||||
|
|
||||||
|
loaders: list[tools_loader.ToolLoader]
|
||||||
|
|
||||||
def __init__(self, ap: app.Application):
|
def __init__(self, ap: app.Application):
|
||||||
self.ap = ap
|
self.ap = ap
|
||||||
self.all_functions = []
|
self.all_functions = []
|
||||||
|
self.loaders = []
|
||||||
|
|
||||||
async def initialize(self):
|
async def initialize(self):
|
||||||
pass
|
|
||||||
|
|
||||||
async def get_function_and_plugin(
|
for loader_cls in tools_loader.preregistered_loaders:
|
||||||
self, name: str
|
loader_inst = loader_cls(self.ap)
|
||||||
) -> typing.Tuple[entities.LLMFunction, plugin_context.BasePlugin]:
|
await loader_inst.initialize()
|
||||||
"""获取函数和插件实例"""
|
self.loaders.append(loader_inst)
|
||||||
for plugin in self.ap.plugin_mgr.plugins(
|
|
||||||
enabled=True, status=plugin_context.RuntimeContainerStatus.INITIALIZED
|
|
||||||
):
|
|
||||||
for function in plugin.content_functions:
|
|
||||||
if function.name == name:
|
|
||||||
return function, plugin.plugin_inst
|
|
||||||
return None, None
|
|
||||||
|
|
||||||
async def get_all_functions(self, plugin_enabled: bool=None, plugin_status: plugin_context.RuntimeContainerStatus=None) -> list[entities.LLMFunction]:
|
async def get_all_functions(self, plugin_enabled: bool=None) -> list[entities.LLMFunction]:
|
||||||
"""获取所有函数"""
|
"""获取所有函数"""
|
||||||
all_functions: list[entities.LLMFunction] = []
|
all_functions: list[entities.LLMFunction] = []
|
||||||
|
|
||||||
for plugin in self.ap.plugin_mgr.plugins(
|
for loader in self.loaders:
|
||||||
enabled=plugin_enabled, status=plugin_status
|
all_functions.extend(await loader.get_tools(plugin_enabled))
|
||||||
):
|
|
||||||
all_functions.extend(plugin.content_functions)
|
|
||||||
|
|
||||||
return all_functions
|
return all_functions
|
||||||
|
|
||||||
@@ -102,38 +96,13 @@ class ToolManager:
|
|||||||
) -> typing.Any:
|
) -> typing.Any:
|
||||||
"""执行函数调用"""
|
"""执行函数调用"""
|
||||||
|
|
||||||
try:
|
for loader in self.loaders:
|
||||||
|
if await loader.has_tool(name):
|
||||||
|
return await loader.invoke_tool(query, name, parameters)
|
||||||
|
else:
|
||||||
|
raise ValueError(f"未找到工具: {name}")
|
||||||
|
|
||||||
function, plugin = await self.get_function_and_plugin(name)
|
async def shutdown(self):
|
||||||
if function is None:
|
"""关闭所有工具"""
|
||||||
return None
|
for loader in self.loaders:
|
||||||
|
await loader.shutdown()
|
||||||
parameters = parameters.copy()
|
|
||||||
|
|
||||||
parameters = {"query": query, **parameters}
|
|
||||||
|
|
||||||
return await function.func(plugin, **parameters)
|
|
||||||
except Exception as e:
|
|
||||||
self.ap.logger.error(f"执行函数 {name} 时发生错误: {e}")
|
|
||||||
traceback.print_exc()
|
|
||||||
return f"error occurred when executing function {name}: {e}"
|
|
||||||
finally:
|
|
||||||
plugin = None
|
|
||||||
|
|
||||||
for p in self.ap.plugin_mgr.plugins():
|
|
||||||
if function in p.content_functions:
|
|
||||||
plugin = p
|
|
||||||
break
|
|
||||||
|
|
||||||
if plugin is not None:
|
|
||||||
|
|
||||||
await self.ap.ctr_mgr.usage.post_function_record(
|
|
||||||
plugin={
|
|
||||||
"name": plugin.plugin_name,
|
|
||||||
"remote": plugin.plugin_source,
|
|
||||||
"version": plugin.plugin_version,
|
|
||||||
"author": plugin.plugin_author,
|
|
||||||
},
|
|
||||||
function_name=function.name,
|
|
||||||
function_description=function.description,
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
semantic_version = "v3.4.10"
|
semantic_version = "v3.4.14.1"
|
||||||
|
|
||||||
debug_mode = False
|
debug_mode = False
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ import asyncio
|
|||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def get_gewechat_image_base64(
|
async def get_gewechat_image_base64(
|
||||||
gewechat_url: str,
|
gewechat_url: str,
|
||||||
gewechat_file_url: str,
|
gewechat_file_url: str,
|
||||||
@@ -67,6 +70,7 @@ async def get_gewechat_image_base64(
|
|||||||
}
|
}
|
||||||
) as response:
|
) as response:
|
||||||
if response.status != 200:
|
if response.status != 200:
|
||||||
|
# print(response)
|
||||||
raise Exception(f"获取gewechat图片下载失败: {await response.text()}")
|
raise Exception(f"获取gewechat图片下载失败: {await response.text()}")
|
||||||
|
|
||||||
resp_data = await response.json()
|
resp_data = await response.json()
|
||||||
@@ -108,6 +112,9 @@ async def get_gewechat_image_base64(
|
|||||||
raise Exception(f"获取图片失败: {str(e)}") from e
|
raise Exception(f"获取图片失败: {str(e)}") from e
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def get_wecom_image_base64(pic_url: str) -> tuple[str, str]:
|
async def get_wecom_image_base64(pic_url: str) -> tuple[str, str]:
|
||||||
"""
|
"""
|
||||||
下载企业微信图片并转换为 base64
|
下载企业微信图片并转换为 base64
|
||||||
@@ -205,4 +212,19 @@ async def extract_b64_and_format(image_base64_data: str) -> typing.Tuple[str, st
|
|||||||
"""
|
"""
|
||||||
base64_str = image_base64_data.split(',')[-1]
|
base64_str = image_base64_data.split(',')[-1]
|
||||||
image_format = image_base64_data.split(':')[-1].split(';')[0].split('/')[-1]
|
image_format = image_base64_data.split(':')[-1].split(';')[0].split('/')[-1]
|
||||||
return base64_str, image_format
|
return base64_str, image_format
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async def get_slack_image_to_base64(pic_url:str, bot_token:str):
|
||||||
|
headers = {"Authorization": f"Bearer {bot_token}"}
|
||||||
|
try:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(pic_url, headers=headers) as resp:
|
||||||
|
image_data = await resp.read()
|
||||||
|
return base64.b64encode(image_data).decode('utf-8')
|
||||||
|
except Exception as e:
|
||||||
|
raise(e)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ gewechat-client
|
|||||||
dingtalk_stream
|
dingtalk_stream
|
||||||
dashscope
|
dashscope
|
||||||
python-telegram-bot
|
python-telegram-bot
|
||||||
|
certifi
|
||||||
|
mcp
|
||||||
|
slack_sdk
|
||||||
|
telegramify-markdown
|
||||||
# indirect
|
# indirect
|
||||||
taskgroup==0.0.0a4
|
taskgroup==0.0.0a4
|
||||||
|
python-socks
|
||||||
@@ -166,61 +166,72 @@
|
|||||||
{
|
{
|
||||||
"name": "glm-4-plus",
|
"name": "glm-4-plus",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4-0520",
|
"name": "glm-4-0520",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4-air",
|
"name": "glm-4-air",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4-airx",
|
"name": "glm-4-airx",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4-long",
|
"name": "glm-4-long",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4-flashx",
|
"name": "glm-4-flashx",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4-flash",
|
"name": "glm-4-flash",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai"
|
"token_mgr": "zhipuai",
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4v-plus",
|
"name": "glm-4v-plus",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai",
|
"token_mgr": "zhipuai",
|
||||||
"vision_supported": true
|
"vision_supported": true,
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4v",
|
"name": "glm-4v",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai",
|
"token_mgr": "zhipuai",
|
||||||
"vision_supported": true
|
"vision_supported": true,
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-4v-flash",
|
"name": "glm-4v-flash",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai",
|
"token_mgr": "zhipuai",
|
||||||
"vision_supported": true
|
"vision_supported": true,
|
||||||
|
"tool_call_supported": true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "glm-zero-preview",
|
"name": "glm-zero-preview",
|
||||||
"requester": "zhipuai-chat-completions",
|
"requester": "zhipuai-chat-completions",
|
||||||
"token_mgr": "zhipuai",
|
"token_mgr": "zhipuai",
|
||||||
"vision_supported": true
|
"vision_supported": true,
|
||||||
|
"tool_call_supported": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -16,7 +16,7 @@
|
|||||||
},
|
},
|
||||||
"income-msg-check": true,
|
"income-msg-check": true,
|
||||||
"ignore-rules": {
|
"ignore-rules": {
|
||||||
"prefix": ["/"],
|
"prefix": [],
|
||||||
"regexp": []
|
"regexp": []
|
||||||
},
|
},
|
||||||
"check-sensitive-words": true,
|
"check-sensitive-words": true,
|
||||||
|
|||||||
@@ -71,27 +71,47 @@
|
|||||||
"token": ""
|
"token": ""
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"adapter":"officialaccount",
|
"adapter": "officialaccount",
|
||||||
"enable": false,
|
"enable": false,
|
||||||
"token": "",
|
"token": "",
|
||||||
"EncodingAESKey":"",
|
"EncodingAESKey": "",
|
||||||
"AppID":"",
|
"AppID": "",
|
||||||
"AppSecret":"",
|
"AppSecret": "",
|
||||||
|
"Mode": "drop",
|
||||||
|
"LoadingMessage": "AI正在思考中,请发送任意内容获取回复。",
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"port": 2287
|
"port": 2287
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"adapter":"dingtalk",
|
"adapter": "dingtalk",
|
||||||
"enable": false,
|
"enable": false,
|
||||||
"client_id":"",
|
"client_id": "",
|
||||||
"client_secret":"",
|
"client_secret": "",
|
||||||
"robot_code":"",
|
"robot_code": "",
|
||||||
"robot_name":""
|
"robot_name": "",
|
||||||
|
"markdown_card": false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"adapter":"telegram",
|
"adapter": "telegram",
|
||||||
"enable": false,
|
"enable": false,
|
||||||
"token":""
|
"token": "",
|
||||||
|
"markdown_card": false
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"adapter": "slack",
|
||||||
|
"enable": false,
|
||||||
|
"bot_token": "",
|
||||||
|
"signing_secret": "",
|
||||||
|
"port": 2288
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"adapter": "wecomcs",
|
||||||
|
"enable": false,
|
||||||
|
"port": 2289,
|
||||||
|
"corpid": "",
|
||||||
|
"secret": "",
|
||||||
|
"token": "",
|
||||||
|
"EncodingAESKey": ""
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"track-function-calls": true,
|
"track-function-calls": true,
|
||||||
|
|||||||
@@ -31,6 +31,12 @@
|
|||||||
],
|
],
|
||||||
"volcark": [
|
"volcark": [
|
||||||
"xxxxxxxx"
|
"xxxxxxxx"
|
||||||
|
],
|
||||||
|
"modelscope": [
|
||||||
|
"xxxxxxxx"
|
||||||
|
],
|
||||||
|
"ppio": [
|
||||||
|
"xxxxxxxx"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"requester": {
|
"requester": {
|
||||||
@@ -95,12 +101,22 @@
|
|||||||
"args": {},
|
"args": {},
|
||||||
"base-url": "https://ark.cn-beijing.volces.com/api/v3",
|
"base-url": "https://ark.cn-beijing.volces.com/api/v3",
|
||||||
"timeout": 120
|
"timeout": 120
|
||||||
|
},
|
||||||
|
"modelscope-chat-completions": {
|
||||||
|
"base-url": "https://api-inference.modelscope.cn/v1",
|
||||||
|
"args": {},
|
||||||
|
"timeout": 120
|
||||||
|
},
|
||||||
|
"ppio-chat-completions": {
|
||||||
|
"base-url": "https://api.ppinfra.com/v3/openai",
|
||||||
|
"args": {},
|
||||||
|
"timeout": 120
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"model": "gpt-4o",
|
"model": "gpt-4o",
|
||||||
"prompt-mode": "normal",
|
"prompt-mode": "normal",
|
||||||
"prompt": {
|
"prompt": {
|
||||||
"default": ""
|
"default": "You are a helpful assistant."
|
||||||
},
|
},
|
||||||
"runner": "local-agent",
|
"runner": "local-agent",
|
||||||
"dify-service-api": {
|
"dify-service-api": {
|
||||||
@@ -138,5 +154,8 @@
|
|||||||
"date": "2023-08-10"
|
"date": "2023-08-10"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"mcp": {
|
||||||
|
"servers": []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "regex",
|
"format": "regex",
|
||||||
"pattern": "^(person|group)_(\\d)*$"
|
"pattern": "^(person|group)_.*$"
|
||||||
},
|
},
|
||||||
"default": []
|
"default": []
|
||||||
},
|
},
|
||||||
@@ -34,7 +34,7 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "regex",
|
"format": "regex",
|
||||||
"pattern": "^(person|group)_(\\d)*$"
|
"pattern": "^(person|group)_.*$"
|
||||||
},
|
},
|
||||||
"default": []
|
"default": []
|
||||||
}
|
}
|
||||||
@@ -99,7 +99,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"patternProperties": {
|
"patternProperties": {
|
||||||
"^\\d+$": {
|
"^.*$": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"at": {
|
"at": {
|
||||||
|
|||||||
@@ -385,6 +385,17 @@
|
|||||||
"default": "",
|
"default": "",
|
||||||
"description": "微信公众号的AppSecret"
|
"description": "微信公众号的AppSecret"
|
||||||
},
|
},
|
||||||
|
"Mode": {
|
||||||
|
"type": "string",
|
||||||
|
"default": "drop",
|
||||||
|
"description": "对于超过15s的响应的处理模式",
|
||||||
|
"enum": ["drop", "passive"]
|
||||||
|
},
|
||||||
|
"LoadingMessage": {
|
||||||
|
"type": "string",
|
||||||
|
"default": "AI正在思考中,请发送任意内容获取回复。",
|
||||||
|
"description": "当使用被动模式时,显示给用户的提示信息"
|
||||||
|
},
|
||||||
"host": {
|
"host": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "0.0.0.0",
|
"default": "0.0.0.0",
|
||||||
@@ -435,6 +446,11 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "",
|
"default": "",
|
||||||
"description": "钉钉的robot_name"
|
"description": "钉钉的robot_name"
|
||||||
|
},
|
||||||
|
"markdown_card": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": false,
|
||||||
|
"description": "是否使用 Markdown 卡片发送消息"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -455,6 +471,41 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"default": "",
|
"default": "",
|
||||||
"description": "Telegram 的 token"
|
"description": "Telegram 的 token"
|
||||||
|
},
|
||||||
|
"markdown_card": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": false,
|
||||||
|
"description": "是否使用 Markdown 卡片发送消息"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "Slack 适配器",
|
||||||
|
"description": "用于接入 Slack",
|
||||||
|
"properties": {
|
||||||
|
"adapter": {
|
||||||
|
"type": "string",
|
||||||
|
"const": "slack"
|
||||||
|
},
|
||||||
|
"enable": {
|
||||||
|
"type": "boolean",
|
||||||
|
"default": false,
|
||||||
|
"description": "是否启用此适配器"
|
||||||
|
},
|
||||||
|
"bot_token": {
|
||||||
|
"type": "string",
|
||||||
|
"default": "",
|
||||||
|
"description": "Slack 的 bot_token"
|
||||||
|
},
|
||||||
|
"signing_secret": {
|
||||||
|
"type": "string",
|
||||||
|
"default": "",
|
||||||
|
"description": "Slack 的 signing_secret"
|
||||||
|
},
|
||||||
|
"port": {
|
||||||
|
"type": "integer",
|
||||||
|
"default": 2288,
|
||||||
|
"description": "监听的端口"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -368,7 +368,7 @@
|
|||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "默认情景预设",
|
"title": "默认情景预设",
|
||||||
"description": "设置默认情景预设。值为空字符串时,将不使用情景预设(人格)",
|
"description": "设置默认情景预设。值为空字符串时,将不使用情景预设(人格)",
|
||||||
"default": ""
|
"default": "You are a helpful assistant."
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"patternProperties": {
|
"patternProperties": {
|
||||||
@@ -520,6 +520,87 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
"mcp": {
|
||||||
|
"type": "object",
|
||||||
|
"title": "MCP 配置",
|
||||||
|
"properties": {
|
||||||
|
"servers": {
|
||||||
|
"type": "array",
|
||||||
|
"title": "MCP 服务器配置",
|
||||||
|
"default": [],
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"oneOf": [
|
||||||
|
{
|
||||||
|
"title": "Stdio 模式服务器",
|
||||||
|
"properties": {
|
||||||
|
"mode": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "模式",
|
||||||
|
"const": "stdio"
|
||||||
|
},
|
||||||
|
"enable": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "启用"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "名称"
|
||||||
|
},
|
||||||
|
"command": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "启动命令"
|
||||||
|
},
|
||||||
|
"args": {
|
||||||
|
"type": "array",
|
||||||
|
"title": "启动参数",
|
||||||
|
"items": {
|
||||||
|
"type": "string"
|
||||||
|
},
|
||||||
|
"default": []
|
||||||
|
},
|
||||||
|
"env": {
|
||||||
|
"type": "object",
|
||||||
|
"default": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "SSE 模式服务器",
|
||||||
|
"properties": {
|
||||||
|
"mode": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "模式",
|
||||||
|
"const": "sse"
|
||||||
|
},
|
||||||
|
"enable": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "启用"
|
||||||
|
},
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "名称"
|
||||||
|
},
|
||||||
|
"url": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "URL"
|
||||||
|
},
|
||||||
|
"headers": {
|
||||||
|
"type": "object",
|
||||||
|
"default": {}
|
||||||
|
},
|
||||||
|
"timeout": {
|
||||||
|
"type": "number",
|
||||||
|
"title": "请求超时时间",
|
||||||
|
"default": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
"items": {
|
"items": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"format": "regex",
|
"format": "regex",
|
||||||
"pattern": "^(person|group)_(\\d+)$"
|
"pattern": "^(person|group)_.*$"
|
||||||
},
|
},
|
||||||
"default": []
|
"default": []
|
||||||
},
|
},
|
||||||
@@ -52,7 +52,7 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"patternProperties": {
|
"patternProperties": {
|
||||||
"^(person|group)_(\\d+)$": {
|
"^(person|group)_.*$": {
|
||||||
"type": "integer"
|
"type": "integer"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user