xiaoiceapi.py 2.8 KB

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