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.

75 lines
3.0KB

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