選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

77 行
2.9KB

  1. import time
  2. import web
  3. from channel.wechatmp.wechatmp_message import parse_xml
  4. from channel.wechatmp.passive_reply_message import TextMsg
  5. from bridge.context import *
  6. from bridge.reply import ReplyType
  7. from channel.wechatmp.common import *
  8. from channel.wechatmp.wechatmp_channel import WechatMPChannel
  9. from common.log import logger
  10. from config import conf
  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. webData = web.data()
  20. # logger.debug("[wechatmp] Receive request:\n" + webData.decode("utf-8"))
  21. wechatmp_msg = parse_xml(webData)
  22. if (
  23. wechatmp_msg.msg_type == "text"
  24. or wechatmp_msg.msg_type == "voice"
  25. # or wechatmp_msg.msg_type == "image"
  26. ):
  27. from_user = wechatmp_msg.from_user_id
  28. message = wechatmp_msg.content
  29. message_id = wechatmp_msg.msg_id
  30. logger.info(
  31. "[wechatmp] {}:{} Receive post query {} {}: {}".format(
  32. web.ctx.env.get("REMOTE_ADDR"),
  33. web.ctx.env.get("REMOTE_PORT"),
  34. from_user,
  35. message_id,
  36. message,
  37. )
  38. )
  39. rtype = ReplyType.VOICE if wechatmp_msg.msg_type == "voice" else None
  40. context = channel._compose_context(
  41. ContextType.TEXT, message, isgroup=False, desire_rtype=rtype, msg=wechatmp_msg
  42. )
  43. if context:
  44. # set private openai_api_key
  45. # if from_user is not changed in itchat, this can be placed at chat_channel
  46. user_data = conf().get_user_data(from_user)
  47. context["openai_api_key"] = user_data.get(
  48. "openai_api_key"
  49. ) # None or user openai_api_key
  50. channel.produce(context)
  51. # The reply will be sent by channel.send() in another thread
  52. return "success"
  53. elif wechatmp_msg.msg_type == "event":
  54. logger.info(
  55. "[wechatmp] Event {} from {}".format(
  56. wechatmp_msg.Event, wechatmp_msg.from_user_id
  57. )
  58. )
  59. content = subscribe_msg()
  60. replyMsg = TextMsg(
  61. wechatmp_msg.from_user_id, wechatmp_msg.to_user_id, content
  62. )
  63. return replyMsg.send()
  64. else:
  65. logger.info("暂且不处理")
  66. return "success"
  67. except Exception as exc:
  68. logger.exception(exc)
  69. return exc