Skip to content

Commit 45a131a

Browse files
committed
support plugins
1 parent a7900d4 commit 45a131a

File tree

2 files changed

+109
-17
lines changed

2 files changed

+109
-17
lines changed

bot/chatgpt/chat_gpt_bot.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,8 @@ def compose_args(self):
8686
"top_p":1,
8787
"frequency_penalty":conf().get('frequency_penalty', 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
8888
"presence_penalty":conf().get('presence_penalty', 0.0), # [-2,2]之间,该值越大则更倾向于产生不同的内容
89+
"request_timeout": 120, # 请求超时时间
90+
"timeout": 120, #重试超时时间,在这个时间内,将会自动重试
8991
}
9092

9193
def reply_text(self, session:ChatGPTSession, session_id, retry_count=0) -> dict:

channel/wechatmp/wechatmp_channel.py

Lines changed: 107 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# -*- coding: utf-8 -*-
2-
# filename: main.py
32
import web
43
import time
54
import math
@@ -10,7 +9,10 @@
109
import channel.wechatmp.receive as receive
1110
from common.log import logger
1211
from config import conf
13-
12+
from bridge.reply import *
13+
from bridge.context import *
14+
from plugins import *
15+
import traceback
1416

1517
class WechatMPServer():
1618
def __init__(self):
@@ -23,15 +25,14 @@ def startup(self):
2325
app = web.application(urls, globals())
2426
app.run()
2527

26-
27-
from concurrent.futures import ThreadPoolExecutor
28-
thread_pool = ThreadPoolExecutor(max_workers=8)
29-
3028
cache_dict = dict()
3129
query1 = dict()
3230
query2 = dict()
3331
query3 = dict()
3432

33+
from concurrent.futures import ThreadPoolExecutor
34+
thread_pool = ThreadPoolExecutor(max_workers=8)
35+
3536
class WechatMPChannel(Channel):
3637

3738
def GET(self):
@@ -66,11 +67,79 @@ def _do_build_reply(self, cache_key, fromUser, message):
6667
reply_text = super().build_reply_content(message, context)
6768
# The query is done, record the cache
6869
logger.info("[threaded] Get reply for {}: {} \nA: {}".format(fromUser, message, reply_text))
69-
reply_cnt = math.ceil(len(reply_text) / 600)
7070
global cache_dict
71+
reply_cnt = math.ceil(len(reply_text) / 600)
7172
cache_dict[cache_key] = (reply_cnt, reply_text)
7273

7374

75+
def send(self, reply : Reply, cache_key):
76+
global cache_dict
77+
reply_cnt = math.ceil(len(reply.content) / 600)
78+
cache_dict[cache_key] = (reply_cnt, reply.content)
79+
80+
81+
def handle(self, context):
82+
global cache_dict
83+
try:
84+
reply = Reply()
85+
86+
logger.debug('[wechatmp] ready to handle context: {}'.format(context))
87+
88+
# reply的构建步骤
89+
e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {'channel' : self, 'context': context, 'reply': reply}))
90+
reply = e_context['reply']
91+
if not e_context.is_pass():
92+
logger.debug('[wechatmp] ready to handle context: type={}, content={}'.format(context.type, context.content))
93+
if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE:
94+
reply = super().build_reply_content(context.content, context)
95+
# elif context.type == ContextType.VOICE:
96+
# msg = context['msg']
97+
# file_name = TmpDir().path() + context.content
98+
# msg.download(file_name)
99+
# reply = super().build_voice_to_text(file_name)
100+
# if reply.type != ReplyType.ERROR and reply.type != ReplyType.INFO:
101+
# context.content = reply.content # 语音转文字后,将文字内容作为新的context
102+
# context.type = ContextType.TEXT
103+
# reply = super().build_reply_content(context.content, context)
104+
# if reply.type == ReplyType.TEXT:
105+
# if conf().get('voice_reply_voice'):
106+
# reply = super().build_text_to_voice(reply.content)
107+
else:
108+
logger.error('[wechatmp] unknown context type: {}'.format(context.type))
109+
return
110+
111+
logger.debug('[wechatmp] ready to decorate reply: {}'.format(reply))
112+
113+
# reply的包装步骤
114+
if reply and reply.type:
115+
e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {'channel' : self, 'context': context, 'reply': reply}))
116+
reply=e_context['reply']
117+
if not e_context.is_pass() and reply and reply.type:
118+
if reply.type == ReplyType.TEXT:
119+
pass
120+
elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
121+
reply.content = str(reply.type)+":\n" + reply.content
122+
elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
123+
pass
124+
else:
125+
logger.error('[wechatmp] unknown reply type: {}'.format(reply.type))
126+
return
127+
128+
# reply的发送步骤
129+
if reply and reply.type:
130+
e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {'channel' : self, 'context': context, 'reply': reply}))
131+
reply=e_context['reply']
132+
if not e_context.is_pass() and reply and reply.type:
133+
logger.debug('[wechatmp] ready to send reply: {} to {}'.format(reply, context['receiver']))
134+
self.send(reply, context['receiver'])
135+
else:
136+
cache_dict[context['receiver']] = (1, "No reply")
137+
except Exception as exc:
138+
print(traceback.format_exc())
139+
cache_dict[context['receiver']] = (1, "ERROR")
140+
141+
142+
74143
def POST(self):
75144
try:
76145
queryTime = time.time()
@@ -94,12 +163,23 @@ def POST(self):
94163
cache = cache_dict.get(cache_key)
95164

