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.

287 satır
12KB

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