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.

78 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. message = web.data() # todo crypto
  21. # logger.debug("[wechatmp] Receive request:\n" + webData.decode("utf-8"))
  22. msg = parse_message(message)
  23. if msg.type == "event":
  24. logger.info(
  25. "[wechatmp] Event {} from {}".format(
  26. msg.event, msg.source
  27. )
  28. )
  29. if msg.event in ["subscribe", "subscribe_scan"]:
  30. reply_text = subscribe_msg()
  31. replyPost = create_reply(reply_text, msg)
  32. return replyPost.render()
  33. else:
  34. return "success"
  35. wechatmp_msg = WeChatMPMessage(msg, client=channel.client)
  36. if wechatmp_msg.ctype in [ContextType.TEXT, ContextType.IMAGE, ContextType.VOICE]:
  37. from_user = wechatmp_msg.from_user_id
  38. content = wechatmp_msg.content
  39. message_id = wechatmp_msg.msg_id
  40. logger.info(
  41. "[wechatmp] {}:{} Receive post query {} {}: {}".format(
  42. web.ctx.env.get("REMOTE_ADDR"),
  43. web.ctx.env.get("REMOTE_PORT"),
  44. from_user,
  45. message_id,
  46. content,
  47. )
  48. )
  49. if msg.type == "voice" and wechatmp_msg.ctype == ContextType.TEXT and conf().get("voice_reply_voice", False):
  50. context = channel._compose_context(
  51. wechatmp_msg.ctype, content, isgroup=False, desire_rtype=ReplyType.VOICE, msg=wechatmp_msg
  52. )
  53. else:
  54. context = channel._compose_context(
  55. wechatmp_msg.ctype, content, isgroup=False, msg=wechatmp_msg
  56. )
  57. if context:
  58. # set private openai_api_key
  59. # if from_user is not changed in itchat, this can be placed at chat_channel
  60. user_data = conf().get_user_data(from_user)
  61. context["openai_api_key"] = user_data.get(
  62. "openai_api_key"
  63. ) # None or user openai_api_key
  64. channel.produce(context)
  65. # The reply will be sent by channel.send() in another thread
  66. return "success"
  67. else:
  68. logger.info("暂且不处理")
  69. return "success"
  70. except Exception as exc:
  71. logger.exception(exc)
  72. return exc