96165
reply_text = ""
97-
98166
# New request
99167
if cache == None:
100168
# The first query begin, reset the cache
101169
cache_dict[cache_key] = (0, "")
102-
thread_pool.submit(self._do_build_reply, cache_key, fromUser, message)
170+
# thread_pool.submit(self._do_build_reply, cache_key, fromUser, message)
171+
172+
context = Context()
173+
context.kwargs = {'isgroup': False, 'receiver': fromUser, 'session_id': fromUser}
174+
img_match_prefix = check_prefix(message, conf().get('image_create_prefix'))
175+
if img_match_prefix:
176+
message = message.replace(img_match_prefix, '', 1).strip()
177+
context.type = ContextType.IMAGE_CREATE
178+
else:
179+
context.type = ContextType.TEXT
180+
context.content = message
181+
thread_pool.submit(self.handle, context)
182+
103183
query1[cache_key] = False
104184
query2[cache_key] = False
105185
query3[cache_key] = False
@@ -183,18 +263,28 @@ def POST(self):
183263
return replyPost
184264

185265
elif isinstance(recMsg, receive.Event) and recMsg.MsgType == 'event':
186-
toUser = recMsg.FromUserName
187-
fromUser = recMsg.ToUserName
266+
logger.info("[wechatmp] Event {} from {}".format(recMsg.Event, recMsg.FromUserName))
188267
content = textwrap.dedent("""\
189268
感谢您的关注!
190269
这里是ChatGPT,可以自由对话。
191-
资源有限,回复较慢,请不要着急。
192-
暂时不支持图片输入输出,但是支持通用表情输入。""")
193-
replyMsg = reply.TextMsg(toUser, fromUser, content)
270+
资源有限,回复较慢,请勿着急。
271+
支持通用表情输入。
272+
暂时不支持图片输入。
273+
支持图片输出,画字开头的问题将回复图片链接。
274+
支持角色扮演和文字冒险两种定制模式对话。
275+
输入'#帮助' 查看详细指令。""")
276+
replyMsg = reply.TextMsg(recMsg.FromUserName, recMsg.ToUserName, content)
194277
return replyMsg.send()
195278
else:
196279
print("暂且不处理")
197280
return "success"
198-
except Exception as Argment:
199-
print(Argment)
200-
return Argment
281+
except Exception as exc:
282+
print(exc)
283+
return exc
284+
285+
286+
def check_prefix(content, prefix_list):
287+
for prefix in prefix_list:
288+
if content.startswith(prefix):
289+
return prefix
290+
return None

0 commit comments

Comments
 (0)