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.

228 lines
11KB

  1. import os
  2. import re
  3. import time
  4. from common.expired_dict import ExpiredDict
  5. from channel.channel import Channel
  6. from bridge.reply import *
  7. from bridge.context import *
  8. from config import conf
  9. from common.log import logger
  10. from plugins import *
  11. try:
  12. from voice.audio_convert import any_to_wav
  13. except Exception as e:
  14. pass
  15. # 抽象类, 它包含了与消息通道无关的通用处理逻辑
  16. class ChatChannel(Channel):
  17. name = None # 登录的用户名
  18. user_id = None # 登录的用户id
  19. def __init__(self):
  20. pass
  21. # 根据消息构造context,消息内容相关的触发项写在这里
  22. def _compose_context(self, ctype: ContextType, content, **kwargs):
  23. context = Context(ctype, content)
  24. context.kwargs = kwargs
  25. # context首次传入时,origin_ctype是None,
  26. # 引入的起因是:当输入语音时,会嵌套生成两个context,第一步语音转文本,第二步通过文本生成文字回复。
  27. # origin_ctype用于第二步文本回复时,判断是否需要匹配前缀,如果是私聊的语音,就不需要匹配前缀
  28. if 'origin_ctype' not in context:
  29. context['origin_ctype'] = ctype
  30. # context首次传入时,receiver是None,根据类型设置receiver
  31. first_in = 'receiver' not in context
  32. # 群名匹配过程,设置session_id和receiver
  33. if first_in: # context首次传入时,receiver是None,根据类型设置receiver
  34. config = conf()
  35. cmsg = context['msg']
  36. if cmsg.from_user_id == self.user_id:
  37. logger.debug("[WX]self message skipped")
  38. return None
  39. if context["isgroup"]:
  40. group_name = cmsg.other_user_nickname
  41. group_id = cmsg.other_user_id
  42. group_name_white_list = config.get('group_name_white_list', [])
  43. group_name_keyword_white_list = config.get('group_name_keyword_white_list', [])
  44. 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)]):
  45. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  46. session_id = cmsg.actual_user_id
  47. if any([group_name in group_chat_in_one_session, 'ALL_GROUP' in group_chat_in_one_session]):
  48. session_id = group_id
  49. else:
  50. return None
  51. context['session_id'] = session_id
  52. context['receiver'] = group_id
  53. else:
  54. context['session_id'] = cmsg.other_user_id
  55. context['receiver'] = cmsg.other_user_id
  56. # 消息内容匹配过程,并处理content
  57. if ctype == ContextType.TEXT:
  58. if first_in and "」\n- - - - - - -" in content: # 初次匹配 过滤引用消息
  59. logger.debug("[WX]reference query skipped")
  60. return None
  61. if context["isgroup"]: # 群聊
  62. # 校验关键字
  63. match_prefix = check_prefix(content, conf().get('group_chat_prefix'))
  64. match_contain = check_contain(content, conf().get('group_chat_keyword'))
  65. if match_prefix is not None or match_contain is not None:
  66. if match_prefix:
  67. content = content.replace(match_prefix, '', 1).strip()
  68. elif context['msg'].is_at and not conf().get("group_at_off", False):
  69. logger.info("[WX]receive group at, continue")
  70. pattern = f'@{self.name}(\u2005|\u0020)'
  71. content = re.sub(pattern, r'', content)
  72. elif context["origin_ctype"] == ContextType.VOICE:
  73. logger.info("[WX]receive group voice, checkprefix didn't match")
  74. return None
  75. else:
  76. return None
  77. else: # 单聊
  78. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  79. if match_prefix is not None: # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容
  80. content = content.replace(match_prefix, '', 1).strip()
  81. elif context["origin_ctype"] == ContextType.VOICE: # 如果源消息是私聊的语音消息,允许不匹配前缀,放宽条件
  82. pass
  83. else:
  84. return None
  85. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  86. if img_match_prefix:
  87. content = content.replace(img_match_prefix, '', 1).strip()
  88. context.type = ContextType.IMAGE_CREATE
  89. else:
  90. context.type = ContextType.TEXT
  91. context.content = content
  92. if 'desire_rtype' not in context and conf().get('always_reply_voice'):
  93. context['desire_rtype'] = ReplyType.VOICE
  94. elif context.type == ContextType.VOICE:
  95. if 'desire_rtype' not in context and conf().get('voice_reply_voice'):
  96. context['desire_rtype'] = ReplyType.VOICE
  97. return context
  98. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  99. def _handle(self, context: Context):
  100. if context is None or not context.content:
  101. return
  102. logger.debug('[WX] ready to handle context: {}'.format(context))
  103. # reply的构建步骤
  104. reply = self._generate_reply(context)
  105. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  106. # reply的包装步骤
  107. reply = self._decorate_reply(context, reply)
  108. # reply的发送步骤
  109. self._send_reply(context, reply)
  110. def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply:
  111. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  112. 'channel': self, 'context': context, 'reply': reply}))
  113. reply = e_context['reply']
  114. if not e_context.is_pass():
  115. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  116. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  117. reply = super().build_reply_content(context.content, context)
  118. elif context.type == ContextType.VOICE: # 语音消息
  119. cmsg = context['msg']
  120. cmsg.prepare()
  121. file_path = context.content
  122. wav_path = os.path.splitext(file_path)[0] + '.wav'
  123. try:
  124. any_to_wav(file_path, wav_path)
  125. except Exception as e: # 转换失败,直接使用mp3,对于某些api,mp3也可以识别
  126. logger.warning("[WX]any to wav error, use raw path. " + str(e))
  127. wav_path = file_path
  128. # 语音识别
  129. reply = super().build_voice_to_text(wav_path)
  130. # 删除临时文件
  131. try:
  132. os.remove(file_path)
  133. os.remove(wav_path)
  134. except Exception as e:
  135. logger.warning("[WX]delete temp file error: " + str(e))
  136. if reply.type == ReplyType.TEXT:
  137. new_context = self._compose_context(
  138. ContextType.TEXT, reply.content, **context.kwargs)
  139. if new_context:
  140. reply = self._generate_reply(new_context)
  141. else:
  142. return
  143. else:
  144. logger.error('[WX] unknown context type: {}'.format(context.type))
  145. return
  146. return reply
  147. def _decorate_reply(self, context: Context, reply: Reply) -> Reply:
  148. if reply and reply.type:
  149. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  150. 'channel': self, 'context': context, 'reply': reply}))
  151. reply = e_context['reply']
  152. desire_rtype = context.get('desire_rtype')
  153. if not e_context.is_pass() and reply and reply.type:
  154. if reply.type == ReplyType.TEXT:
  155. reply_text = reply.content
  156. if desire_rtype == ReplyType.VOICE:
  157. reply = super().build_text_to_voice(reply.content)
  158. return self._decorate_reply(context, reply)
  159. if context['isgroup']:
  160. reply_text = '@' + context['msg'].actual_user_nickname + ' ' + reply_text.strip()
  161. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  162. else:
  163. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  164. reply.content = reply_text
  165. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  166. reply.content = str(reply.type)+":\n" + reply.content
  167. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  168. pass
  169. else:
  170. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  171. return
  172. if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
  173. logger.warning('[WX] desire_rtype: {}, but reply type: {}'.format(context.get('desire_rtype'), reply.type))
  174. return reply
  175. def _send_reply(self, context: Context, reply: Reply):
  176. if reply and reply.type:
  177. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  178. 'channel': self, 'context': context, 'reply': reply}))
  179. reply = e_context['reply']
  180. if not e_context.is_pass() and reply and reply.type:
  181. logger.debug('[WX] ready to send reply: {}, context: {}'.format(reply, context))
  182. self._send(reply, context)
  183. def _send(self, reply: Reply, context: Context, retry_cnt = 0):
  184. try:
  185. self.send(reply, context)
  186. except Exception as e:
  187. logger.error('[WX] sendMsg error: {}'.format(str(e)))
  188. if isinstance(e, NotImplementedError):
  189. return
  190. logger.exception(e)
  191. if retry_cnt < 2:
  192. time.sleep(3+3*retry_cnt)
  193. self._send(reply, context, retry_cnt+1)
  194. def check_prefix(content, prefix_list):
  195. for prefix in prefix_list:
  196. if content.startswith(prefix):
  197. return prefix
  198. return None
  199. def check_contain(content, keyword_list):
  200. if not keyword_list:
  201. return None
  202. for ky in keyword_list:
  203. if content.find(ky) != -1:
  204. return True
  205. return None