coze_bot_api.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. -----------------File Info-----------------------
  5. Name: web.py
  6. Description: web api support
  7. Author: GentleCP
  8. Email: me@gentlecp.com
  9. Create Date: 2021/6/19
  10. -----------------End-----------------------------
  11. """
  12. from fastapi import FastAPI, Response, Request, BackgroundTasks
  13. from WXBizMsgCrypt3 import WXBizMsgCrypt
  14. from xml.etree.ElementTree import fromstring
  15. import uvicorn
  16. import requests
  17. import json
  18. # 加载配置文件
  19. with open('config.json', 'r') as f:
  20. config = json.load(f)
  21. # 从配置文件中提取参数
  22. token = config['token']
  23. aeskey = config['aeskey']
  24. corpid = config['corpid']
  25. corpsecret = config['corpsecret']
  26. coze_access_token = config['coze_access_token']
  27. bot_id = config['bot_id']
  28. port = config['port']
  29. # token = "EcSp"#企业微信应用api信息
  30. # aeskey = "OTZoY8N67kOnGosEpS3jw4Rsjea0Gu6D7X4IWxoYKtY"#企业微信应用api信息
  31. # corpid = "ww5541cfeea51e3188"#企业id
  32. # corpsecret = "SbyG25s1LsMsW0nAMiaNprrQIHYrWKQP4f2mNLLDnwE"##api成功后的secret
  33. # coze_access_token = "pat_HNBYQOWE5h4r1tzXi8S2PuY4ddoVRH3DpTbE3NsYBjtcWHTYw5ffrVmKPh26hSLW"#豆包access_token
  34. # bot_id="7397619068440182793"#豆包机器人id
  35. # port = 18090#服务器端口
  36. wxcpt = WXBizMsgCrypt(token, aeskey, corpid)
  37. app = FastAPI()
  38. def call_llm(prompt: str, bot_id: str,coze_access_token:str):
  39. req_head = {
  40. "Authorization":f"Bearer {coze_access_token}",
  41. "Content-Type": "application/json",
  42. }
  43. req_data = {
  44. "conversation_id": "123",
  45. "bot_id": bot_id,
  46. "user": "test",
  47. "query": prompt,
  48. "stream": False
  49. }
  50. res = requests.post("https://api.coze.cn/open_api/v2/chat", headers=req_head, json=req_data)
  51. res.raise_for_status() # 检查响应状态码是否为200
  52. return res.json()
  53. def qiwei_get():
  54. res = requests.get(f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}")
  55. qw_access_token = res.json()["access_token"]
  56. return qw_access_token
  57. def qiwei_post(username: str, answer: str,agentid:str):
  58. req_data = {
  59. "touser": username,
  60. "toparty": "",
  61. "totag": "",
  62. "msgtype": "text",
  63. "agentid": agentid,
  64. "text": {"content": answer},
  65. "safe": 0,
  66. "enable_id_trans": 0,
  67. "enable_duplicate_check": 0,
  68. "duplicate_check_interval": 1800
  69. }
  70. res = requests.post(f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={qiwei_get()}", json=req_data)
  71. print(res.json())
  72. #return res.json()
  73. def consumer(user_query,decrypt_data):
  74. print(f"请求:{user_query}")
  75. username = decrypt_data.get('FromUserName', '')
  76. agentid = decrypt_data.get('AgentID', '')
  77. # 返回coze结果
  78. coze_response = call_llm(prompt=user_query,bot_id=bot_id,coze_access_token = coze_access_token)
  79. answer = coze_response['messages'][1]['content']
  80. print(f"结果:{answer}")
  81. # 主动发结果给qiwei
  82. qiwei_post(username, answer, agentid)
  83. @app.get("/bot")
  84. async def verify(msg_signature: str, timestamp: str, nonce: str, echostr: str):
  85. ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
  86. if ret == 0:
  87. return Response(content=sEchoStr.decode('utf-8'))
  88. else:
  89. print(sEchoStr)
  90. @app.post("/bot")
  91. async def recv(msg_signature: str, timestamp: str, nonce: str, request: Request, background_tasks: BackgroundTasks):
  92. #start_time = time.time()
  93. body = await request.body()
  94. ret, sMsg = wxcpt.DecryptMsg(body.decode('utf-8'), msg_signature, timestamp, nonce)
  95. decrypt_data = {}
  96. for node in list(fromstring(sMsg.decode('utf-8'))):
  97. decrypt_data[node.tag] = node.text
  98. user_query = decrypt_data.get('Content', '')
  99. background_tasks.add_task(consumer, user_query, decrypt_data)
  100. return Response(content="")
  101. if __name__ == "__main__":
  102. uvicorn.run("coze_bot_api:app", port=port, host='0.0.0.0', reload=False,ssl_keyfile="./key.pem", ssl_certfile="./cert.pem")