baidu_unit_bot.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. # encoding:utf-8
  2. import requests
  3. from bot.bot import Bot
  4. from bridge.reply import Reply, ReplyType
  5. # Baidu Unit对话接口 (可用, 但能力较弱)
  6. class BaiduUnitBot(Bot):
  7. def reply(self, query, context=None):
  8. token = self.get_token()
  9. url = "https://aip.baidubce.com/rpc/2.0/unit/service/v3/chat?access_token=" + token
  10. post_data = (
  11. '{"version":"3.0","service_id":"S73177","session_id":"","log_id":"7758521","skill_ids":["1221886"],"request":{"terminal_id":"88888","query":"'
  12. + query
  13. + '", "hyper_params": {"chat_custom_bot_profile": 1}}}'
  14. )
  15. print(post_data)
  16. headers = {"content-type": "application/x-www-form-urlencoded"}
  17. response = requests.post(url, data=post_data.encode(), headers=headers)
  18. if response:
  19. reply = Reply(
  20. ReplyType.TEXT,
  21. response.json()["result"]["context"]["SYS_PRESUMED_HIST"][1],
  22. )
  23. return reply
  24. def get_token(self):
  25. access_key = "YOUR_ACCESS_KEY"
  26. secret_key = "YOUR_SECRET_KEY"
  27. host = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + access_key + "&client_secret=" + secret_key
  28. response = requests.get(host)
  29. if response:
  30. print(response.json())
  31. return response.json()["access_token"]