Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

380 lignes
19KB

  1. import os
  2. import re
  3. import threading
  4. import time
  5. from asyncio import CancelledError
  6. from concurrent.futures import Future, ThreadPoolExecutor
  7. from bridge.context import *
  8. from bridge.reply import *
  9. from channel.channel import Channel
  10. from common.dequeue import Dequeue
  11. from common.log import logger
  12. from config import conf
  13. from plugins import *
  14. try:
  15. from voice.audio_convert import any_to_wav
  16. except Exception as e:
  17. pass
  18. # 抽象类, 它包含了与消息通道无关的通用处理逻辑
  19. class ChatChannel(Channel):
  20. name = None # 登录的用户名
  21. user_id = None # 登录的用户id
  22. futures = {} # 记录每个session_id提交到线程池的future对象, 用于重置会话时把没执行的future取消掉,正在执行的不会被取消
  23. sessions = {} # 用于控制并发,每个session_id同时只能有一个context在处理
  24. lock = threading.Lock() # 用于控制对sessions的访问
  25. handler_pool = ThreadPoolExecutor(max_workers=8) # 处理消息的线程池
  26. def __init__(self):
  27. _thread = threading.Thread(target=self.consume)
  28. _thread.setDaemon(True)
  29. _thread.start()
  30. # 根据消息构造context,消息内容相关的触发项写在这里
  31. def _compose_context(self, ctype: ContextType, content, **kwargs):
  32. context = Context(ctype, content)
  33. context.kwargs = kwargs
  34. # context首次传入时,origin_ctype是None,
  35. # 引入的起因是:当输入语音时,会嵌套生成两个context,第一步语音转文本,第二步通过文本生成文字回复。
  36. # origin_ctype用于第二步文本回复时,判断是否需要匹配前缀,如果是私聊的语音,就不需要匹配前缀
  37. if "origin_ctype" not in context:
  38. context["origin_ctype"] = ctype
  39. # context首次传入时,receiver是None,根据类型设置receiver
  40. first_in = "receiver" not in context
  41. # 群名匹配过程,设置session_id和receiver
  42. if first_in: # context首次传入时,receiver是None,根据类型设置receiver
  43. config = conf()
  44. cmsg = context["msg"]
  45. user_data = conf().get_user_data(cmsg.from_user_id)
  46. context["openai_api_key"] = user_data.get("openai_api_key")
  47. context["gpt_model"] = user_data.get("gpt_model")
  48. if context.get("isgroup", False):
  49. group_name = cmsg.other_user_nickname
  50. group_id = cmsg.other_user_id
  51. group_name_white_list = config.get("group_name_white_list", [])
  52. group_name_keyword_white_list = config.get("group_name_keyword_white_list", [])
  53. if any(
  54. [
  55. group_name in group_name_white_list,
  56. "ALL_GROUP" in group_name_white_list,
  57. check_contain(group_name, group_name_keyword_white_list),
  58. ]
  59. ):
  60. group_chat_in_one_session = conf().get("group_chat_in_one_session", [])
  61. session_id = cmsg.actual_user_id
  62. if any(
  63. [
  64. group_name in group_chat_in_one_session,
  65. "ALL_GROUP" in group_chat_in_one_session,
  66. ]
  67. ):
  68. session_id = group_id
  69. else:
  70. return None
  71. context["session_id"] = session_id
  72. context["receiver"] = group_id
  73. else:
  74. context["session_id"] = cmsg.other_user_id
  75. context["receiver"] = cmsg.other_user_id
  76. e_context = PluginManager().emit_event(EventContext(Event.ON_RECEIVE_MESSAGE, {"channel": self, "context": context}))
  77. context = e_context["context"]
  78. if e_context.is_pass() or context is None:
  79. return context
  80. if cmsg.from_user_id == self.user_id and not config.get("trigger_by_self", True):
  81. logger.debug("[WX]self message skipped")
  82. return None
  83. # 消息内容匹配过程,并处理content
  84. if ctype == ContextType.TEXT:
  85. if first_in and "」\n- - - - - - -" in content: # 初次匹配 过滤引用消息
  86. logger.debug(content)
  87. logger.debug("[WX]reference query skipped")
  88. return None
  89. if context.get("isgroup", False): # 群聊
  90. # 校验关键字
  91. match_prefix = check_prefix(content, conf().get("group_chat_prefix"))
  92. match_contain = check_contain(content, conf().get("group_chat_keyword"))
  93. flag = False
  94. if context["msg"].to_user_id != context["msg"].actual_user_id:
  95. if match_prefix is not None or match_contain is not None:
  96. flag = True
  97. if match_prefix:
  98. content = content.replace(match_prefix, "", 1).strip()
  99. if context["msg"].is_at:
  100. logger.info("[WX]receive group at")
  101. if not conf().get("group_at_off", False):
  102. flag = True
  103. pattern = f"@{re.escape(self.name)}(\u2005|\u0020)"
  104. subtract_res = re.sub(pattern, r"", content)
  105. if isinstance(context["msg"].at_list, list):
  106. for at in context["msg"].at_list:
  107. pattern = f"@{re.escape(at)}(\u2005|\u0020)"
  108. subtract_res = re.sub(pattern, r"", subtract_res)
  109. if subtract_res == content and context["msg"].self_display_name:
  110. # 前缀移除后没有变化,使用群昵称再次移除
  111. pattern = f"@{re.escape(context['msg'].self_display_name)}(\u2005|\u0020)"
  112. subtract_res = re.sub(pattern, r"", content)
  113. content = subtract_res
  114. if not flag:
  115. if context["origin_ctype"] == ContextType.VOICE:
  116. logger.info("[WX]receive group voice, but checkprefix didn't match")
  117. return None
  118. else: # 单聊
  119. match_prefix = check_prefix(content, conf().get("single_chat_prefix", [""]))
  120. if match_prefix is not None: # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容
  121. content = content.replace(match_prefix, "", 1).strip()
  122. elif context["origin_ctype"] == ContextType.VOICE: # 如果源消息是私聊的语音消息,允许不匹配前缀,放宽条件
  123. pass
  124. else:
  125. return None
  126. content = content.strip()
  127. img_match_prefix = check_prefix(content, conf().get("image_create_prefix"))
  128. if img_match_prefix:
  129. content = content.replace(img_match_prefix, "", 1)
  130. context.type = ContextType.IMAGE_CREATE
  131. else:
  132. context.type = ContextType.TEXT
  133. context.content = content.strip()
  134. if "desire_rtype" not in context and conf().get("always_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
  135. context["desire_rtype"] = ReplyType.VOICE
  136. elif context.type == ContextType.VOICE:
  137. if "desire_rtype" not in context and conf().get("voice_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
  138. context["desire_rtype"] = ReplyType.VOICE
  139. return context
  140. def _handle(self, context: Context):
  141. if context is None or not context.content:
  142. return
  143. logger.debug("[WX] ready to handle context: {}".format(context))
  144. # reply的构建步骤
  145. reply = self._generate_reply(context)
  146. logger.debug("[WX] ready to decorate reply: {}".format(reply))
  147. # reply的包装步骤
  148. reply = self._decorate_reply(context, reply)
  149. # reply的发送步骤
  150. self._send_reply(context, reply)
  151. def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply:
  152. e_context = PluginManager().emit_event(
  153. EventContext(
  154. Event.ON_HANDLE_CONTEXT,
  155. {"channel": self, "context": context, "reply": reply},
  156. )
  157. )
  158. reply = e_context["reply"]
  159. if not e_context.is_pass():
  160. logger.debug("[WX] ready to handle context: type={}, content={}".format(context.type, context.content))
  161. if e_context.is_break():
  162. context["generate_breaked_by"] = e_context["breaked_by"]
  163. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  164. context["channel"] = e_context["channel"]
  165. reply = super().build_reply_content(context.content, context)
  166. elif context.type == ContextType.VOICE: # 语音消息
  167. cmsg = context["msg"]
  168. cmsg.prepare()
  169. file_path = context.content
  170. wav_path = os.path.splitext(file_path)[0] + ".wav"
  171. try:
  172. any_to_wav(file_path, wav_path)
  173. except Exception as e: # 转换失败,直接使用mp3,对于某些api,mp3也可以识别
  174. logger.warning("[WX]any to wav error, use raw path. " + str(e))
  175. wav_path = file_path
  176. # 语音识别
  177. reply = super().build_voice_to_text(wav_path)
  178. # 删除临时文件
  179. try:
  180. os.remove(file_path)
  181. if wav_path != file_path:
  182. os.remove(wav_path)
  183. except Exception as e:
  184. pass
  185. # logger.warning("[WX]delete temp file error: " + str(e))
  186. if reply.type == ReplyType.TEXT:
  187. new_context = self._compose_context(ContextType.TEXT, reply.content, **context.kwargs)
  188. if new_context:
  189. reply = self._generate_reply(new_context)
  190. else:
  191. return
  192. elif context.type == ContextType.IMAGE: # 图片消息,当前仅做下载保存到本地的逻辑
  193. cmsg = context["msg"]
  194. cmsg.prepare()
  195. elif context.type == ContextType.SHARING: # 分享信息,当前无默认逻辑
  196. pass
  197. elif context.type == ContextType.FUNCTION or context.type == ContextType.FILE: # 文件消息及函数调用等,当前无默认逻辑
  198. pass
  199. else:
  200. logger.error("[WX] unknown context type: {}".format(context.type))
  201. return
  202. return reply
  203. def _decorate_reply(self, context: Context, reply: Reply) -> Reply:
  204. if reply and reply.type:
  205. e_context = PluginManager().emit_event(
  206. EventContext(
  207. Event.ON_DECORATE_REPLY,
  208. {"channel": self, "context": context, "reply": reply},
  209. )
  210. )
  211. reply = e_context["reply"]
  212. desire_rtype = context.get("desire_rtype")
  213. if not e_context.is_pass() and reply and reply.type:
  214. if reply.type in self.NOT_SUPPORT_REPLYTYPE:
  215. logger.error("[WX]reply type not support: " + str(reply.type))
  216. reply.type = ReplyType.ERROR
  217. reply.content = "不支持发送的消息类型: " + str(reply.type)
  218. if reply.type == ReplyType.TEXT:
  219. reply_text = reply.content
  220. if desire_rtype == ReplyType.VOICE and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
  221. reply = super().build_text_to_voice(reply.content)
  222. return self._decorate_reply(context, reply)
  223. if context.get("isgroup", False):
  224. reply_text = "@" + context["msg"].actual_user_nickname + "\n" + reply_text.strip()
  225. reply_text = conf().get("group_chat_reply_prefix", "") + reply_text + conf().get("group_chat_reply_suffix", "")
  226. else:
  227. reply_text = conf().get("single_chat_reply_prefix", "") + reply_text + conf().get("single_chat_reply_suffix", "")
  228. reply.content = reply_text
  229. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  230. reply.content = "[" + str(reply.type) + "]\n" + reply.content
  231. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE or reply.type == ReplyType.FILE or reply.type == ReplyType.VIDEO or reply.type == ReplyType.VIDEO_URL:
  232. pass
  233. else:
  234. logger.error("[WX] unknown reply type: {}".format(reply.type))
  235. return
  236. if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
  237. logger.warning("[WX] desire_rtype: {}, but reply type: {}".format(context.get("desire_rtype"), reply.type))
  238. return reply
  239. def _send_reply(self, context: Context, reply: Reply):
  240. if reply and reply.type:
  241. e_context = PluginManager().emit_event(
  242. EventContext(
  243. Event.ON_SEND_REPLY,
  244. {"channel": self, "context": context, "reply": reply},
  245. )
  246. )
  247. reply = e_context["reply"]
  248. if not e_context.is_pass() and reply and reply.type:
  249. logger.debug("[WX] ready to send reply: {}, context: {}".format(reply, context))
  250. self._send(reply, context)
  251. def _send(self, reply: Reply, context: Context, retry_cnt=0):
  252. try:
  253. self.send(reply, context)
  254. except Exception as e:
  255. logger.error("[WX] sendMsg error: {}".format(str(e)))
  256. if isinstance(e, NotImplementedError):
  257. return
  258. logger.exception(e)
  259. if retry_cnt < 2:
  260. time.sleep(3 + 3 * retry_cnt)
  261. self._send(reply, context, retry_cnt + 1)
  262. def _success_callback(self, session_id, **kwargs): # 线程正常结束时的回调函数
  263. logger.debug("Worker return success, session_id = {}".format(session_id))
  264. def _fail_callback(self, session_id, exception, **kwargs): # 线程异常结束时的回调函数
  265. logger.exception("Worker return exception: {}".format(exception))
  266. def _thread_pool_callback(self, session_id, **kwargs):
  267. def func(worker: Future):
  268. try:
  269. worker_exception = worker.exception()
  270. if worker_exception:
  271. self._fail_callback(session_id, exception=worker_exception, **kwargs)
  272. else:
  273. self._success_callback(session_id, **kwargs)
  274. except CancelledError as e:
  275. logger.info("Worker cancelled, session_id = {}".format(session_id))
  276. except Exception as e:
  277. logger.exception("Worker raise exception: {}".format(e))
  278. with self.lock:
  279. self.sessions[session_id][1].release()
  280. return func
  281. def produce(self, context: Context):
  282. session_id = context["session_id"]
  283. with self.lock:
  284. if session_id not in self.sessions:
  285. self.sessions[session_id] = [
  286. Dequeue(),
  287. threading.BoundedSemaphore(conf().get("concurrency_in_session", 4)),
  288. ]
  289. if context.type == ContextType.TEXT and context.content.startswith("#"):
  290. self.sessions[session_id][0].putleft(context) # 优先处理管理命令
  291. else:
  292. self.sessions[session_id][0].put(context)
  293. # 消费者函数,单独线程,用于从消息队列中取出消息并处理
  294. def consume(self):
  295. while True:
  296. with self.lock:
  297. session_ids = list(self.sessions.keys())
  298. for session_id in session_ids:
  299. context_queue, semaphore = self.sessions[session_id]
  300. if semaphore.acquire(blocking=False): # 等线程处理完毕才能删除
  301. if not context_queue.empty():
  302. context = context_queue.get()
  303. logger.debug("[WX] consume context: {}".format(context))
  304. future: Future = self.handler_pool.submit(self._handle, context)
  305. future.add_done_callback(self._thread_pool_callback(session_id, context=context))
  306. if session_id not in self.futures:
  307. self.futures[session_id] = []
  308. self.futures[session_id].append(future)
  309. elif semaphore._initial_value == semaphore._value + 1: # 除了当前,没有任务再申请到信号量,说明所有任务都处理完毕
  310. self.futures[session_id] = [t for t in self.futures[session_id] if not t.done()]
  311. assert len(self.futures[session_id]) == 0, "thread pool error"
  312. del self.sessions[session_id]
  313. else:
  314. semaphore.release()
  315. time.sleep(0.1)
  316. # 取消session_id对应的所有任务,只能取消排队的消息和已提交线程池但未执行的任务
  317. def cancel_session(self, session_id):
  318. with self.lock:
  319. if session_id in self.sessions:
  320. for future in self.futures[session_id]:
  321. future.cancel()
  322. cnt = self.sessions[session_id][0].qsize()
  323. if cnt > 0:
  324. logger.info("Cancel {} messages in session {}".format(cnt, session_id))
  325. self.sessions[session_id][0] = Dequeue()
  326. def cancel_all_session(self):
  327. with self.lock:
  328. for session_id in self.sessions:
  329. for future in self.futures[session_id]:
  330. future.cancel()
  331. cnt = self.sessions[session_id][0].qsize()
  332. if cnt > 0:
  333. logger.info("Cancel {} messages in session {}".format(cnt, session_id))
  334. self.sessions[session_id][0] = Dequeue()
  335. def check_prefix(content, prefix_list):
  336. if not prefix_list:
  337. return None
  338. for prefix in prefix_list:
  339. if content.startswith(prefix):
  340. return prefix
  341. return None
  342. def check_contain(content, keyword_list):
  343. if not keyword_list:
  344. return None
  345. for ky in keyword_list:
  346. if content.find(ky) != -1:
  347. return True
  348. return None