Skip to content

Commit 857ce1d

Browse files
authored
Merge pull request #2398 from stonyz/web-channel
增加web channel
2 parents be0d727 + 71c18c0 commit 857ce1d

File tree

6 files changed

+381
-1
lines changed

6 files changed

+381
-1
lines changed

app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def func(_signo, _stack_frame):
2727

2828
def start_channel(channel_name: str):
2929
channel = channel_factory.create_channel(channel_name)
30-
if channel_name in ["wx", "wxy", "terminal", "wechatmp", "wechatmp_service", "wechatcom_app", "wework",
30+
if channel_name in ["wx", "wxy", "terminal", "wechatmp","web", "wechatmp_service", "wechatcom_app", "wework",
3131
const.FEISHU, const.DINGTALK]:
3232
PluginManager().load_plugins()
3333

channel/channel_factory.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ def create_channel(channel_type) -> Channel:
2121
elif channel_type == "terminal":
2222
from channel.terminal.terminal_channel import TerminalChannel
2323
ch = TerminalChannel()
24+
elif channel_type == 'web':
25+
from channel.web.web_channel import WebChannel
26+
ch = WebChannel()
2427
elif channel_type == "wechatmp":
2528
from channel.wechatmp.wechatmp_channel import WechatMPChannel
2629
ch = WechatMPChannel(passive_reply=True)

channel/web/README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Web channel
2+
使用SSE(Server-Sent Events,服务器推送事件)实现,提供了一个默认的网页。也可以自己实现加入api
3+
4+
#使用方法
5+
- 在配置文件中channel_type填入web即可
6+
- 访问地址 http://localhost:9899
7+
- port可以在配置项 web_port中设置

channel/web/chat.html

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
<!DOCTYPE html>
2+
<html lang="zh">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
6+
<title>Chat</title>
7+
<style>
8+
body {
9+
font-family: Arial, sans-serif;
10+
display: flex;
11+
flex-direction: column;
12+
height: 100vh; /* 占据所有高度 */
13+
margin: 0;
14+
/* background-color: #f8f9fa; */
15+
}
16+
#chat-container {
17+
display: flex;
18+
flex-direction: column;
19+
width: 100%;
20+
max-width: 500px;
21+
margin: auto;
22+
border: 1px solid #ccc;
23+
border-radius: 5px;
24+
overflow: hidden;
25+
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
26+
flex: 1; /* 使聊天容器占据剩余空间 */
27+
}
28+
#messages {
29+
flex-direction: column;
30+
display: flex;
31+
flex: 1;
32+
overflow-y: auto;
33+
padding: 10px;
34+
overflow-y: auto;
35+
border-bottom: 1px solid #ccc;
36+
background-color: #ffffff;
37+
}
38+
39+
.message {
40+
margin: 5px 0; /* 间隔 */
41+
padding: 10px 15px; /* 内边距 */
42+
border-radius: 15px; /* 圆角 */
43+
max-width: 80%; /* 限制最大宽度 */
44+
min-width: 80px; /* 设置最小宽度 */
45+
min-height: 40px; /* 设置最小高度 */
46+
word-wrap: break-word; /* 自动换行 */
47+
position: relative; /* 时间戳定位 */
48+
display: inline-block; /* 内容自适应宽度 */
49+
box-sizing: border-box; /* 包括内边距和边框 */
50+
flex-shrink: 0; /* 禁止高度被压缩 */
51+
word-wrap: break-word; /* 自动换行,防止单行过长 */
52+
white-space: normal; /* 允许正常换行 */
53+
overflow: hidden;
54+
}
55+
56+
.bot {
57+
background-color: #f1f1f1; /* 灰色背景 */
58+
color: black; /* 黑色字体 */
59+
align-self: flex-start; /* 左对齐 */
60+
margin-right: auto; /* 确保消息靠左 */
61+
text-align: left; /* 内容左对齐 */
62+
}
63+
64+
.user {
65+
background-color: #2bc840; /* 蓝色背景 */
66+
align-self: flex-end; /* 右对齐 */
67+
margin-left: auto; /* 确保消息靠右 */
68+
text-align: left; /* 内容左对齐 */
69+
}
70+
.timestamp {
71+
font-size: 0.8em; /* 时间戳字体大小 */
72+
color: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
73+
margin-bottom: 5px; /* 时间戳下方间距 */
74+
display: block; /* 时间戳独占一行 */
75+
}
76+
#input-container {
77+
display: flex;
78+
padding: 10px;
79+
background-color: #ffffff;
80+
border-top: 1px solid #ccc;
81+
}
82+
#input {
83+
flex: 1;
84+
padding: 10px;
85+
border: 1px solid #ccc;
86+
border-radius: 5px;
87+
margin-right: 10px;
88+
}
89+
#send {
90+
padding: 10px;
91+
border: none;
92+
background-color: #007bff;
93+
color: white;
94+
border-radius: 5px;
95+
cursor: pointer;
96+
}
97+
#send:hover {
98+
background-color: #0056b3;
99+
}
100+
</style>
101+
</head>
102+
<body>
103+
<div id="chat-container">
104+
<div id="messages"></div>
105+
<div id="input-container">
106+
<input type="text" id="input" placeholder="输入消息..." />
107+
<button id="send">发送</button>
108+
</div>
109+
</div>
110+
111+
<script>
112+
const messagesDiv = document.getElementById('messages');
113+
const input = document.getElementById('input');
114+
const sendButton = document.getElementById('send');
115+
116+
// 生成唯一的 user_id
117+
const userId = 'user_' + Math.random().toString(36).substr(2, 9);
118+
119+
// 连接 SSE
120+
const eventSource = new EventSource(`/sse/${userId}`);
121+
122+
eventSource.onmessage = function(event) {
123+
const message = JSON.parse(event.data);
124+
const messageDiv = document.createElement('div');
125+
messageDiv.className = 'message bot';
126+
const timestamp = new Date(message.timestamp).toLocaleTimeString(); // 假设消息中有时间戳
127+
messageDiv.innerHTML = `<div class="timestamp">${timestamp}</div>${message.content}`; // 显示时间
128+
messagesDiv.appendChild(messageDiv);
129+
messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
130+
};
131+
132+
sendButton.onclick = function() {
133+
sendMessage();
134+
};
135+
136+
input.addEventListener('keypress', function(event) {
137+
if (event.key === 'Enter') {
138+
sendMessage();
139+
event.preventDefault(); // 防止换行
140+
}
141+
});
142+
143+
function sendMessage() {
144+
const userMessage = input.value;
145+
if (userMessage) {
146+
const timestamp = new Date().toISOString(); // 获取当前时间戳
147+
fetch('/message', {
148+
method: 'POST',
149+
headers: {
150+
'Content-Type': 'application/json'
151+
},
152+
body: JSON.stringify({ user_id: userId, message: userMessage, timestamp: timestamp }) // 发送时间戳
153+
});
154+
const messageDiv = document.createElement('div');
155+
messageDiv.className = 'message user';
156+
const userTimestamp = new Date().toLocaleTimeString(); // 获取当前时间
157+
messageDiv.innerHTML = `<div class="timestamp">${userTimestamp}</div>${userMessage}`; // 显示时间
158+
messagesDiv.appendChild(messageDiv);
159+
messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
160+
input.value = ''; // 清空输入框
161+
}
162+
}
163+
</script>
164+
</body>
165+
</html>

