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.

wechaty_channel.py 13KB

1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
1 년 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. # encoding:utf-8
  2. """
  3. wechaty channel
  4. Python Wechaty - https://github.com/wechaty/python-wechaty
  5. """
  6. import io
  7. import os
  8. import json
  9. import time
  10. import asyncio
  11. import requests
  12. import pysilk
  13. import wave
  14. from pydub import AudioSegment
  15. from typing import Optional, Union
  16. from bridge.context import Context, ContextType
  17. from wechaty_puppet import MessageType, FileBox, ScanStatus # type: ignore
  18. from wechaty import Wechaty, Contact
  19. from wechaty.user import Message, Room, MiniProgram, UrlLink
  20. from channel.channel import Channel
  21. from common.log import logger
  22. from common.tmp_dir import TmpDir
  23. from config import conf
  24. class WechatyChannel(Channel):
  25. def __init__(self):
  26. pass
  27. def startup(self):
  28. asyncio.run(self.main())
  29. async def main(self):
  30. config = conf()
  31. # 使用PadLocal协议 比较稳定(免费web协议 os.environ['WECHATY_PUPPET_SERVICE_ENDPOINT'] = '127.0.0.1:8080')
  32. token = config.get('wechaty_puppet_service_token')
  33. os.environ['WECHATY_PUPPET_SERVICE_TOKEN'] = token
  34. global bot
  35. bot = Wechaty()
  36. bot.on('scan', self.on_scan)
  37. bot.on('login', self.on_login)
  38. bot.on('message', self.on_message)
  39. await bot.start()
  40. async def on_login(self, contact: Contact):
  41. logger.info('[WX] login user={}'.format(contact))
  42. async def on_scan(self, status: ScanStatus, qr_code: Optional[str] = None,
  43. data: Optional[str] = None):
  44. contact = self.Contact.load(self.contact_id)
  45. logger.info('[WX] scan user={}, scan status={}, scan qr_code={}'.format(contact, status.name, qr_code))
  46. # print(f'user <{contact}> scan status: {status.name} , 'f'qr_code: {qr_code}')
  47. async def on_message(self, msg: Message):
  48. """
  49. listen for message event
  50. """
  51. from_contact = msg.talker() # 获取消息的发送者
  52. to_contact = msg.to() # 接收人
  53. room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None
  54. from_user_id = from_contact.contact_id
  55. to_user_id = to_contact.contact_id # 接收人id
  56. # other_user_id = msg['User']['UserName'] # 对手方id
  57. content = msg.text()
  58. mention_content = await msg.mention_text() # 返回过滤掉@name后的消息
  59. match_prefix = self.check_prefix(content, conf().get('single_chat_prefix'))
  60. conversation: Union[Room, Contact] = from_contact if room is None else room
  61. if room is None and msg.type() == MessageType.MESSAGE_TYPE_TEXT:
  62. if not msg.is_self() and match_prefix is not None:
  63. # 好友向自己发送消息
  64. if match_prefix != '':
  65. str_list = content.split(match_prefix, 1)
  66. if len(str_list) == 2:
  67. content = str_list[1].strip()
  68. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  69. if img_match_prefix:
  70. content = content.split(img_match_prefix, 1)[1].strip()
  71. await self._do_send_img(content, from_user_id)
  72. else:
  73. await self._do_send(content, from_user_id)
  74. elif msg.is_self() and match_prefix:
  75. # 自己给好友发送消息
  76. str_list = content.split(match_prefix, 1)
  77. if len(str_list) == 2:
  78. content = str_list[1].strip()
  79. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  80. if img_match_prefix:
  81. content = content.split(img_match_prefix, 1)[1].strip()
  82. await self._do_send_img(content, to_user_id)
  83. else:
  84. await self._do_send(content, to_user_id)
  85. elif room is None and msg.type() == MessageType.MESSAGE_TYPE_AUDIO:
  86. if not msg.is_self(): # 接收语音消息
  87. # 下载语音文件
  88. voice_file = await msg.to_file_box()
  89. silk_file = TmpDir().path() + voice_file.name
  90. await voice_file.to_file(silk_file)
  91. logger.info("[WX]receive voice file: " + silk_file)
  92. # 将文件转成wav格式音频
  93. wav_file = silk_file.replace(".slk", ".wav")
  94. with open(silk_file, 'rb') as f:
  95. silk_data = f.read()
  96. pcm_data = pysilk.decode(silk_data)
  97. with wave.open(wav_file, 'wb') as wav_data:
  98. wav_data.setnchannels(1)
  99. wav_data.setsampwidth(2)
  100. wav_data.setframerate(24000)
  101. wav_data.writeframes(pcm_data)
  102. if os.path.exists(wav_file):
  103. converter_state = "true" # 转换wav成功
  104. else:
  105. converter_state = "false" # 转换wav失败
  106. logger.info("[WX]receive voice converter: " + converter_state)
  107. # 语音识别为文本
  108. query = super().build_voice_to_text(wav_file)
  109. # 交验关键字
  110. match_prefix = self.check_prefix(query, conf().get('single_chat_prefix'))
  111. if match_prefix is not None:
  112. if match_prefix != '':
  113. str_list = query.split(match_prefix, 1)
  114. if len(str_list) == 2:
  115. query = str_list[1].strip()
  116. # 返回消息
  117. if conf().get('voice_reply_voice'):
  118. await self._do_send_voice(query, from_user_id)
  119. else:
  120. await self._do_send(query, from_user_id)
  121. else:
  122. logger.info("[WX]receive voice check prefix: " + 'False')
  123. # 清除缓存文件
  124. os.remove(wav_file)
  125. os.remove(silk_file)
  126. elif room and msg.type() == MessageType.MESSAGE_TYPE_TEXT:
  127. # 群组&文本消息
  128. room_id = room.room_id
  129. room_name = await room.topic()
  130. from_user_id = from_contact.contact_id
  131. from_user_name = from_contact.name
  132. is_at = await msg.mention_self()
  133. content = mention_content
  134. config = conf()
  135. match_prefix = (is_at and not config.get("group_at_off", False)) \
  136. or self.check_prefix(content, config.get('group_chat_prefix')) \
  137. or self.check_contain(content, config.get('group_chat_keyword'))
  138. # Wechaty判断is_at为True,返回的内容是过滤掉@之后的内容;而is_at为False,则会返回完整的内容
  139. # 故判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容,用于实现类似自定义+前缀触发生成AI图片的功能
  140. prefixes = config.get('group_chat_prefix')
  141. for prefix in prefixes:
  142. if content.startswith(prefix):
  143. content = content.replace(prefix, '', 1).strip()
  144. break
  145. if ('ALL_GROUP' in config.get('group_name_white_list') or room_name in config.get(
  146. 'group_name_white_list') or self.check_contain(room_name, config.get(
  147. 'group_name_keyword_white_list'))) and match_prefix:
  148. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  149. if img_match_prefix:
  150. content = content.split(img_match_prefix, 1)[1].strip()
  151. await self._do_send_group_img(content, room_id)
  152. else:
  153. await self._do_send_group(content, room_id, room_name, from_user_id, from_user_name)
  154. async def send(self, message: Union[str, Message, FileBox, Contact, UrlLink, MiniProgram], receiver):
  155. logger.info('[WX] sendMsg={}, receiver={}'.format(message, receiver))
  156. if receiver:
  157. contact = await bot.Contact.find(receiver)
  158. await contact.say(message)
  159. async def send_group(self, message: Union[str, Message, FileBox, Contact, UrlLink, MiniProgram], receiver):
  160. logger.info('[WX] sendMsg={}, receiver={}'.format(message, receiver))
  161. if receiver:
  162. room = await bot.Room.find(receiver)
  163. await room.say(message)
  164. async def _do_send(self, query, reply_user_id):
  165. try:
  166. if not query:
  167. return
  168. context = Context(ContextType.TEXT, query)
  169. context['session_id'] = reply_user_id
  170. reply_text = super().build_reply_content(query, context).content
  171. if reply_text:
  172. await self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
  173. except Exception as e:
  174. logger.exception(e)
  175. async def _do_send_voice(self, query, reply_user_id):
  176. try:
  177. if not query:
  178. return
  179. context = Context(ContextType.TEXT, query)
  180. context['session_id'] = reply_user_id
  181. reply_text = super().build_reply_content(query, context).content
  182. if reply_text:
  183. # 转换 mp3 文件为 silk 格式
  184. mp3_file = super().build_text_to_voice(reply_text).content
  185. silk_file = mp3_file.replace(".mp3", ".silk")
  186. # Load the MP3 file
  187. audio = AudioSegment.from_file(mp3_file, format="mp3")
  188. # Convert to WAV format
  189. audio = audio.set_frame_rate(24000).set_channels(1)
  190. wav_data = audio.raw_data
  191. sample_width = audio.sample_width
  192. # Encode to SILK format
  193. silk_data = pysilk.encode(wav_data, 24000)
  194. # Save the silk file
  195. with open(silk_file, "wb") as f:
  196. f.write(silk_data)
  197. # 发送语音
  198. t = int(time.time())
  199. file_box = FileBox.from_file(silk_file, name=str(t) + '.silk')
  200. await self.send(file_box, reply_user_id)
  201. # 清除缓存文件
  202. os.remove(mp3_file)
  203. os.remove(silk_file)
  204. except Exception as e:
  205. logger.exception(e)
  206. async def _do_send_img(self, query, reply_user_id):
  207. try:
  208. if not query:
  209. return
  210. context = Context(ContextType.IMAGE_CREATE, query)
  211. img_url = super().build_reply_content(query, context).content
  212. if not img_url:
  213. return
  214. # 图片下载
  215. # pic_res = requests.get(img_url, stream=True)
  216. # image_storage = io.BytesIO()
  217. # for block in pic_res.iter_content(1024):
  218. # image_storage.write(block)
  219. # image_storage.seek(0)
  220. # 图片发送
  221. logger.info('[WX] sendImage, receiver={}'.format(reply_user_id))
  222. t = int(time.time())
  223. file_box = FileBox.from_url(url=img_url, name=str(t) + '.png')
  224. await self.send(file_box, reply_user_id)
  225. except Exception as e:
  226. logger.exception(e)
  227. async def _do_send_group(self, query, group_id, group_name, group_user_id, group_user_name):
  228. if not query:
  229. return
  230. context = Context(ContextType.TEXT, query)
  231. group_chat_in_one_session = conf().get('group_chat_in_one_session', [])
  232. if ('ALL_GROUP' in group_chat_in_one_session or \
  233. group_name in group_chat_in_one_session or \
  234. self.check_contain(group_name, group_chat_in_one_session)):
  235. context['session_id'] = str(group_id)
  236. else:
  237. context['session_id'] = str(group_id) + '-' + str(group_user_id)
  238. reply_text = super().build_reply_content(query, context).content
  239. if reply_text:
  240. reply_text = '@' + group_user_name + ' ' + reply_text.strip()
  241. await self.send_group(conf().get("group_chat_reply_prefix", "") + reply_text, group_id)
  242. async def _do_send_group_img(self, query, reply_room_id):
  243. try:
  244. if not query:
  245. return
  246. context = Context(ContextType.IMAGE_CREATE, query)
  247. img_url = super().build_reply_content(query, context).content
  248. if not img_url:
  249. return
  250. # 图片发送
  251. logger.info('[WX] sendImage, receiver={}'.format(reply_room_id))
  252. t = int(time.time())
  253. file_box = FileBox.from_url(url=img_url, name=str(t) + '.png')
  254. await self.send_group(file_box, reply_room_id)
  255. except Exception as e:
  256. logger.exception(e)
  257. def check_prefix(self, content, prefix_list):
  258. for prefix in prefix_list:
  259. if content.startswith(prefix):
  260. return prefix
  261. return None
  262. def check_contain(self, content, keyword_list):
  263. if not keyword_list:
  264. return None
  265. for ky in keyword_list:
  266. if content.find(ky) != -1:
  267. return True
  268. return None