xiaoiceapi.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import requests
  2. import json
  3. import time
  4. import sys
  5. from bs4 import BeautifulSoup
  6. from flask import Flask,request,jsonify
  7. class xiaoiceApi():
  8. def __init__(self):
  9. self.headers = {}
  10. self.loadheaders()
  11. def loadheaders(self):
  12. '''
  13. 导入headers
  14. '''
  15. with open("./headers.txt") as headers:
  16. line = headers.readline().strip()
  17. while line:
  18. key = line.split(":")[0]
  19. self.headers[key] = line[len(key)+1:]
  20. line = headers.readline().strip()
  21. def chat(self, input_strs):
  22. '''
  23. 聊天
  24. args (str):
  25. input_strs 问题
  26. return (dict):
  27. status 状态
  28. text 内容
  29. '''
  30. if not self.headers:
  31. return self.dicts("error", "请打开浏览器 复制并将headers放入headers.txt中")
  32. data = {
  33. 'location':'msgdialog',
  34. 'module':'msgissue',
  35. 'style_id':1,
  36. 'text':input_strs,
  37. 'uid':5175429989,
  38. 'tovfids':'',
  39. 'fids':'',
  40. 'el':'[object HTMLDivElement]',
  41. '_t':0,
  42. }
  43. try:
  44. url = 'http://weibo.com/aj/message/add?ajwvr=6'
  45. page = requests.post(url, data=data, headers=self.headers)
  46. self.savePage(page.text, "./tmp/postpage.txt")
  47. if page.json()['code'] == '100000':
  48. text = self.loop(input_strs)
  49. return self.dicts("succeed", text)
  50. else:
  51. return self.dicts("failed", page.json()['msg'])
  52. except Exception as e:
  53. return self.dicts("error", e)
  54. def dicts(self, status, text):
  55. '''
  56. 包装return
  57. '''
  58. return {"status":status, "text":text}
  59. def loop(self, input_strs):
  60. '''
  61. 刷新直到获取到回答
  62. '''
  63. times = 1
  64. while times:
  65. times += 1
  66. response = requests.get("http://weibo.com/aj/message/getbyid?ajwvr=6&uid=5175429989&count=1&_t=0" , headers=self.headers)
  67. self.savePage(response.text, "./tmp/response.txt")
  68. soup = BeautifulSoup(response.json()['data']['html'], "lxml")
  69. text = soup.find("p", class_='page').text
  70. if text != input_strs or times > 20:
  71. break
  72. time.sleep(0.3)
  73. return text
  74. def savePage(self, text, file):
  75. with open(file, "w") as f:
  76. f.write(text)
  77. def api(self):
  78. app = Flask(__name__)
  79. @app.route("/")
  80. def index():
  81. que = request.args.get("que")
  82. ans = self.chat(que)
  83. return jsonify(ans)
  84. app.run()
  85. if __name__ == '__main__':
  86. xb = xiaoiceApi()
  87. xb.api()