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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 and not config.get('trigger_by_self', False):
  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. flag = False
  66. if match_prefix is not None or match_contain is not None:
  67. flag = True
  68. if match_prefix:
  69. content = content.replace(match_prefix, '', 1).strip()
  70. if context['msg'].is_at:
  71. logger.info("[WX]receive group at")
  72. if not conf().get("group_at_off", False):
  73. flag = True
  74. pattern = f'@{self.name}(\u2005|\u0020)'
  75. content = re.sub(pattern, r'', content)
  76. if not flag:
  77. if context["origin_ctype"] == ContextType.VOICE:
  78. logger.info("[WX]receive group voice, but checkprefix didn't match")
  79. return None
  80. else: # 单聊
  81. match_prefix = check_prefix(content, conf().get('single_chat_prefix'))
  82. if match_prefix is not None: # 判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容
  83. content = content.replace(match_prefix, '', 1).strip()
  84. elif context["origin_ctype"] == ContextType.VOICE: # 如果源消息是私聊的语音消息,允许不匹配前缀,放宽条件
  85. pass
  86. else:
  87. return None
  88. img_match_prefix = check_prefix(content, conf().get('image_create_prefix'))
  89. if img_match_prefix:
  90. content = content.replace(img_match_prefix, '', 1).strip()
  91. context.type = ContextType.IMAGE_CREATE
  92. else:
  93. context.type = ContextType.TEXT
  94. context.content = content
  95. if 'desire_rtype' not in context and conf().get('always_reply_voice'):
  96. context['desire_rtype'] = ReplyType.VOICE
  97. elif context.type == ContextType.VOICE:
  98. if 'desire_rtype' not in context and conf().get('voice_reply_voice'):
  99. context['desire_rtype'] = ReplyType.VOICE
  100. return context
  101. def _handle(self, context: Context):
  102. if context is None or not context.content:
  103. return
  104. logger.debug('[WX] ready to handle context: {}'.format(context))
  105. # reply的构建步骤
  106. reply = self._generate_reply(context)
  107. logger.debug('[WX] ready to decorate reply: {}'.format(reply))
  108. # reply的包装步骤
  109. reply = self._decorate_reply(context, reply)
  110. # reply的发送步骤
  111. self._send_reply(context, reply)
  112. def _generate_reply(self, context: Context, reply: Reply = Reply()) -> Reply:
  113. e_context = PluginManager().emit_event(EventContext(Event.ON_HANDLE_CONTEXT, {
  114. 'channel': self, 'context': context, 'reply': reply}))
  115. reply = e_context['reply']
  116. if not e_context.is_pass():
  117. logger.debug('[WX] ready to handle context: type={}, content={}'.format(context.type, context.content))
  118. if context.type == ContextType.TEXT or context.type == ContextType.IMAGE_CREATE: # 文字和图片消息
  119. reply = super().build_reply_content(context.content, context)
  120. elif context.type == ContextType.VOICE: # 语音消息
  121. cmsg = context['msg']
  122. cmsg.prepare()
  123. file_path = context.content
  124. wav_path = os.path.splitext(file_path)[0] + '.wav'
  125. try:
  126. any_to_wav(file_path, wav_path)
  127. except Exception as e: # 转换失败,直接使用mp3,对于某些api,mp3也可以识别
  128. logger.warning("[WX]any to wav error, use raw path. " + str(e))
  129. wav_path = file_path
  130. # 语音识别
  131. reply = super().build_voice_to_text(wav_path)
  132. # 删除临时文件
  133. try:
  134. os.remove(file_path)
  135. if wav_path != file_path:
  136. os.remove(wav_path)
  137. except Exception as e:
  138. pass
  139. # logger.warning("[WX]delete temp file error: " + str(e))
  140. if reply.type == ReplyType.TEXT:
  141. new_context = self._compose_context(
  142. ContextType.TEXT, reply.content, **context.kwargs)
  143. if new_context:
  144. reply = self._generate_reply(new_context)
  145. else:
  146. return
  147. else:
  148. logger.error('[WX] unknown context type: {}'.format(context.type))
  149. return
  150. return reply
  151. def _decorate_reply(self, context: Context, reply: Reply) -> Reply:
  152. if reply and reply.type:
  153. e_context = PluginManager().emit_event(EventContext(Event.ON_DECORATE_REPLY, {
  154. 'channel': self, 'context': context, 'reply': reply}))
  155. reply = e_context['reply']
  156. desire_rtype = context.get('desire_rtype')
  157. if not e_context.is_pass() and reply and reply.type:
  158. if reply.type == ReplyType.TEXT:
  159. reply_text = reply.content
  160. if desire_rtype == ReplyType.VOICE:
  161. reply = super().build_text_to_voice(reply.content)
  162. return self._decorate_reply(context, reply)
  163. if context['isgroup']:
  164. reply_text = '@' + context['msg'].actual_user_nickname + ' ' + reply_text.strip()
  165. reply_text = conf().get("group_chat_reply_prefix", "")+reply_text
  166. else:
  167. reply_text = conf().get("single_chat_reply_prefix", "")+reply_text
  168. reply.content = reply_text
  169. elif reply.type == ReplyType.ERROR or reply.type == ReplyType.INFO:
  170. reply.content = str(reply.type)+":\n" + reply.content
  171. elif reply.type == ReplyType.IMAGE_URL or reply.type == ReplyType.VOICE or reply.type == ReplyType.IMAGE:
  172. pass
  173. else:
  174. logger.error('[WX] unknown reply type: {}'.format(reply.type))
  175. return
  176. if desire_rtype and desire_rtype != reply.type and reply.type not in [ReplyType.ERROR, ReplyType.INFO]:
  177. logger.warning('[WX] desire_rtype: {}, but reply type: {}'.format(context.get('desire_rtype'), reply.type))
  178. return reply
  179. def _send_reply(self, context: Context, reply: Reply):
  180. if reply and reply.type:
  181. e_context = PluginManager().emit_event(EventContext(Event.ON_SEND_REPLY, {
  182. 'channel': self, 'context': context, 'reply': reply}))
  183. reply = e_context['reply']
  184. if not e_context.is_pass() and reply and reply.type:
  185. logger.debug('[WX] ready to send reply: {}, context: {}'.format(reply, context))
  186. self._send(reply, context)
  187. def _send(self, reply: Reply, context: Context, retry_cnt = 0):
  188. try:
  189. self.send(reply, context)
  190. except Exception as e:
  191. logger.error('[WX] sendMsg error: {}'.format(str(e)))
  192. if isinstance(e, NotImplementedError):
  193. return
  194. logger.exception(e)
  195. if retry_cnt < 2:
  196. time.sleep(3+3*retry_cnt)
  197. self._send(reply, context, retry_cnt+1)
  198. def check_prefix(content, prefix_list):
  199. for prefix in prefix_list:
  200. if content.startswith(prefix):
  201. return prefix
  202. return None
  203. def check_contain(content, keyword_list):
  204. if not keyword_list:
  205. return None
  206. for ky in keyword_list:
  207. if content.find(ky) != -1:
  208. return True
  209. return None