You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

311 lines
15KB

  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'):
  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'):
  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 == ReplyType.TEXT:
  168. reply_text = reply.content
  169. if desire_rtype == ReplyType.VOICE:
  170. reply = super().build_text_to_voice(reply.content)
  171. return self._decorate_reply(context, reply)
  172. if context['isgroup']:
  173. reply_text = '@' + context['msg'].actual_user_nickname + ' ' + reply_text.strip()
  174. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  175. else:
  176. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  177. reply.content = reply_text
  178. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  179. reply.content = str(reply.type)+":\n" + reply.content
  180. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  181. pass
  182. else:
  183. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  184. return
  185. if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
  186. logger.warning('[WX] desire_rtype: {}, but reply type: {}'.format(context.get('desire_rtype'), reply.type))
  187. return reply
  188. def _send_reply(self, context: Context, reply: Reply):
  189. if reply and reply.type:
  190. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  191. 'channel': self, 'context': context, 'reply': reply}))
  192. reply = e_context['reply']
  193. if not e_context.is_pass() and reply and reply.type:
  194. logger.debug('[WX] ready to send reply: {}, context: {}'.format(reply, context))
  195. self._send(reply, context)
  196. def _send(self, reply: Reply, context: Context, retry_cnt = 0):
  197. try:
  198. self.send(reply, context)
  199. except Exception as e:
  200. logger.error('[WX] sendMsg error: {}'.format(str(e)))
  201. if isinstance(e, NotImplementedError):
  202. return
  203. logger.exception(e)
  204. if retry_cnt < 2:
  205. time.sleep(3+3*retry_cnt)
  206. self._send(reply, context, retry_cnt+1)
  207. def thread_pool_callback(self, session_id):
  208. def func(worker:Future):
  209. try:
  210. worker_exception = worker.exception()
  211. if worker_exception:
  212. logger.exception("Worker return exception: {}".format(worker_exception))
  213. except CancelledError as e:
  214. logger.info("Worker cancelled, session_id = {}".format(session_id))
  215. except Exception as e:
  216. logger.exception("Worker raise exception: {}".format(e))
  217. with self.lock:
  218. self.sessions[session_id][1].release()
  219. return func
  220. def produce(self, context: Context):
  221. session_id = context['session_id']
  222. with self.lock:
  223. if session_id not in self.sessions:
  224. self.sessions[session_id] = [Dequeue(), threading.BoundedSemaphore(conf().get("concurrency_in_session", 1))]
  225. if context.type == ContextType.TEXT and context.content.startswith("#"):
  226. self.sessions[session_id][0].putleft(context) # 优先处理管理命令
  227. else:
  228. self.sessions[session_id][0].put(context)
  229. # 消费者函数,单独线程,用于从消息队列中取出消息并处理
  230. def consume(self):
  231. while True:
  232. with self.lock:
  233. session_ids = list(self.sessions.keys())
  234. for session_id in session_ids:
  235. context_queue, semaphore = self.sessions[session_id]
  236. if semaphore.acquire(blocking = False): # 等线程处理完毕才能删除
  237. if not context_queue.empty():
  238. context = context_queue.get()
  239. logger.debug("[WX] consume context: {}".format(context))
  240. future:Future = self.handler_pool.submit(self._handle, context)
  241. future.add_done_callback(self.thread_pool_callback(session_id))
  242. if session_id not in self.futures:
  243. self.futures[session_id] = []
  244. self.futures[session_id].append(future)
  245. elif semaphore._initial_value == semaphore._value+1: # 除了当前,没有任务再申请到信号量,说明所有任务都处理完毕
  246. self.futures[session_id] = [t for t in self.futures[session_id] if not t.done()]
  247. assert len(self.futures[session_id]) == 0, "thread pool error"
  248. del self.sessions[session_id]
  249. else:
  250. semaphore.release()
  251. time.sleep(0.1)
  252. # 取消session_id对应的所有任务,只能取消排队的消息和已提交线程池但未执行的任务
  253. def cancel_session(self, session_id):
  254. with self.lock:
  255. if session_id in self.sessions:
  256. for future in self.futures[session_id]:
  257. future.cancel()
  258. cnt = self.sessions[session_id][0].qsize()
  259. if cnt>0:
  260. logger.info("Cancel {} messages in session {}".format(cnt, session_id))
  261. self.sessions[session_id][0] = Dequeue()
  262. def cancel_all_session(self):
  263. with self.lock:
  264. for session_id in self.sessions:
  265. for future in self.futures[session_id]:
  266. future.cancel()
  267. cnt = self.sessions[session_id][0].qsize()
  268. if cnt>0:
  269. logger.info("Cancel {} messages in session {}".format(cnt, session_id))
  270. self.sessions[session_id][0] = Dequeue()
  271. def check_prefix(content, prefix_list):
  272. for prefix in prefix_list:
  273. if content.startswith(prefix):
  274. return prefix
  275. return None
  276. def check_contain(content, keyword_list):
  277. if not keyword_list:
  278. return None
  279. for ky in keyword_list:
  280. if content.find(ky) != -1:
  281. return True
  282. return None