Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

233 lignes
12KB

  1. # -*- coding: utf-8 -*-
  2. import asyncio
  3. import imghdr
  4. import io
  5. import os
  6. import threading
  7. import time
  8. import requests
  9. import web
  10. from wechatpy.crypto import WeChatCrypto
  11. from wechatpy.exceptions import WeChatClientException
  12. from collections import defaultdict
  13. from bridge.context import *
  14. from bridge.reply import *
  15. from channel.chat_channel import ChatChannel
  16. from channel.wechatmp.common import *
  17. from channel.wechatmp.wechatmp_client import WechatMPClient
  18. from common.log import logger
  19. from common.singleton import singleton
  20. from common.utils import split_string_by_utf8_length
  21. from config import conf
  22. from voice.audio_convert import any_to_mp3, split_audio
  23. # If using SSL, uncomment the following lines, and modify the certificate path.
  24. # from cheroot.server import HTTPServer
  25. # from cheroot.ssl.builtin import BuiltinSSLAdapter
  26. # HTTPServer.ssl_adapter = BuiltinSSLAdapter(
  27. # certificate='/ssl/cert.pem',
  28. # private_key='/ssl/cert.key')
  29. @singleton
  30. class WechatMPChannel(ChatChannel):
  31. def __init__(self, passive_reply=True):
  32. super().__init__()
  33. self.passive_reply = passive_reply
  34. self.NOT_SUPPORT_REPLYTYPE = []
  35. appid = conf().get("wechatmp_app_id")
  36. secret = conf().get("wechatmp_app_secret")
  37. token = conf().get("wechatmp_token")
  38. aes_key = conf().get("wechatmp_aes_key")
  39. self.client = WechatMPClient(appid, secret)
  40. self.crypto = None
  41. if aes_key:
  42. self.crypto = WeChatCrypto(token, aes_key, appid)
  43. if self.passive_reply:
  44. # Cache the reply to the user's first message
  45. self.cache_dict = defaultdict(list)
  46. # Record whether the current message is being processed
  47. self.running = set()
  48. # Count the request from wechat official server by message_id
  49. self.request_cnt = dict()
  50. # The permanent media need to be deleted to avoid media number limit
  51. self.delete_media_loop = asyncio.new_event_loop()
  52. t = threading.Thread(target=self.start_loop, args=(self.delete_media_loop,))
  53. t.setDaemon(True)
  54. t.start()
  55. def startup(self):
  56. if self.passive_reply:
  57. urls = ("/wx", "channel.wechatmp.passive_reply.Query")
  58. else:
  59. urls = ("/wx", "channel.wechatmp.active_reply.Query")
  60. app = web.application(urls, globals(), autoreload=False)
  61. port = conf().get("wechatmp_port", 8080)
  62. web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
  63. def start_loop(self, loop):
  64. asyncio.set_event_loop(loop)
  65. loop.run_forever()
  66. async def delete_media(self, media_id):
  67. logger.debug("[wechatmp] permanent media {} will be deleted in 10s".format(media_id))
  68. await asyncio.sleep(10)
  69. self.client.material.delete(media_id)
  70. logger.info("[wechatmp] permanent media {} has been deleted".format(media_id))
  71. def send(self, reply: Reply, context: Context):
  72. receiver = context["receiver"]
  73. if self.passive_reply:
  74. if reply.type == ReplyType.TEXT or reply.type == ReplyType.INFO or reply.type == ReplyType.ERROR:
  75. reply_text = reply.content
  76. logger.info("[wechatmp] text cached, receiver {}\n{}".format(receiver, reply_text))
  77. self.cache_dict[receiver].append(("text", reply_text))
  78. elif reply.type == ReplyType.VOICE:
  79. try:
  80. voice_file_path = reply.content
  81. with open(voice_file_path, "rb") as f:
  82. # support: <2M, <60s, mp3/wma/wav/amr
  83. response = self.client.material.add("voice", f)
  84. logger.debug("[wechatmp] upload voice response: {}".format(response))
  85. # 根据文件大小估计一个微信自动审核的时间,审核结束前返回将会导致语音无法播放,这个估计有待验证
  86. f_size = os.fstat(f.fileno()).st_size
  87. time.sleep(1.0 + 2 * f_size / 1024 / 1024)
  88. # todo check media_id
  89. except WeChatClientException as e:
  90. logger.error("[wechatmp] upload voice failed: {}".format(e))
  91. return
  92. media_id = response["media_id"]
  93. logger.info("[wechatmp] voice uploaded, receiver {}, media_id {}".format(receiver, media_id))
  94. self.cache_dict[receiver].append(("voice", media_id))
  95. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  96. img_url = reply.content
  97. pic_res = requests.get(img_url, stream=True)
  98. image_storage = io.BytesIO()
  99. for block in pic_res.iter_content(1024):
  100. image_storage.write(block)
  101. image_storage.seek(0)
  102. image_type = imghdr.what(image_storage)
  103. filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type
  104. content_type = "image/" + image_type
  105. try:
  106. response = self.client.material.add("image", (filename, image_storage, content_type))
  107. logger.debug("[wechatmp] upload image response: {}".format(response))
  108. except WeChatClientException as e:
  109. logger.error("[wechatmp] upload image failed: {}".format(e))
  110. return
  111. media_id = response["media_id"]
  112. logger.info("[wechatmp] image uploaded, receiver {}, media_id {}".format(receiver, media_id))
  113. self.cache_dict[receiver].append(("image", media_id))
  114. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  115. image_storage = reply.content
  116. image_storage.seek(0)
  117. image_type = imghdr.what(image_storage)
  118. filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type
  119. content_type = "image/" + image_type
  120. try:
  121. response = self.client.material.add("image", (filename, image_storage, content_type))
  122. logger.debug("[wechatmp] upload image response: {}".format(response))
  123. except WeChatClientException as e:
  124. logger.error("[wechatmp] upload image failed: {}".format(e))
  125. return
  126. media_id = response["media_id"]
  127. logger.info("[wechatmp] image uploaded, receiver {}, media_id {}".format(receiver, media_id))
  128. self.cache_dict[receiver].append(("image", media_id))
  129. else:
  130. if reply.type == ReplyType.TEXT or reply.type == ReplyType.INFO or reply.type == ReplyType.ERROR:
  131. reply_text = reply.content
  132. texts = split_string_by_utf8_length(reply_text, MAX_UTF8_LEN)
  133. if len(texts) > 1:
  134. logger.info("[wechatmp] text too long, split into {} parts".format(len(texts)))
  135. for i, text in enumerate(texts):
  136. self.client.message.send_text(receiver, text)
  137. if i != len(texts) - 1:
  138. time.sleep(0.5) # 休眠0.5秒,防止发送过快乱序
  139. logger.info("[wechatmp] Do send text to {}: {}".format(receiver, reply_text))
  140. elif reply.type == ReplyType.VOICE:
  141. try:
  142. file_path = reply.content
  143. file_name = os.path.basename(file_path)
  144. file_type = os.path.splitext(file_name)[1]
  145. if file_type == ".mp3":
  146. file_type = "audio/mpeg"
  147. elif file_type == ".amr":
  148. file_type = "audio/amr"
  149. else:
  150. mp3_file = os.path.splitext(file_path)[0] + ".mp3"
  151. any_to_mp3(file_path, mp3_file)
  152. file_path = mp3_file
  153. file_name = os.path.basename(file_path)
  154. file_type = "audio/mpeg"
  155. logger.info("[wechatmp] file_name: {}, file_type: {} ".format(file_name, file_type))
  156. media_ids = []
  157. duration, files = split_audio(file_path, 60 * 1000)
  158. if len(files) > 1:
  159. logger.info("[wechatmp] voice too long {}s > 60s , split into {} parts".format(duration / 1000.0, len(files)))
  160. for path in files:
  161. # support: <2M, <60s, AMR\MP3
  162. response = self.client.media.upload("voice", (os.path.basename(path), open(path, "rb"), file_type))
  163. logger.debug("[wechatcom] upload voice response: {}".format(response))
  164. media_ids.append(response["media_id"])
  165. os.remove(path)
  166. except WeChatClientException as e:
  167. logger.error("[wechatmp] upload voice failed: {}".format(e))
  168. return
  169. try:
  170. os.remove(file_path)
  171. except Exception:
  172. pass
  173. for media_id in media_ids:
  174. self.client.message.send_voice(receiver, media_id)
  175. time.sleep(1)
  176. logger.info("[wechatmp] Do send voice to {}".format(receiver))
  177. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  178. img_url = reply.content
  179. pic_res = requests.get(img_url, stream=True)
  180. image_storage = io.BytesIO()
  181. for block in pic_res.iter_content(1024):
  182. image_storage.write(block)
  183. image_storage.seek(0)
  184. image_type = imghdr.what(image_storage)
  185. filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type
  186. content_type = "image/" + image_type
  187. try:
  188. response = self.client.media.upload("image", (filename, image_storage, content_type))
  189. logger.debug("[wechatmp] upload image response: {}".format(response))
  190. except WeChatClientException as e:
  191. logger.error("[wechatmp] upload image failed: {}".format(e))
  192. return
  193. self.client.message.send_image(receiver, response["media_id"])
  194. logger.info("[wechatmp] Do send image to {}".format(receiver))
  195. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  196. image_storage = reply.content
  197. image_storage.seek(0)
  198. image_type = imghdr.what(image_storage)
  199. filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type
  200. content_type = "image/" + image_type
  201. try:
  202. response = self.client.media.upload("image", (filename, image_storage, content_type))
  203. logger.debug("[wechatmp] upload image response: {}".format(response))
  204. except WeChatClientException as e:
  205. logger.error("[wechatmp] upload image failed: {}".format(e))
  206. return
  207. self.client.message.send_image(receiver, response["media_id"])
  208. logger.info("[wechatmp] Do send image to {}".format(receiver))
  209. return
  210. def _success_callback(self, session_id, context, **kwargs): # 线程异常结束时的回调函数
  211. logger.debug("[wechatmp] Success to generate reply, msgId={}".format(context["msg"].msg_id))
  212. if self.passive_reply:
  213. self.running.remove(session_id)
  214. def _fail_callback(self, session_id, exception, context, **kwargs): # 线程异常结束时的回调函数
  215. logger.exception("[wechatmp] Fail to generate reply to user, msgId={}, exception={}".format(context["msg"].msg_id, exception))
  216. if self.passive_reply:
  217. assert session_id not in self.cache_dict
  218. self.running.remove(session_id)