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
2.7KB

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