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.

79 lines
3.2KB

  1. import time
  2. import web
  3. from channel.wechatmp.wechatmp_message import WeChatMPMessage
  4. from bridge.context import *
  5. from bridge.reply import *
  6. from channel.wechatmp.common import *
  7. from channel.wechatmp.wechatmp_channel import WechatMPChannel
  8. from wechatpy import parse_message
  9. from common.log import logger
  10. from config import conf
  11. from wechatpy.replies import create_reply
  12. # This class is instantiated once per query
  13. class Query:
  14. def GET(self):
  15. return verify_server(web.input())
  16. def POST(self):
  17. # Make sure to return the instance that first created, @singleton will do that.
  18. channel = WechatMPChannel()
  19. try:
  20. verify_server(web.input())
  21. message = web.data() # todo crypto
  22. # logger.debug("[wechatmp] Receive request:\n" + webData.decode("utf-8"))
  23. msg = parse_message(message)
  24. if msg.type == "event":
  25. logger.info(
  26. "[wechatmp] Event {} from {}".format(
  27. msg.event, msg.source
  28. )
  29. )
  30. if msg.event in ["subscribe", "subscribe_scan"]:
  31. reply_text = subscribe_msg()
  32. replyPost = create_reply(reply_text, msg)
  33. return replyPost.render()
  34. else:
  35. return "success"
  36. wechatmp_msg = WeChatMPMessage(msg, client=channel.client)
  37. if wechatmp_msg.ctype in [ContextType.TEXT, ContextType.IMAGE, ContextType.VOICE]:
  38. from_user = wechatmp_msg.from_user_id
  39. content = wechatmp_msg.content
  40. message_id = wechatmp_msg.msg_id
  41. logger.info(
  42. "[wechatmp] {}:{} Receive post query {} {}: {}".format(
  43. web.ctx.env.get("REMOTE_ADDR"),
  44. web.ctx.env.get("REMOTE_PORT"),
  45. from_user,
  46. message_id,
  47. content,
  48. )
  49. )
  50. if msg.type == "voice" and wechatmp_msg.ctype == ContextType.TEXT and conf().get("voice_reply_voice", False):
  51. context = channel._compose_context(
  52. wechatmp_msg.ctype, content, isgroup=False, desire_rtype=ReplyType.VOICE, msg=wechatmp_msg
  53. )
  54. else:
  55. context = channel._compose_context(
  56. wechatmp_msg.ctype, content, isgroup=False, msg=wechatmp_msg
  57. )
  58. if context:
  59. # set private openai_api_key
  60. # if from_user is not changed in itchat, this can be placed at chat_channel
  61. user_data = conf().get_user_data(from_user)
  62. context["openai_api_key"] = user_data.get(
  63. "openai_api_key"
  64. ) # None or user openai_api_key
  65. channel.produce(context)
  66. # The reply will be sent by channel.send() in another thread
  67. return "success"
  68. else:
  69. logger.info("暂且不处理")
  70. return "success"
  71. except Exception as exc:
  72. logger.exception(exc)
  73. return exc