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

active_reply.py 3.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. reply_text = subscribe_msg()
  30. replyPost = create_reply(reply_text, msg)
  31. return replyPost.render()
  32. wechatmp_msg = WeChatMPMessage(msg, client=channel.client)
  33. if wechatmp_msg.ctype in [ContextType.TEXT, ContextType.IMAGE, ContextType.VOICE]:
  34. from_user = wechatmp_msg.from_user_id
  35. content = wechatmp_msg.content
  36. message_id = wechatmp_msg.msg_id
  37. logger.info(
  38. "[wechatmp] {}:{} Receive post query {} {}: {}".format(
  39. web.ctx.env.get("REMOTE_ADDR"),
  40. web.ctx.env.get("REMOTE_PORT"),
  41. from_user,
  42. message_id,
  43. content,
  44. )
  45. )
  46. if msg.type == "voice" and wechatmp_msg.ctype == ContextType.TEXT and conf().get("voice_reply_voice", False):
  47. context = channel._compose_context(
  48. wechatmp_msg.ctype, content, isgroup=False, desire_rtype=ReplyType.VOICE, 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