xiaoiceapi.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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 JSONDecodeError:
  52. return self.dicts("error", "请查看tmp下页面的内容")
  53. except Exception as e:
  54. return self.dicts("error", e)
  55. def dicts(self, status, text):
  56. '''
  57. 包装return
  58. '''
  59. return {"status":status, "text":text}
  60. def loop(self, input_strs):
  61. '''
  62. 刷新直到获取到回答
  63. '''
  64. times = 1
  65. while times:
  66. times += 1
  67. response = requests.get("http://weibo.com/aj/message/getbyid?ajwvr=6&uid=5175429989&count=1&_t=0" , headers=self.headers)
  68. self.savePage(response.text, "./tmp/response.txt")
  69. soup = BeautifulSoup(response.json()['data']['html'], "lxml")
  70. text = soup.find("p", class_='page').text
  71. if text != input_strs or times > 20:
  72. break
  73. time.sleep(0.5)
  74. return text
  75. def savePage(self, text, file):
  76. with open(file, "w") as f:
  77. f.write(text)
  78. def api(self):
  79. app = Flask(__name__)
  80. @app.route("/")
  81. def index():
  82. que = request.args.get("que")
  83. ans = self.chat(que)
  84. return jsonify(ans)
  85. app.run()
  86. xb = xiaoiceApi()
  87. xb.api()