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.

wechaty_channel.py 13KB

1 år sedan
1 år sedan
1 år sedan
1 år sedan
1 år sedan
1 år sedan
1 år sedan
1 år sedan
1 år sedan
1 år sedan
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. # Wechaty判断is_at为True,返回的内容是过滤掉@之后的内容;而is_at为False,则会返回完整的内容
  138. # 故判断如果匹配到自定义前缀,则返回过滤掉前缀+空格后的内容,用于实现类似自定义+前缀触发生成AI图片的功能
  139. prefixes = config.get('group_chat_prefix')
  140. for prefix in prefixes:
  141. if content.startswith(prefix):
  142. content = content.replace(prefix, '', 1).strip()
  143. break
  144. if ('ALL_GROUP' in config.get('group_name_white_list') or room_name in config.get(
  145. 'group_name_white_list') or self.check_contain(room_name, config.get(
  146. 'group_name_keyword_white_list'))) and match_prefix:
  147. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  148. if img_match_prefix:
  149. content = content.split(img_match_prefix, 1)[1].strip()
  150. await self._do_send_group_img(content, room_id)
  151. else:
  152. await self._do_send_group(content, room_id, room_name, from_user_id, from_user_name)
  153. async def send(self, message: Union[str, Message, FileBox, Contact, UrlLink, MiniProgram], receiver):
  154. logger.info('[WX] sendMsg={}, receiver={}'.format(message, receiver))
  155. if receiver:
  156. contact = await bot.Contact.find(receiver)
  157. await contact.say(message)
  158. async def send_group(self, message: Union[str, Message, FileBox, Contact, UrlLink, MiniProgram], receiver):
  159. logger.info('[WX] sendMsg={}, receiver={}'.format(message, receiver))
  160. if receiver:
  161. room = await bot.Room.find(receiver)
  162. await room.say(message)
  163. async def _do_send(self, query, reply_user_id):
  164. try:
  165. if not query:
  166. return
  167. context = dict()
  168. context['session_id'] = reply_user_id
  169. reply_text = super().build_reply_content(query, context)
  170. if reply_text:
  171. await self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
  172. except Exception as e:
  173. logger.exception(e)
  174. async def _do_send_voice(self, query, reply_user_id):
  175. try:
  176. if not query:
  177. return
  178. context = dict()
  179. context['session_id'] = reply_user_id
  180. reply_text = super().build_reply_content(query, context)
  181. if reply_text:
  182. # 转换 mp3 文件为 silk 格式
  183. mp3_file = super().build_text_to_voice(reply_text)
  184. silk_file = mp3_file.replace(".mp3", ".silk")
  185. # Load the MP3 file
  186. audio = AudioSegment.from_file(mp3_file, format="mp3")
  187. # Convert to WAV format
  188. audio = audio.set_frame_rate(24000).set_channels(1)
  189. wav_data = audio.raw_data
  190. sample_width = audio.sample_width
  191. # Encode to SILK format
  192. silk_data = pysilk.encode(wav_data, 24000)
  193. # Save the silk file
  194. with open(silk_file, "wb") as f:
  195. f.write(silk_data)
  196. # 发送语音
  197. t = int(time.time())
  198. file_box = FileBox.from_file(silk_file, name=str(t) + '.silk')
  199. await self.send(file_box, reply_user_id)
  200. # 清除缓存文件
  201. os.remove(mp3_file)
  202. os.remove(silk_file)
  203. except Exception as e:
  204. logger.exception(e)
  205. async def _do_send_img(self, query, reply_user_id):
  206. try:
  207. if not query:
  208. return
  209. context = dict()
  210. context['type'] = 'IMAGE_CREATE'
  211. img_url = super().build_reply_content(query, context)
  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 = dict()
  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)
  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 = dict()
  247. context['type'] = 'IMAGE_CREATE'
  248. img_url = super().build_reply_content(query, context)
  249. if not img_url:
  250. return
  251. # 图片发送
  252. logger.info('[WX] sendImage, receiver={}'.format(reply_room_id))
  253. t = int(time.time())
  254. file_box = FileBox.from_url(url=img_url, name=str(t) + '.png')
  255. await self.send_group(file_box, reply_room_id)
  256. except Exception as e:
  257. logger.exception(e)
  258. def check_prefix(self, content, prefix_list):
  259. for prefix in prefix_list:
  260. if content.startswith(prefix):
  261. return prefix
  262. return None
  263. def check_contain(self, content, keyword_list):
  264. if not keyword_list:
  265. return None
  266. for ky in keyword_list:
  267. if content.find(ky) != -1:
  268. return True
  269. return None