xiaoiceapi.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. #firefox里的原始头冒号后面会多出一个空格,需除去
  20. self.headers[key] = line[len(key)+1:].strip()
  21. line = headers.readline().strip()
  22. def chat(self, input_strs):
  23. '''
  24. 聊天
  25. args (str):
  26. input_strs 问题
  27. return (dict):
  28. status 状态
  29. text 内容
  30. '''
  31. if not self.headers:
  32. return self.dicts("error", "请打开浏览器 复制并将headers放入headers.txt中")
  33. data = {
  34. 'location':'msgdialog',
  35. 'module':'msgissue',
  36. 'style_id':1,
  37. 'text':input_strs,
  38. 'uid':5175429989,
  39. 'tovfids':'',
  40. 'fids':'',
  41. 'el':'[object HTMLDivElement]',
  42. '_t':0,
  43. }
  44. try:
  45. #原http的api已改为https的api
  46. url = 'https://weibo.com/aj/message/add?ajwvr=6'
  47. page = requests.post(url, data=data, headers=self.headers)
  48. self.savePage(page.text, "./tmp/postpage.txt")
  49. if page.json()['code'] == '100000':
  50. text = self.loop(input_strs)
  51. return self.dicts("succeed", text)
  52. else:
  53. return self.dicts("failed", page.json()['msg'])
  54. except Exception as e:
  55. return self.dicts("error", e)
  56. def dicts(self, status, text):
  57. '''
  58. 包装return
  59. '''
  60. return {"status":status, "text":text}
  61. def loop(self, input_strs):
  62. '''
  63. 刷新直到获取到回答
  64. '''
  65. times = 1
  66. while times:
  67. times += 1
  68. #同上,原http的api已改为https的api,另外headers用全反而无法获取页面,只需用到cookies
  69. response = requests.get("https://weibo.com/aj/message/getbyid?ajwvr=6&uid=5175429989&count=1&_t=0" , headers={"Cookie":self.headers["Cookie"]})
  70. self.savePage(response.text, "./tmp/response.txt")
  71. soup = BeautifulSoup(response.json()['data']['html'], "lxml")
  72. text = soup.find("p", class_='page').text
  73. if text != input_strs or times > 20:
  74. break
  75. time.sleep(0.3)
  76. return text
  77. def savePage(self, text, file):
  78. with open(file, "w") as f:
  79. f.write(text)
  80. def api(self):
  81. app = Flask(__name__)
  82. @app.route("/")
  83. def index():
  84. que = request.args.get("que")
  85. ans = self.chat(que)
  86. return jsonify(ans)
  87. app.run()
  88. if __name__ == '__main__':
  89. xb = xiaoiceApi()
  90. xb.api()