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.

359 lignes
17KB

  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. if context.get("isgroup", False):
  46. group_name = cmsg.other_user_nickname
  47. group_id = cmsg.other_user_id
  48. group_name_white_list = config.get("group_name_white_list", [])
  49. group_name_keyword_white_list = config.get("group_name_keyword_white_list", [])
  50. if any(
  51. [
  52. group_name in group_name_white_list,
  53. "ALL_GROUP" in group_name_white_list,
  54. check_contain(group_name, group_name_keyword_white_list),
  55. ]
  56. ):
  57. group_chat_in_one_session = conf().get("group_chat_in_one_session", [])
  58. session_id = cmsg.actual_user_id
  59. if any(
  60. [
  61. group_name in group_chat_in_one_session,
  62. "ALL_GROUP" in group_chat_in_one_session,
  63. ]
  64. ):
  65. session_id = group_id
  66. else:
  67. return None
  68. context["session_id"] = session_id
  69. context["receiver"] = group_id
  70. else:
  71. context["session_id"] = cmsg.other_user_id
  72. context["receiver"] = cmsg.other_user_id
  73. e_context = PluginManager().emit_event(EventContext(Event.ON_RECEIVE_MESSAGE, {"channel": self, "context": context}))
  74. context = e_context["context"]
  75. if e_context.is_pass() or context is None:
  76. return context
  77. if cmsg.from_user_id == self.user_id and not config.get("trigger_by_self", True):
  78. logger.debug("[WX]self message skipped")
  79. return None
  80. # 消息内容匹配过程,并处理content
  81. if ctype == ContextType.TEXT:
  82. if first_in and "」\n- - - - - - -" in content: # 初次匹配 过滤引用消息
  83. logger.debug("[WX]reference query skipped")
  84. return None
  85. if context.get("isgroup", False): # 群聊
  86. # 校验关键字
  87. match_prefix = check_prefix(content, conf().get("group_chat_prefix"))
  88. match_contain = check_contain(content, conf().get("group_chat_keyword"))
  89. flag = False
  90. if match_prefix is not None or match_contain is not None:
  91. flag = True
  92. if match_prefix:
  93. content = content.replace(match_prefix, "", 1).strip()
  94. if context["msg"].is_at:
  95. logger.info("[WX]receive group at")
  96. if not conf().get("group_at_off", False):
  97. flag = True
  98. pattern = f"@{re.escape(self.name)}(\u2005|\u0020)"
  99. content = re.sub(pattern, r"", content)
  100. if not flag:
  101. if context["origin_ctype"] == ContextType.VOICE:
  102. logger.info("[WX]receive group voice, but checkprefix didn't match")
  103. return None
  104. else: # 单聊
  105. match_prefix = check_prefix(content, conf().get("single_chat_prefix", [""]))
  106. if match_prefix is not None: # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容
  107. content = content.replace(match_prefix, "", 1).strip()
  108. elif context["origin_ctype"] == ContextType.VOICE: # 如果源消息是私聊的语音消息,允许不匹配前缀,放宽条件
  109. pass
  110. else:
  111. return None
  112. content = content.strip()
  113. img_match_prefix = check_prefix(content, conf().get("image_create_prefix"))
  114. if img_match_prefix:
  115. content = content.replace(img_match_prefix, "", 1)
  116. context.type = ContextType.IMAGE_CREATE
  117. else:
  118. context.type = ContextType.TEXT
  119. context.content = content.strip()
  120. if "desire_rtype" not in context and conf().get("always_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
  121. context["desire_rtype"] = ReplyType.VOICE
  122. elif context.type == ContextType.VOICE:
  123. if "desire_rtype" not in context and conf().get("voice_reply_voice") and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
  124. context["desire_rtype"] = ReplyType.VOICE
  125. return context
  126. def _handle(self, context: Context):
  127. if context is None or not context.content:
  128. return
  129. logger.debug("[WX] ready to handle context: {}".format(context))
  130. # reply的构建步骤
  131. reply = self._generate_reply(context)
  132. logger.debug("[WX] ready to decorate reply: {}".format(reply))
  133. # reply的包装步骤
  134. reply = self._decorate_reply(context, reply)
  135. # reply的发送步骤
  136. self._send_reply(context, reply)
  137. def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply:
  138. e_context = PluginManager().emit_event(
  139. EventContext(
  140. Event.ON_HANDLE_CONTEXT,
  141. {"channel": self, "context": context, "reply": reply},
  142. )
  143. )
  144. reply = e_context["reply"]
  145. if not e_context.is_pass():
  146. logger.debug("[WX] ready to handle context: type={}, content={}".format(context.type, context.content))
  147. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  148. reply = super().build_reply_content(context.content, context)
  149. elif context.type == ContextType.VOICE: # 语音消息
  150. cmsg = context["msg"]
  151. cmsg.prepare()
  152. file_path = context.content
  153. wav_path = os.path.splitext(file_path)[0] + ".wav"
  154. try:
  155. any_to_wav(file_path, wav_path)
  156. except Exception as e: # 转换失败,直接使用mp3,对于某些api,mp3也可以识别
  157. logger.warning("[WX]any to wav error, use raw path. " + str(e))
  158. wav_path = file_path
  159. # 语音识别
  160. reply = super().build_voice_to_text(wav_path)
  161. # 删除临时文件
  162. try:
  163. os.remove(file_path)
  164. if wav_path != file_path:
  165. os.remove(wav_path)
  166. except Exception as e:
  167. pass
  168. # logger.warning("[WX]delete temp file error: " + str(e))
  169. if reply.type == ReplyType.TEXT:
  170. new_context = self._compose_context(ContextType.TEXT, reply.content, **context.kwargs)
  171. if new_context:
  172. reply = self._generate_reply(new_context)
  173. else:
  174. return
  175. elif context.type == ContextType.IMAGE: # 图片消息,当前无默认逻辑
  176. pass
  177. else:
  178. logger.error("[WX] unknown context type: {}".format(context.type))
  179. return
  180. return reply
  181. def _decorate_reply(self, context: Context, reply: Reply) -> Reply:
  182. if reply and reply.type:
  183. e_context = PluginManager().emit_event(
  184. EventContext(
  185. Event.ON_DECORATE_REPLY,
  186. {"channel": self, "context": context, "reply": reply},
  187. )
  188. )
  189. reply = e_context["reply"]
  190. desire_rtype = context.get("desire_rtype")
  191. if not e_context.is_pass() and reply and reply.type:
  192. if reply.type in self.NOT_SUPPORT_REPLYTYPE:
  193. logger.error("[WX]reply type not support: " + str(reply.type))
  194. reply.type = ReplyType.ERROR
  195. reply.content = "不支持发送的消息类型: " + str(reply.type)
  196. if reply.type == ReplyType.TEXT:
  197. reply_text = reply.content
  198. if desire_rtype == ReplyType.VOICE and ReplyType.VOICE not in self.NOT_SUPPORT_REPLYTYPE:
  199. reply = super().build_text_to_voice(reply.content)
  200. return self._decorate_reply(context, reply)
  201. if context.get("isgroup", False):
  202. reply_text = "@" + context["msg"].actual_user_nickname + " " + reply_text.strip()
  203. reply_text = conf().get("group_chat_reply_prefix", "") + reply_text
  204. else:
  205. reply_text = conf().get("single_chat_reply_prefix", "") + reply_text
  206. reply.content = reply_text
  207. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  208. reply.content = "[" + str(reply.type) + "]\n" + reply.content
  209. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  210. pass
  211. else:
  212. logger.error("[WX] unknown reply type: {}".format(reply.type))
  213. return
  214. if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
  215. logger.warning("[WX] desire_rtype: {}, but reply type: {}".format(context.get("desire_rtype"), reply.type))
  216. return reply
  217. def _send_reply(self, context: Context, reply: Reply):
  218. if reply and reply.type:
  219. e_context = PluginManager().emit_event(
  220. EventContext(
  221. Event.ON_SEND_REPLY,
  222. {"channel": self, "context": context, "reply": reply},
  223. )
  224. )
  225. reply = e_context["reply"]
  226. if not e_context.is_pass() and reply and reply.type:
  227. logger.debug("[WX] ready to send reply: {}, context: {}".format(reply, context))
  228. self._send(reply, context)
  229. def _send(self, reply: Reply, context: Context, retry_cnt=0):
  230. try:
  231. self.send(reply, context)
  232. except Exception as e:
  233. logger.error("[WX] sendMsg error: {}".format(str(e)))
  234. if isinstance(e, NotImplementedError):
  235. return
  236. logger.exception(e)
  237. if retry_cnt < 2:
  238. time.sleep(3 + 3 * retry_cnt)
  239. self._send(reply, context, retry_cnt + 1)
  240. def _success_callback(self, session_id, **kwargs): # 线程正常结束时的回调函数
  241. logger.debug("Worker return success, session_id = {}".format(session_id))
  242. def _fail_callback(self, session_id, exception, **kwargs): # 线程异常结束时的回调函数
  243. logger.exception("Worker return exception: {}".format(exception))
  244. def _thread_pool_callback(self, session_id, **kwargs):
  245. def func(worker: Future):
  246. try:
  247. worker_exception = worker.exception()
  248. if worker_exception:
  249. self._fail_callback(session_id, exception=worker_exception, **kwargs)
  250. else:
  251. self._success_callback(session_id, **kwargs)
  252. except CancelledError as e:
  253. logger.info("Worker cancelled, session_id = {}".format(session_id))
  254. except Exception as e:
  255. logger.exception("Worker raise exception: {}".format(e))
  256. with self.lock:
  257. self.sessions[session_id][1].release()
  258. return func
  259. def produce(self, context: Context):
  260. session_id = context["session_id"]
  261. with self.lock:
  262. if session_id not in self.sessions:
  263. self.sessions[session_id] = [
  264. Dequeue(),
  265. threading.BoundedSemaphore(conf().get("concurrency_in_session", 4)),
  266. ]
  267. if context.type == ContextType.TEXT and context.content.startswith("#"):
  268. self.sessions[session_id][0].putleft(context) # 优先处理管理命令
  269. else:
  270. self.sessions[session_id][0].put(context)
  271. # 消费者函数,单独线程,用于从消息队列中取出消息并处理
  272. def consume(self):
  273. while True:
  274. with self.lock:
  275. session_ids = list(self.sessions.keys())
  276. for session_id in session_ids:
  277. context_queue, semaphore = self.sessions[session_id]
  278. if semaphore.acquire(blocking=False): # 等线程处理完毕才能删除
  279. if not context_queue.empty():
  280. context = context_queue.get()
  281. logger.debug("[WX] consume context: {}".format(context))
  282. future: Future = self.handler_pool.submit(self._handle, context)
  283. future.add_done_callback(self._thread_pool_callback(session_id, context=context))
  284. if session_id not in self.futures:
  285. self.futures[session_id] = []
  286. self.futures[session_id].append(future)
  287. elif semaphore._initial_value == semaphore._value + 1: # 除了当前,没有任务再申请到信号量,说明所有任务都处理完毕
  288. self.futures[session_id] = [t for t in self.futures[session_id] if not t.done()]
  289. assert len(self.futures[session_id]) == 0, "thread pool error"
  290. del self.sessions[session_id]
  291. else:
  292. semaphore.release()
  293. time.sleep(0.1)
  294. # 取消session_id对应的所有任务,只能取消排队的消息和已提交线程池但未执行的任务
  295. def cancel_session(self, session_id):
  296. with self.lock:
  297. if session_id in self.sessions:
  298. for future in self.futures[session_id]:
  299. future.cancel()
  300. cnt = self.sessions[session_id][0].qsize()
  301. if cnt > 0:
  302. logger.info("Cancel {} messages in session {}".format(cnt, session_id))
  303. self.sessions[session_id][0] = Dequeue()
  304. def cancel_all_session(self):
  305. with self.lock:
  306. for session_id in self.sessions:
  307. for future in self.futures[session_id]:
  308. future.cancel()
  309. cnt = self.sessions[session_id][0].qsize()
  310. if cnt > 0:
  311. logger.info("Cancel {} messages in session {}".format(cnt, session_id))
  312. self.sessions[session_id][0] = Dequeue()
  313. def check_prefix(content, prefix_list):
  314. if not prefix_list:
  315. return None
  316. for prefix in prefix_list:
  317. if content.startswith(prefix):
  318. return prefix
  319. return None
  320. def check_contain(content, keyword_list):
  321. if not keyword_list:
  322. return None
  323. for ky in keyword_list:
  324. if content.find(ky) != -1:
  325. return True
  326. return None