channel/web/web_channel.py

Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
import sys
2+
import time
3+
import web
4+
import json
5+
from queue import Queue
6+
from bridge.context import *
7+
from bridge.reply import Reply, ReplyType
8+
from channel.chat_channel import ChatChannel, check_prefix
9+
from channel.chat_message import ChatMessage
10+
from common.log import logger
11+
from common.singleton import singleton
12+
from config import conf
13+
import os
14+
15+
16+
class WebMessage(ChatMessage):
17+
def __init__(
18+
self,
19+
msg_id,
20+
content,
21+
ctype=ContextType.TEXT,
22+
from_user_id="User",
23+
to_user_id="Chatgpt",
24+
other_user_id="Chatgpt",
25+
):
26+
self.msg_id = msg_id
27+
self.ctype = ctype
28+
self.content = content
29+
self.from_user_id = from_user_id
30+
self.to_user_id = to_user_id
31+
self.other_user_id = other_user_id
32+
33+
34+
@singleton
35+
class WebChannel(ChatChannel):
36+
NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE]
37+
_instance = None
38+
39+
# def __new__(cls):
40+
# if cls._instance is None:
41+
# cls._instance = super(WebChannel, cls).__new__(cls)
42+
# return cls._instance
43+
44+
def __init__(self):
45+
super().__init__()
46+
self.message_queues = {} # 为每个用户存储一个消息队列
47+
self.msg_id_counter = 0 # 添加消息ID计数器
48+
49+
def _generate_msg_id(self):
50+
"""生成唯一的消息ID"""
51+
self.msg_id_counter += 1
52+
return str(int(time.time())) + str(self.msg_id_counter)
53+
54+
def send(self, reply: Reply, context: Context):
55+
try:
56+
if reply.type == ReplyType.IMAGE:
57+
from PIL import Image
58+
59+
image_storage = reply.content
60+
image_storage.seek(0)
61+
img = Image.open(image_storage)
62+
print("<IMAGE>")
63+
img.show()
64+
elif reply.type == ReplyType.IMAGE_URL:
65+
import io
66+
67+
import requests
68+
from PIL import Image
69+
70+
img_url = reply.content
71+
pic_res = requests.get(img_url, stream=True)
72+
image_storage = io.BytesIO()
73+
for block in pic_res.iter_content(1024):
74+
image_storage.write(block)
75+
image_storage.seek(0)
76+
img = Image.open(image_storage)
77+
print(img_url)
78+
img.show()
79+
else:
80+
print(reply.content)
81+
82+
# 获取用户ID,如果没有则使用默认值
83+
# user_id = getattr(context.get("session", None), "session_id", "default_user")
84+
user_id = context["receiver"]
85+
# 确保用户有对应的消息队列
86+
if user_id not in self.message_queues:
87+
self.message_queues[user_id] = Queue()
88+
89+
# 将消息放入对应用户的队列
90+
message_data = {
91+
"type": str(reply.type),
92+
"content": reply.content,
93+
"timestamp": time.time()
94+
}
95+
self.message_queues[user_id].put(message_data)
96+
logger.debug(f"Message queued for user {user_id}")
97+
98+
except Exception as e:
99+
logger.error(f"Error in send method: {e}")
100+
raise
101+
102+
def sse_handler(self, user_id):
103+
"""
104+
Handle Server-Sent Events (SSE) for real-time communication.
105+
"""
106+
web.header('Content-Type', 'text/event-stream')
107+
web.header('Cache-Control', 'no-cache')
108+
web.header('Connection', 'keep-alive')
109+
110+
# 确保用户有消息队列
111+
if user_id not in self.message_queues:
112+
self.message_queues[user_id] = Queue()
113+
114+
try:
115+
while True:
116+
try:
117+
# 发送心跳
118+
yield f": heartbeat\n\n"
119+
120+
# 非阻塞方式获取消息
121+
if not self.message_queues[user_id].empty():
122+
message = self.message_queues[user_id].get_nowait()
123+
yield f"data: {json.dumps(message)}\n\n"
124+
time.sleep(0.5)
125+
except Exception as e:
126+
logger.error(f"SSE Error: {e}")
127+
break
128+
finally:
129+
# 清理资源
130+
if user_id in self.message_queues:
131+
# 只有当队列为空时才删除
132+
if self.message_queues[user_id].empty():
133+
del self.message_queues[user_id]
134+
135+
def post_message(self):
136+
"""
137+
Handle incoming messages from users via POST request.
138+
"""
139+
try:
140+
data = web.data() # 获取原始POST数据
141+
json_data = json.loads(data)
142+
user_id = json_data.get('user_id', 'default_user')
143+
prompt = json_data.get('message', '')
144+
except json.JSONDecodeError:
145+
return json.dumps({"status": "error", "message": "Invalid JSON"})
146+
except Exception as e:
147+
return json.dumps({"status": "error", "message": str(e)})
148+
149+
if not prompt:
150+
return json.dumps({"status": "error", "message": "No message provided"})
151+
152+
try:
153+
msg_id = self._generate_msg_id()
154+
context = self._compose_context(ContextType.TEXT, prompt, msg=WebMessage(msg_id,
155+
prompt,
156+
from_user_id=user_id,
157+
other_user_id = user_id
158+
))
159+
context["isgroup"] = False
160+
# context["session"] = web.storage(session_id=user_id)
161+
162+
if not context:
163+
return json.dumps({"status": "error", "message": "Failed to process message"})
164+
165+
self.produce(context)
166+
return json.dumps({"status": "success", "message": "Message received"})
167+
168+
except Exception as e:
169+
logger.error(f"Error processing message: {e}")
170+
return json.dumps({"status": "error", "message": "Internal server error"})
171+
172+
def chat_page(self):
173+
"""Serve the chat HTML page."""
174+
file_path = os.path.join(os.path.dirname(__file__), 'chat.html') # 使用绝对路径
175+
with open(file_path, 'r', encoding='utf-8') as f:
176+
return f.read()
177+
178+
def startup(self):
179+
logger.setLevel("WARN")
180+
print("\nWeb Channel is running. Send POST requests to /message to send messages.")
181+
182+
urls = (
183+
'/sse/(.+)', 'SSEHandler', # 修改路由以接收用户ID
184+
'/message', 'MessageHandler',
185+
'/chat', 'ChatHandler',
186+
)
187+
port = conf().get("web_port", 9899)
188+
app = web.application(urls, globals(), autoreload=False)
189+
web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
190+
191+
192+
class SSEHandler:
193+
def GET(self, user_id):
194+
return WebChannel().sse_handler(user_id)
195+
196+
197+
class MessageHandler:
198+
def POST(self):
199+
return WebChannel().post_message()
200+
201+
202+
class ChatHandler:
203+
def GET(self):
204+
return WebChannel().chat_page()

0 commit comments

Comments
 (0)