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.

106 satır
3.9KB

  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. import web
  4. from wechatpy.enterprise import WeChatClient, create_reply, parse_message
  5. from wechatpy.enterprise.crypto import WeChatCrypto
  6. from wechatpy.enterprise.exceptions import InvalidCorpIdException
  7. from wechatpy.exceptions import InvalidSignatureException
  8. from bridge.context import Context
  9. from bridge.reply import Reply, ReplyType
  10. from channel.chat_channel import ChatChannel
  11. from channel.wechatcom.wechatcom_message import WechatComMessage
  12. from common.log import logger
  13. from common.singleton import singleton
  14. from config import conf
  15. @singleton
  16. class WechatComChannel(ChatChannel):
  17. NOT_SUPPORT_REPLYTYPE = [ReplyType.IMAGE, ReplyType.VOICE]
  18. def __init__(self):
  19. super().__init__()
  20. self.corp_id = conf().get("wechatcom_corp_id")
  21. self.secret = conf().get("wechatcom_secret")
  22. self.agent_id = conf().get("wechatcom_agent_id")
  23. self.token = conf().get("wechatcom_token")
  24. self.aes_key = conf().get("wechatcom_aes_key")
  25. print(self.corp_id, self.secret, self.agent_id, self.token, self.aes_key)
  26. logger.info(
  27. "[wechatcom] init: corp_id: {}, secret: {}, agent_id: {}, token: {}, aes_key: {}".format(
  28. self.corp_id, self.secret, self.agent_id, self.token, self.aes_key
  29. )
  30. )
  31. self.crypto = WeChatCrypto(self.token, self.aes_key, self.corp_id)
  32. self.client = WeChatClient(self.corp_id, self.secret) # todo: 这里可能有线程安全问题
  33. def startup(self):
  34. # start message listener
  35. urls = ("/wxcom", "channel.wechatcom.wechatcom_channel.Query")
  36. app = web.application(urls, globals(), autoreload=False)
  37. port = conf().get("wechatcom_port", 8080)
  38. web.httpserver.runsimple(app.wsgifunc(), ("0.0.0.0", port))
  39. def send(self, reply: Reply, context: Context):
  40. print("send reply: ", reply.content, context["receiver"])
  41. receiver = context["receiver"]
  42. reply_text = reply.content
  43. self.client.message.send_text(self.agent_id, receiver, reply_text)
  44. logger.info("[send] Do send to {}: {}".format(receiver, reply_text))
  45. class Query:
  46. def GET(self):
  47. channel = WechatComChannel()
  48. params = web.input()
  49. signature = params.msg_signature
  50. timestamp = params.timestamp
  51. nonce = params.nonce
  52. echostr = params.echostr
  53. print(params)
  54. try:
  55. echostr = channel.crypto.check_signature(
  56. signature, timestamp, nonce, echostr
  57. )
  58. except InvalidSignatureException:
  59. raise web.Forbidden()
  60. return echostr
  61. def POST(self):
  62. channel = WechatComChannel()
  63. params = web.input()
  64. signature = params.msg_signature
  65. timestamp = params.timestamp
  66. nonce = params.nonce
  67. try:
  68. message = channel.crypto.decrypt_message(
  69. web.data(), signature, timestamp, nonce
  70. )
  71. except (InvalidSignatureException, InvalidCorpIdException):
  72. raise web.Forbidden()
  73. print(message)
  74. msg = parse_message(message)
  75. print(msg)
  76. if msg.type == "event":
  77. if msg.event == "subscribe":
  78. reply = create_reply("感谢关注", msg).render()
  79. res = channel.crypto.encrypt_message(reply, nonce, timestamp)
  80. return res
  81. else:
  82. try:
  83. wechatcom_msg = WechatComMessage(msg, client=channel.client)
  84. except NotImplementedError as e:
  85. logger.debug("[wechatcom] " + str(e))
  86. return "success"
  87. context = channel._compose_context(
  88. wechatcom_msg.ctype,
  89. wechatcom_msg.content,
  90. isgroup=False,
  91. msg=wechatcom_msg,
  92. )
  93. if context:
  94. channel.produce(context)
  95. return "success"