Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

317 lines
16KB

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