Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

chat_channel.py 17KB

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