mirror of
https://github.com/zhayujie/chatgpt-on-wechat.git
synced 2026-05-08 20:31:04 +08:00
Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 16324e7283 | |||
| 9f7e2e1572 | |||
| 857ce1d530 | |||
| be0d72775d | |||
| 7832a2495b | |||
| 0506b7f735 | |||
| 4c0b7942f0 | |||
| 651c840c4a | |||
| 2a351ca415 | |||
| 49b7106d71 | |||
| 8bf633f539 | |||
| 0f8efcb4b0 | |||
| c567641c5c | |||
| bdc3820382 | |||
| 33a69a7907 | |||
| a4d0e9bbc3 | |||
| afc753e1d2 | |||
| e641a41224 | |||
| 79305c0632 | |||
| ef2ce3f09d | |||
| 71c18c04fc | |||
| cf84e57f81 | |||
| 9421d44579 | |||
| 5cd2ae8cc8 |
@@ -40,7 +40,7 @@ DEMO视频:https://cdn.link-ai.tech/doc/cow_demo.mp4
|
||||
|
||||
**企业服务和产品咨询** 可联系产品顾问:
|
||||
|
||||
<img width="160" src="https://img-1317903499.cos.ap-guangzhou.myqcloud.com/docs/github-product-consult.png">
|
||||
<img width="160" src="https://cdn.link-ai.tech/consultant-s.jpg">
|
||||
|
||||
<br>
|
||||
|
||||
@@ -144,6 +144,7 @@ pip3 install -r requirements-optional.txt
|
||||
{
|
||||
"model": "gpt-3.5-turbo", # 模型名称, 支持 gpt-3.5-turbo, gpt-4, gpt-4-turbo, wenxin, xunfei, glm-4, claude-3-haiku, moonshot
|
||||
"open_ai_api_key": "YOUR API KEY", # 如果使用openAI模型则填入上面创建的 OpenAI API KEY
|
||||
"open_ai_api_base": "https://api.openai.com/v1", # OpenAI接口代理地址
|
||||
"proxy": "", # 代理客户端的ip和端口,国内环境开启代理的需要填写该项,如 "127.0.0.1:7890"
|
||||
"single_chat_prefix": ["bot", "@bot"], # 私聊时文本需要包含该前缀才能触发机器人回复
|
||||
"single_chat_reply_prefix": "[bot] ", # 私聊时自动回复的前缀,用于区分真人
|
||||
@@ -275,7 +276,7 @@ sudo docker logs -f chatgpt-on-wechat
|
||||
volumes:
|
||||
- ./config.json:/app/plugins/config.json
|
||||
```
|
||||
|
||||
**注**:采用docker方式部署的详细教程可以参考:[docker部署CoW项目](https://www.wangpc.cc/ai/docker-deploy-cow/)
|
||||
### 4. Railway部署
|
||||
|
||||
> Railway 每月提供5刀和最多500小时的免费额度。 (07.11更新: 目前大部分账号已无法免费部署)
|
||||
|
||||
@@ -27,7 +27,7 @@ def sigterm_handler_wrap(_signo):
|
||||
|
||||
def start_channel(channel_name: str):
|
||||
channel = channel_factory.create_channel(channel_name)
|
||||
if channel_name in ["wx", "wxy", "terminal", "wechatmp", "wechatmp_service", "wechatcom_app", "wework",
|
||||
if channel_name in ["wx", "wxy", "terminal", "wechatmp","web", "wechatmp_service", "wechatcom_app", "wework",
|
||||
const.FEISHU, const.DINGTALK]:
|
||||
PluginManager().load_plugins()
|
||||
|
||||
|
||||
@@ -21,6 +21,9 @@ def create_channel(channel_type) -> Channel:
|
||||
elif channel_type == "terminal":
|
||||
from channel.terminal.terminal_channel import TerminalChannel
|
||||
ch = TerminalChannel()
|
||||
elif channel_type == 'web':
|
||||
from channel.web.web_channel import WebChannel
|
||||
ch = WebChannel()
|
||||
elif channel_type == "wechatmp":
|
||||
from channel.wechatmp.wechatmp_channel import WechatMPChannel
|
||||
ch = WechatMPChannel(passive_reply=True)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Web channel
|
||||
使用SSE(Server-Sent Events,服务器推送事件)实现,提供了一个默认的网页。也可以自己实现加入api
|
||||
|
||||
#使用方法
|
||||
- 在配置文件中channel_type填入web即可
|
||||
- 访问地址 http://localhost:9899
|
||||
- port可以在配置项 web_port中设置
|
||||
@@ -0,0 +1,165 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Chat</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh; /* 占据所有高度 */
|
||||
margin: 0;
|
||||
/* background-color: #f8f9fa; */
|
||||
}
|
||||
#chat-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
width: 100%;
|
||||
max-width: 500px;
|
||||
margin: auto;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
|
||||
flex: 1; /* 使聊天容器占据剩余空间 */
|
||||
}
|
||||
#messages {
|
||||
flex-direction: column;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 10px;
|
||||
overflow-y: auto;
|
||||
border-bottom: 1px solid #ccc;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin: 5px 0; /* 间隔 */
|
||||
padding: 10px 15px; /* 内边距 */
|
||||
border-radius: 15px; /* 圆角 */
|
||||
max-width: 80%; /* 限制最大宽度 */
|
||||
min-width: 80px; /* 设置最小宽度 */
|
||||
min-height: 40px; /* 设置最小高度 */
|
||||
word-wrap: break-word; /* 自动换行 */
|
||||
position: relative; /* 时间戳定位 */
|
||||
display: inline-block; /* 内容自适应宽度 */
|
||||
box-sizing: border-box; /* 包括内边距和边框 */
|
||||
flex-shrink: 0; /* 禁止高度被压缩 */
|
||||
word-wrap: break-word; /* 自动换行,防止单行过长 */
|
||||
white-space: normal; /* 允许正常换行 */
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bot {
|
||||
background-color: #f1f1f1; /* 灰色背景 */
|
||||
color: black; /* 黑色字体 */
|
||||
align-self: flex-start; /* 左对齐 */
|
||||
margin-right: auto; /* 确保消息靠左 */
|
||||
text-align: left; /* 内容左对齐 */
|
||||
}
|
||||
|
||||
.user {
|
||||
background-color: #2bc840; /* 蓝色背景 */
|
||||
align-self: flex-end; /* 右对齐 */
|
||||
margin-left: auto; /* 确保消息靠右 */
|
||||
text-align: left; /* 内容左对齐 */
|
||||
}
|
||||
.timestamp {
|
||||
font-size: 0.8em; /* 时间戳字体大小 */
|
||||
color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
|
||||
margin-bottom: 5px; /* 时间戳下方间距 */
|
||||
display: block; /* 时间戳独占一行 */
|
||||
}
|
||||
#input-container {
|
||||
display: flex;
|
||||
padding: 10px;
|
||||
background-color: #ffffff;
|
||||
border-top: 1px solid #ccc;
|
||||
}
|
||||
#input {
|
||||
flex: 1;
|
||||
padding: 10px;
|
||||
border: 1px solid #ccc;
|
||||
border-radius: 5px;
|
||||
margin-right: 10px;
|
||||
}
|
||||
#send {
|
||||
padding: 10px;
|
||||
border: none;
|
||||
background-color: #007bff;
|
||||
color: white;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
#send:hover {
|
||||
background-color: #0056b3;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="chat-container">
|
||||
<div id="messages"></div>
|
||||
<div id="input-container">
|
||||
<input type="text" id="input" placeholder="输入消息..." />
|
||||
<button id="send">发送</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const messagesDiv = document.getElementById('messages');
|
||||
const input = document.getElementById('input');
|
||||
const sendButton = document.getElementById('send');
|
||||
|
||||
// 生成唯一的 user_id
|
||||
const userId = 'user_' + Math.random().toString(36).substr(2, 9);
|
||||
|
||||
// 连接 SSE
|
||||
const eventSource = new EventSource(`/sse/${userId}`);
|
||||
|
||||
eventSource.onmessage = function(event) {
|
||||
const message = JSON.parse(event.data);
|
||||
const messageDiv = document.createElement('div');
|
||||
messageDiv.className = 'message bot';
|
||||
const timestamp = new Date(message.timestamp).toLocaleTimeString(); // 假设消息中有时间戳
|
||||
messageDiv.innerHTML = `<div class="timestamp">${timestamp}</div>${message.content}`; // 显示时间
|
||||
messagesDiv.appendChild(messageDiv);
|
||||
messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
|
||||
};
|
||||
|
||||
sendButton.onclick = function() {
|
||||
sendMessage();
|
||||
};
|
||||
|
||||
input.addEventListener('keypress', function(event) {
|
||||
if (event.key === 'Enter') {
|
||||
sendMessage();
|
||||
event.preventDefault(); // 防止换行
|
||||
}
|
||||
});
|
||||
|
||||
function sendMessage() {
|
||||
const userMessage = input.value;
|
||||
if (userMessage) {
|
||||
const timestamp = new Date().toISOString(); // 获取当前时间戳
|
||||
fetch('/message', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ user_id: userId, message: userMessage, timestamp: timestamp }) // 发送时间戳
|
||||
});
|
||||
const messageDiv = document.createElement('div');
|
||||
messageDiv.className = 'message user';
|
||||
const userTimestamp = new Date().toLocaleTimeString(); // 获取当前时间
|
||||
messageDiv.innerHTML = `<div class="timestamp">${userTimestamp}</div>${userMessage}`; // 显示时间
|
||||
messagesDiv.appendChild(messageDiv);
|
||||
messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
|
||||
input.value = ''; // 清空输入框
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,204 @@
|
||||
import sys
|
||||
import time
|
||||
import web
|
||||
import json
|
||||
from queue import Queue
|
||||
from bridge.context import *
|
||||
from bridge.reply import Reply, ReplyType
|
||||
from channel.chat_channel import ChatChannel, check_prefix
|
||||
from channel.chat_message import ChatMessage
|
||||
from common.log import logger
|
||||
from common.singleton import singleton
|
||||
from config import conf
|
||||
import os
|
||||
|
||||
|
||||
class WebMessage(ChatMessage):
|
||||
def __init__(
|
||||
self,
|
||||
msg_id,
|
||||
content,
|
||||
ctype=ContextType.TEXT,
|
||||
from_user_id="User",
|
||||
to_user_id="Chatgpt",
|
||||
other_user_id="Chatgpt",
|
||||
):
|
||||
self.msg_id = msg_id
|
||||
self.ctype = ctype
|
||||
self.content = content
|
||||
self.from_user_id = from_user_id
|
||||
self.to_user_id = to_user_id
|
||||
self.other_user_id = other_user_id
|
||||
|
||||
|
||||
@singleton
|
||||
class WebChannel(ChatChannel):
|
||||
NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE]
|
||||
_instance = None
|
||||
|
||||
# def __new__(cls):
|
||||
# if cls._instance is None:
|
||||
# cls._instance = super(WebChannel, cls).__new__(cls)
|
||||
# return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.message_queues = {} # 为每个用户存储一个消息队列
|
||||
self.msg_id_counter = 0 # 添加消息ID计数器
|
||||
|
||||
def _generate_msg_id(self):
|
||||
"""生成唯一的消息ID"""
|
||||
self.msg_id_counter += 1
|
||||
return str(int(time.time())) + str(self.msg_id_counter)
|
||||
|
||||
def send(self, reply: Reply, context: Context):
|
||||
try:
|
||||
if reply.type == ReplyType.IMAGE:
|
||||
from PIL import Image
|
||||
|
||||
image_storage = reply.content
|
||||
image_storage.seek(0)
|
||||
img = Image.open(image_storage)
|
||||
print("<IMAGE>")
|
||||
img.show()
|
||||
elif reply.type == ReplyType.IMAGE_URL:
|
||||
import io
|
||||
|
||||
import requests
|
||||
from PIL import Image
|
||||
|
||||
img_url = reply.content
|
||||
pic_res = requests.get(img_url, stream=True)
|
||||
image_storage = io.BytesIO()
|
||||
for block in pic_res.iter_content(1024):
|
||||
image_storage.write(block)
|
||||
image_storage.seek(0)
|
||||
img = Image.open(image_storage)
|
||||
print(img_url)
|
||||
img.show()
|
||||
else:
|
||||
print(reply.content)
|
||||
|
||||
# 获取用户ID,如果没有则使用默认值
|
||||
# user_id = getattr(context.get("session", None), "session_id", "default_user")
|
||||
user_id = context["receiver"]
|
||||
# 确保用户有对应的消息队列
|
||||
if user_id not in self.message_queues:
|
||||
self.message_queues[user_id] = Queue()
|
||||
|
||||
# 将消息放入对应用户的队列
|
||||
message_data = {
|
||||
"type": str(reply.type),
|
||||
"content": reply.content,
|
||||
"timestamp": time.time()
|
||||
}
|
||||
self.message_queues[user_id].put(message_data)
|
||||
logger.debug(f"Message queued for user {user_id}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in send method: {e}")
|
||||
raise
|
||||
|
||||
def sse_handler(self, user_id):
|
||||
"""
|
||||
Handle Server-Sent Events (SSE) for real-time communication.
|
||||
"""
|
||||
web.header('Content-Type', 'text/event-stream')
|
||||
web.header('Cache-Control', 'no-cache')
|
||||
web.header('Connection', 'keep-alive')
|
||||
|
||||
# 确保用户有消息队列
|
||||
if user_id not in self.message_queues:
|
||||
self.message_queues[user_id] = Queue()
|
||||
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
# 发送心跳
|
||||
yield f": heartbeat\n\n"
|
||||
|
||||
# 非阻塞方式获取消息
|
||||
if not self.message_queues[user_id].empty():
|
||||
message = self.message_queues[user_id].get_nowait()
|
||||
yield f"data: {json.dumps(message)}\n\n"
|
||||
time.sleep(0.5)
|
||||
except Exception as e:
|
||||
logger.error(f"SSE Error: {e}")
|
||||
break
|
||||
finally:
|
||||
# 清理资源
|
||||
if user_id in self.message_queues:
|
||||
# 只有当队列为空时才删除
|
||||
if self.message_queues[user_id].empty():
|
||||
del self.message_queues[user_id]
|
||||
|
||||
def post_message(self):
|
||||
"""
|
||||
Handle incoming messages from users via POST request.
|
||||
"""
|
||||
try:
|
||||
data = web.data() # 获取原始POST数据
|
||||
json_data = json.loads(data)
|
||||
user_id = json_data.get('user_id', 'default_user')
|
||||
prompt = json_data.get('message', '')
|
||||
except json.JSONDecodeError:
|
||||
return json.dumps({"status": "error", "message": "Invalid JSON"})
|
||||
except Exception as e:
|
||||
return json.dumps({"status": "error", "message": str(e)})
|
||||
|
||||
if not prompt:
|
||||
return json.dumps({"status": "error", "message": "No message provided"})
|
||||
|
||||
try:
|
||||
msg_id = self._generate_msg_id()
|
||||
context = self._compose_context(ContextType.TEXT, prompt, msg=WebMessage(msg_id,
|
||||
prompt,
|
||||
from_user_id=user_id,
|
||||
other_user_id = user_id
|
||||
))
|
||||
context["isgroup"] = False
|
||||
# context["session"] = web.storage(session_id=user_id)
|
||||
|
||||
if not context:
|
||||
return json.dumps({"status": "error", "message": "Failed to process message"})
|
||||
|
||||
self.produce(context)
|
||||
return json.dumps({"status": "success", "message": "Message received"})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error processing message: {e}")
|
||||
return json.dumps({"status": "error", "message": "Internal server error"})
|
||||
|
||||
def chat_page(self):
|
||||
"""Serve the chat HTML page."""
|
||||
file_path = os.path.join(os.path.dirname(__file__), 'chat.html') # 使用绝对路径
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
return f.read()
|
||||
|
||||
def startup(self):
|
||||
logger.setLevel("WARN")
|
||||
print("\nWeb Channel is running. Send POST requests to /message to send messages.")
|
||||
|
||||
urls = (
|
||||
'/sse/(.+)', 'SSEHandler', # 修改路由以接收用户ID
|
||||
'/message', 'MessageHandler',
|
||||
'/chat', 'ChatHandler',
|
||||
)
|
||||
port = conf().get("web_port", 9899)
|
||||
app = web.application(urls, globals(), autoreload=False)
|
||||
web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
|
||||
|
||||
|
||||
class SSEHandler:
|
||||
def GET(self, user_id):
|
||||
return WebChannel().sse_handler(user_id)
|
||||
|
||||
|
||||
class MessageHandler:
|
||||
def POST(self):
|
||||
return WebChannel().post_message()
|
||||
|
||||
|
||||
class ChatHandler:
|
||||
def GET(self):
|
||||
return WebChannel().chat_page()
|
||||
+3
-1
@@ -59,6 +59,8 @@ LINKAI_4o = "linkai-4o"
|
||||
GEMINI_PRO = "gemini-1.0-pro"
|
||||
GEMINI_15_flash = "gemini-1.5-flash"
|
||||
GEMINI_15_PRO = "gemini-1.5-pro"
|
||||
GEMINI_20_flash_exp = "gemini-2.0-flash-exp"
|
||||
|
||||
|
||||
GLM_4 = "glm-4"
|
||||
GLM_4_PLUS = "glm-4-plus"
|
||||
@@ -87,7 +89,7 @@ MODEL_LIST = [
|
||||
XUNFEI,
|
||||
ZHIPU_AI, GLM_4, GLM_4_PLUS, GLM_4_flash, GLM_4_LONG, GLM_4_ALLTOOLS, GLM_4_0520, GLM_4_AIR, GLM_4_AIRX,
|
||||
MOONSHOT, MiniMax,
|
||||
GEMINI, GEMINI_PRO, GEMINI_15_flash, GEMINI_15_PRO,
|
||||
GEMINI, GEMINI_PRO, GEMINI_15_flash, GEMINI_15_PRO,GEMINI_20_flash_exp,
|
||||
CLAUDE_3_OPUS, CLAUDE_3_OPUS_0229, CLAUDE_35_SONNET, CLAUDE_35_SONNET_1022, CLAUDE_35_SONNET_0620, CLAUDE_3_SONNET, CLAUDE_3_HAIKU, "claude", "claude-3-haiku", "claude-3-sonnet", "claude-3-opus", "claude-3.5-sonnet",
|
||||
"moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k",
|
||||
QWEN, QWEN_TURBO, QWEN_PLUS, QWEN_MAX,
|
||||
|
||||
@@ -2,7 +2,7 @@ from bridge.context import Context, ContextType
|
||||
from bridge.reply import Reply, ReplyType
|
||||
from common.log import logger
|
||||
from linkai import LinkAIClient, PushMsg
|
||||
from config import conf, pconf, plugin_config, available_setting
|
||||
from config import conf, pconf, plugin_config, available_setting, write_plugin_config
|
||||
from plugins import PluginManager
|
||||
import time
|
||||
|
||||
@@ -51,10 +51,10 @@ class ChatClient(LinkAIClient):
|
||||
local_config["voice_reply_voice"] = False
|
||||
|
||||
if config.get("admin_password"):
|
||||
if not plugin_config.get("Godcmd"):
|
||||
plugin_config["Godcmd"] = {"password": config.get("admin_password"), "admin_users": []}
|
||||
if not pconf("Godcmd"):
|
||||
write_plugin_config({"Godcmd": {"password": config.get("admin_password"), "admin_users": []} })
|
||||
else:
|
||||
plugin_config["Godcmd"]["password"] = config.get("admin_password")
|
||||
pconf("Godcmd")["password"] = config.get("admin_password")
|
||||
PluginManager().instances["GODCMD"].reload()
|
||||
|
||||
if config.get("group_app_map") and pconf("linkai"):
|
||||
|
||||
@@ -179,6 +179,7 @@ available_setting = {
|
||||
"Minimax_api_key": "",
|
||||
"Minimax_group_id": "",
|
||||
"Minimax_base_url": "",
|
||||
"web_port": 9899,
|
||||
}
|
||||
|
||||
|
||||
@@ -341,6 +342,14 @@ def write_plugin_config(pconf: dict):
|
||||
for k in pconf:
|
||||
plugin_config[k.lower()] = pconf[k]
|
||||
|
||||
def remove_plugin_config(name: str):
|
||||
"""
|
||||
移除待重新加载的插件全局配置
|
||||
:param name: 待重载的插件名
|
||||
"""
|
||||
global plugin_config
|
||||
plugin_config.pop(name.lower(), None)
|
||||
|
||||
|
||||
def pconf(plugin_name: str) -> dict:
|
||||
"""
|
||||
|
||||
@@ -477,7 +477,7 @@ class Godcmd(Plugin):
|
||||
return model
|
||||
|
||||
def reload(self):
|
||||
gconf = plugin_config[self.name]
|
||||
gconf = pconf(self.name)
|
||||
if gconf:
|
||||
if gconf.get("password"):
|
||||
self.password = gconf["password"]
|
||||
|
||||
@@ -201,12 +201,14 @@ class LinkAI(Plugin):
|
||||
group_name = context.get("msg").from_user_nickname
|
||||
app_code = self._fetch_group_app_code(group_name)
|
||||
if app_code:
|
||||
remote_enabled = Util.fetch_app_plugin(app_code, "内容总结")
|
||||
if context.type.name in ["FILE", "SHARING"]:
|
||||
remote_enabled = Util.fetch_app_plugin(app_code, "内容总结")
|
||||
else:
|
||||
# 非群聊场景使用全局app_code
|
||||
app_code = conf().get("linkai_app_code")
|
||||
if app_code:
|
||||
remote_enabled = Util.fetch_app_plugin(app_code, "内容总结")
|
||||
if context.type.name in ["FILE", "SHARING"]:
|
||||
remote_enabled = Util.fetch_app_plugin(app_code, "内容总结")
|
||||
|
||||
# 基础条件:总开关开启且消息类型符合要求
|
||||
base_enabled = (
|
||||
@@ -289,7 +291,7 @@ class LinkAI(Plugin):
|
||||
plugin_conf = json.load(f)
|
||||
plugin_conf["midjourney"]["enabled"] = False
|
||||
plugin_conf["summary"]["enabled"] = False
|
||||
plugin_config["linkai"] = plugin_conf
|
||||
write_plugin_config({"linkai": plugin_conf})
|
||||
return plugin_conf
|
||||
except Exception as e:
|
||||
logger.exception(e)
|
||||
|
||||
@@ -12,11 +12,14 @@ class LinkSummary:
|
||||
def summary_file(self, file_path: str, app_code: str):
|
||||
file_body = {
|
||||
"file": open(file_path, "rb"),
|
||||
"name": file_path.split("/")[-1],
|
||||
"name": file_path.split("/")[-1]
|
||||
}
|
||||
body = {
|
||||
"app_code": app_code
|
||||
}
|
||||
url = self.base_url() + "/v1/summary/file"
|
||||
res = requests.post(url, headers=self.headers(), files=file_body, timeout=(5, 300))
|
||||
logger.info(f"[LinkSum] file summary, app_code={app_code}")
|
||||
res = requests.post(url, headers=self.headers(), files=file_body, data=body, timeout=(5, 300))
|
||||
return self._parse_summary_res(res)
|
||||
|
||||
def summary_url(self, url: str, app_code: str):
|
||||
@@ -25,6 +28,7 @@ class LinkSummary:
|
||||
"url": url,
|
||||
"app_code": app_code
|
||||
}
|
||||
logger.info(f"[LinkSum] url summary, app_code={app_code}")
|
||||
res = requests.post(url=self.base_url() + "/v1/summary/url", headers=self.headers(), json=body, timeout=(5, 180))
|
||||
return self._parse_summary_res(res)
|
||||
|
||||
@@ -50,7 +54,7 @@ class LinkSummary:
|
||||
def _parse_summary_res(self, res):
|
||||
if res.status_code == 200:
|
||||
res = res.json()
|
||||
logger.debug(f"[LinkSum] url summary, res={res}")
|
||||
logger.debug(f"[LinkSum] summary result, res={res}")
|
||||
if res.get("code") == 200:
|
||||
data = res.get("data")
|
||||
return {
|
||||
|
||||
+16
-13
@@ -31,17 +31,20 @@ class Util:
|
||||
|
||||
@staticmethod
|
||||
def fetch_app_plugin(app_code: str, plugin_name: str) -> bool:
|
||||
headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
|
||||
# do http request
|
||||
base_url = conf().get("linkai_api_base", "https://api.link-ai.tech")
|
||||
params = {"app_code": app_code}
|
||||
res = requests.get(url=base_url + "/v1/app/info", params=params, headers=headers, timeout=(5, 10))
|
||||
if res.status_code == 200:
|
||||
plugins = res.json().get("data").get("plugins")
|
||||
for plugin in plugins:
|
||||
if plugin.get("name") and plugin.get("name") == plugin_name:
|
||||
return True
|
||||
return False
|
||||
else:
|
||||
logger.warning(f"[LinkAI] find app info exception, res={res}")
|
||||
try:
|
||||
headers = {"Authorization": "Bearer " + conf().get("linkai_api_key")}
|
||||
# do http request
|
||||
base_url = conf().get("linkai_api_base", "https://api.link-ai.tech")
|
||||
params = {"app_code": app_code}
|
||||
res = requests.get(url=base_url + "/v1/app/info", params=params, headers=headers, timeout=(5, 10))
|
||||
if res.status_code == 200:
|
||||
plugins = res.json().get("data").get("plugins")
|
||||
for plugin in plugins:
|
||||
if plugin.get("name") and plugin.get("name") == plugin_name:
|
||||
return True
|
||||
return False
|
||||
else:
|
||||
logger.warning(f"[LinkAI] find app info exception, res={res}")
|
||||
return False
|
||||
except Exception as e:
|
||||
return False
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
import os
|
||||
import json
|
||||
from config import pconf, plugin_config, conf
|
||||
from config import pconf, plugin_config, conf, write_plugin_config
|
||||
from common.log import logger
|
||||
|
||||
|
||||
@@ -24,13 +24,13 @@ class Plugin:
|
||||
plugin_conf = json.load(f)
|
||||
|
||||
# 写入全局配置内存
|
||||
plugin_config[self.name] = plugin_conf
|
||||
write_plugin_config({self.name: plugin_conf})
|
||||
logger.debug(f"loading plugin config, plugin_name={self.name}, conf={plugin_conf}")
|
||||
return plugin_conf
|
||||
|
||||
def save_config(self, config: dict):
|
||||
try:
|
||||
plugin_config[self.name] = config
|
||||
write_plugin_config({self.name: config})
|
||||
# 写入全局配置
|
||||
global_config_path = "./plugins/config.json"
|
||||
if os.path.exists(global_config_path):
|
||||
|
||||
@@ -9,7 +9,7 @@ import sys
|
||||
from common.log import logger
|
||||
from common.singleton import singleton
|
||||
from common.sorted_dict import SortedDict
|
||||
from config import conf, write_plugin_config
|
||||
from config import conf, remove_plugin_config, write_plugin_config
|
||||
|
||||
from .event import *
|
||||
|
||||
@@ -151,6 +151,8 @@ class PluginManager:
|
||||
self.disable_plugin(name)
|
||||
failed_plugins.append(name)
|
||||
continue
|
||||
if name in self.instances:
|
||||
self.instances[name].handlers.clear()
|
||||
self.instances[name] = instance
|
||||
for event in instance.handlers:
|
||||
if event not in self.listening_plugins:
|
||||
@@ -161,10 +163,13 @@ class PluginManager:
|
||||
|
||||
def reload_plugin(self, name: str):
|
||||
name = name.upper()
|
||||
remove_plugin_config(name)
|
||||
if name in self.instances:
|
||||
for event in self.listening_plugins:
|
||||
if name in self.listening_plugins[event]:
|
||||
self.listening_plugins[event].remove(name)
|
||||
if name in self.instances:
|
||||
self.instances[name].handlers.clear()
|
||||
del self.instances[name]
|
||||
self.activate_plugins()
|
||||
return True
|
||||
|
||||
@@ -180,6 +180,7 @@ class Role(Plugin):
|
||||
e_context["reply"] = reply
|
||||
e_context.action = EventAction.BREAK_PASS
|
||||
else:
|
||||
e_context["context"]["generate_breaked_by"] = EventAction.BREAK
|
||||
prompt = self.roleplays[sessionid].action(content)
|
||||
e_context["context"].type = ContextType.TEXT
|
||||
e_context["context"].content = prompt
|
||||
|
||||
@@ -12,10 +12,6 @@
|
||||
"url": "https://github.com/lanvent/plugin_summary.git",
|
||||
"desc": "总结聊天记录的插件"
|
||||
},
|
||||
"timetask": {
|
||||
"url": "https://github.com/haikerapples/timetask.git",
|
||||
"desc": "一款定时任务系统的插件"
|
||||
},
|
||||
"Apilot": {
|
||||
"url": "https://github.com/6vision/Apilot.git",
|
||||
"desc": "通过api直接查询早报、热榜、快递、天气等实用信息的插件"
|
||||
|
||||
Reference in New Issue
Block a user