選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

224 行
10KB

  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. elif context.type == ContextType.VOICE:
  93. if 'desire_rtype' not in context and conf().get('voice_reply_voice'):
  94. context['desire_rtype'] = ReplyType.VOICE
  95. return context
  96. # 处理消息 TODO: 如果wechaty解耦,此处逻辑可以放置到父类
  97. def _handle(self, context: Context):
  98. if context is None or not context.content:
  99. return
  100. logger.debug('[WX] ready to handle context: {}'.format(context))
  101. # reply的构建步骤
  102. reply = self._generate_reply(context)
  103. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  104. # reply的包装步骤
  105. reply = self._decorate_reply(context, reply)
  106. # reply的发送步骤
  107. self._send_reply(context, reply)
  108. def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply:
  109. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  110. 'channel': self, 'context': context, 'reply': reply}))
  111. reply = e_context['reply']
  112. if not e_context.is_pass():
  113. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  114. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  115. reply = super().build_reply_content(context.content, context)
  116. elif context.type == ContextType.VOICE: # 语音消息
  117. cmsg = context['msg']
  118. cmsg.prepare()
  119. file_path = context.content
  120. wav_path = os.path.splitext(file_path)[0] + '.wav'
  121. try:
  122. any_to_wav(file_path, wav_path)
  123. except Exception as e: # 转换失败,直接使用mp3,对于某些api,mp3也可以识别
  124. logger.warning("[WX]any to wav error, use raw path. " + str(e))
  125. wav_path = file_path
  126. # 语音识别
  127. reply = super().build_voice_to_text(wav_path)
  128. # 删除临时文件
  129. try:
  130. os.remove(file_path)
  131. os.remove(wav_path)
  132. except Exception as e:
  133. logger.warning("[WX]delete temp file error: " + str(e))
  134. if reply.type == ReplyType.TEXT:
  135. new_context = self._compose_context(
  136. ContextType.TEXT, reply.content, **context.kwargs)
  137. if new_context:
  138. reply = self._generate_reply(new_context)
  139. else:
  140. return
  141. else:
  142. logger.error('[WX] unknown context type: {}'.format(context.type))
  143. return
  144. return reply
  145. def _decorate_reply(self, context: Context, reply: Reply) -> Reply:
  146. if reply and reply.type:
  147. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  148. 'channel': self, 'context': context, 'reply': reply}))
  149. reply = e_context['reply']
  150. desire_rtype = context.get('desire_rtype')
  151. if not e_context.is_pass() and reply and reply.type:
  152. if reply.type == ReplyType.TEXT:
  153. reply_text = reply.content
  154. if desire_rtype == ReplyType.VOICE:
  155. reply = super().build_text_to_voice(reply.content)
  156. return self._decorate_reply(context, reply)
  157. if context['isgroup']:
  158. reply_text = '@' + context['msg'].actual_user_nickname + ' ' + reply_text.strip()
  159. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  160. else:
  161. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  162. reply.content = reply_text
  163. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  164. reply.content = str(reply.type)+":\n" + reply.content
  165. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  166. pass
  167. else:
  168. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  169. return
  170. if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
  171. logger.warning('[WX] desire_rtype: {}, but reply type: {}'.format(context.get('desire_rtype'), reply.type))
  172. return reply
  173. def _send_reply(self, context: Context, reply: Reply):
  174. if reply and reply.type:
  175. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  176. 'channel': self, 'context': context, 'reply': reply}))
  177. reply = e_context['reply']
  178. if not e_context.is_pass() and reply and reply.type:
  179. logger.debug('[WX] ready to send reply: {} to {}'.format(reply, context))
  180. self._send(reply, context)
  181. def _send(self, reply: Reply, context: Context, retry_cnt = 0):
  182. try:
  183. self.send(reply, context)
  184. except Exception as e:
  185. logger.error('[WX] sendMsg error: {}'.format(e))
  186. if retry_cnt < 2:
  187. time.sleep(3+3*retry_cnt)
  188. self._send(reply, context, retry_cnt+1)
  189. def check_prefix(content, prefix_list):
  190. for prefix in prefix_list:
  191. if content.startswith(prefix):
  192. return prefix
  193. return None
  194. def check_contain(content, keyword_list):
  195. if not keyword_list:
  196. return None
  197. for ky in keyword_list:
  198. if content.find(ky) != -1:
  199. return True
  200. return None