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.

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