Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

71 rinda
2.6KB

  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 wechatmp_msg.msg_type == "text" or wechatmp_msg.msg_type == "voice":
  22. from_user = wechatmp_msg.from_user_id
  23. message = wechatmp_msg.content.decode("utf-8")
  24. message_id = wechatmp_msg.msg_id
  25. logger.info(
  26. "[wechatmp] {}:{} Receive post query {} {}: {}".format(
  27. web.ctx.env.get("REMOTE_ADDR"),
  28. web.ctx.env.get("REMOTE_PORT"),
  29. from_user,
  30. message_id,
  31. message,
  32. )
  33. )
  34. context = channel._compose_context(
  35. ContextType.TEXT, message, isgroup=False, msg=wechatmp_msg
  36. )
  37. if context:
  38. # set private openai_api_key
  39. # if from_user is not changed in itchat, this can be placed at chat_channel
  40. user_data = conf().get_user_data(from_user)
  41. context["openai_api_key"] = user_data.get(
  42. "openai_api_key"
  43. ) # None or user openai_api_key
  44. channel.produce(context)
  45. # The reply will be sent by channel.send() in another thread
  46. return "success"
  47. elif wechatmp_msg.msg_type == "event":
  48. logger.info(
  49. "[wechatmp] Event {} from {}".format(
  50. wechatmp_msg.Event, wechatmp_msg.from_user_id
  51. )
  52. )
  53. content = subscribe_msg()
  54. replyMsg = reply.TextMsg(
  55. wechatmp_msg.from_user_id, wechatmp_msg.to_user_id, content
  56. )
  57. return replyMsg.send()
  58. else:
  59. logger.info("暂且不处理")
  60. return "success"
  61. except Exception as exc:
  62. logger.exception(exc)
  63. return exc