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.

wechatmp_channel.py 5.0KB

il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
il y a 1 an
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # -*- coding: utf-8 -*-
  2. import web
  3. import io
  4. import imghdr
  5. import requests
  6. from bridge.context import *
  7. from bridge.reply import *
  8. from channel.chat_channel import ChatChannel
  9. from channel.wechatmp.wechatmp_client import WechatMPClient
  10. from channel.wechatmp.common import *
  11. from common.expired_dict import ExpiredDict
  12. from common.log import logger
  13. from common.tmp_dir import TmpDir
  14. from common.singleton import singleton
  15. from config import conf
  16. # If using SSL, uncomment the following lines, and modify the certificate path.
  17. from cheroot.server import HTTPServer
  18. from cheroot.ssl.builtin import BuiltinSSLAdapter
  19. HTTPServer.ssl_adapter = BuiltinSSLAdapter(
  20. certificate='/ssl/cert.pem',
  21. private_key='/ssl/cert.key')
  22. @singleton
  23. class WechatMPChannel(ChatChannel):
  24. def __init__(self, passive_reply=True):
  25. super().__init__()
  26. self.passive_reply = passive_reply
  27. self.running = set()
  28. self.received_msgs = ExpiredDict(60 * 60 * 24)
  29. self.client = WechatMPClient()
  30. if self.passive_reply:
  31. self.NOT_SUPPORT_REPLYTYPE = [ReplyType.IMAGE, ReplyType.VOICE]
  32. self.cache_dict = dict()
  33. self.query1 = dict()
  34. self.query2 = dict()
  35. self.query3 = dict()
  36. else:
  37. self.NOT_SUPPORT_REPLYTYPE = []
  38. def startup(self):
  39. if self.passive_reply:
  40. urls = ("/wx", "channel.wechatmp.subscribe_account.Query")
  41. else:
  42. urls = ("/wx", "channel.wechatmp.service_account.Query")
  43. app = web.application(urls, globals(), autoreload=False)
  44. port = conf().get("wechatmp_port", 8080)
  45. web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
  46. def send(self, reply: Reply, context: Context):
  47. receiver = context["receiver"]
  48. if self.passive_reply:
  49. self.cache_dict[receiver] = reply.content
  50. logger.info("[wechatmp] reply cached reply to {}: {}".format(receiver, reply))
  51. else:
  52. if reply.type == ReplyType.TEXT or reply.type == ReplyType.INFO or reply.type == ReplyType.ERROR:
  53. reply_text = reply.content
  54. self.client.send_text(receiver, reply_text)
  55. logger.info("[wechatmp] Do send to {}: {}".format(receiver, reply_text))
  56. elif reply.type == ReplyType.VOICE:
  57. voice_file_path = reply.content
  58. logger.info("[wechatmp] voice file path {}".format(voice_file_path))
  59. with open(voice_file_path, 'rb') as f:
  60. filename = receiver + "-" + context["msg"].msg_id + ".mp3"
  61. media_id = self.client.upload_media("voice", (filename, f, "audio/mpeg"))
  62. self.client.send_voice(receiver, media_id)
  63. logger.info("[wechatmp] Do send voice to {}".format(receiver))
  64. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  65. img_url = reply.content
  66. pic_res = requests.get(img_url, stream=True)
  67. print(pic_res.headers)
  68. image_storage = io.BytesIO()
  69. for block in pic_res.iter_content(1024):
  70. image_storage.write(block)
  71. image_storage.seek(0)
  72. image_type = imghdr.what(image_storage)
  73. filename = receiver + "-" + context["msg"].msg_id + "." + image_type
  74. content_type = "image/" + image_type
  75. # content_type = pic_res.headers.get('content-type')
  76. media_id = self.client.upload_media("image", (filename, image_storage, content_type))
  77. self.client.send_image(receiver, media_id)
  78. logger.info("[wechatmp] sendImage url={}, receiver={}".format(img_url, receiver))
  79. elif reply.type == ReplyType.IMAGE: # 从文件读取图片
  80. image_storage = reply.content
  81. image_storage.seek(0)
  82. image_type = imghdr.what(image_storage)
  83. filename = receiver + "-" + context["msg"].msg_id + "." + image_type
  84. content_type = "image/" + image_type
  85. media_id = self.client.upload_media("image", (filename, image_storage, content_type))
  86. self.client.send_image(receiver, media_id)
  87. logger.info("[wechatmp] sendImage, receiver={}".format(receiver))
  88. return
  89. def _success_callback(self, session_id, context, **kwargs): # 线程异常结束时的回调函数
  90. logger.debug(
  91. "[wechatmp] Success to generate reply, msgId={}".format(
  92. context["msg"].msg_id
  93. )
  94. )
  95. if self.passive_reply:
  96. self.running.remove(session_id)
  97. def _fail_callback(self, session_id, exception, context, **kwargs): # 线程异常结束时的回调函数
  98. logger.exception(
  99. "[wechatmp] Fail to generate reply to user, msgId={}, exception={}".format(
  100. context["msg"].msg_id, exception
  101. )
  102. )
  103. if self.passive_reply:
  104. assert session_id not in self.cache_dict
  105. self.running.remove(session_id)