xiaoiceapi.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. import re
  8. from PIL import Image
  9. class xiaoiceApi():
  10. def __init__(self):
  11. self.headers = {}
  12. self.loadheaders()
  13. def loadheaders(self):
  14. '''
  15. 导入headers
  16. '''
  17. with open("./headers.txt") as headers:
  18. line = headers.readline().strip()
  19. while line:
  20. key = line.split(":")[0]
  21. #firefox里的原始头冒号后面会多出一个空格,需除去
  22. self.headers[key] = line[len(key)+1:].strip()
  23. line = headers.readline().strip()
  24. def chat(self, input_strs):
  25. '''
  26. 聊天
  27. args (str):
  28. input_strs 问题
  29. return (dict):
  30. status 状态
  31. text 内容
  32. '''
  33. if not self.headers:
  34. return self.dicts("error", "请打开浏览器 复制并将headers放入headers.txt中")
  35. data = {
  36. 'location':'msgdialog',
  37. 'module':'msgissue',
  38. 'style_id':1,
  39. 'text':input_strs,
  40. 'uid':5175429989,
  41. 'tovfids':'',
  42. 'fids':'',
  43. 'el':'[object HTMLDivElement]',
  44. '_t':0,
  45. }
  46. try:
  47. #原http的api已改为https的api
  48. url = 'https://weibo.com/aj/message/add?ajwvr=6'
  49. page = requests.post(url, data=data, headers=self.headers)
  50. self.savePage(page.text, "./tmp/postpage.txt")
  51. if page.json()['code'] == '100000':
  52. text = self.loop(input_strs)
  53. return self.dicts("succeed", text)
  54. else:
  55. return self.dicts("failed", page.json()['msg'])
  56. except Exception as e:
  57. return self.dicts("error", e)
  58. def dicts(self, status, text):
  59. '''
  60. 包装return
  61. '''
  62. return {"status":status, "text":text}
  63. def loop(self, input_strs):
  64. '''
  65. 刷新直到获取到回答
  66. '''
  67. times = 1
  68. while times <= 20:
  69. times += 1
  70. #同上,原http的api已改为https的api,另外headers用全反而无法获取页面,只需用到cookies
  71. response = requests.get("https://weibo.com/aj/message/getbyid?ajwvr=6&uid=5175429989&count=1&_t=0" , headers={"Cookie":self.headers["Cookie"]})
  72. self.savePage(response.text, "./tmp/response.txt")
  73. soup = BeautifulSoup(response.json()['data']['html'], "lxml")
  74. text = soup.find("p", class_='page')
  75. if text:
  76. text = text.text
  77. if text == input_strs:
  78. continue
  79. elif "收起" in soup.get_text():
  80. imgUrl = soup.find(href=re.compile('msget')).get('href')
  81. text = "图片地址: " + imgUrl
  82. picRespone = requests.get(imgUrl, headers={"Cookie":self.headers["Cookie"]})
  83. if picRespone.status_code == 200:
  84. with open('pic.jpg', 'wb') as f:
  85. f.write(picRespone.content)
  86. img = Image.open('pic.jpg')
  87. img.show()
  88. elif "mp3" in soup.get_text():
  89. mp3Url = soup.find(href=re.compile('msget')).get('href')
  90. text = "语音地址: " + imgUrl
  91. picRespone = requests.get(imgUrl, headers={"Cookie":self.headers["Cookie"]})
  92. if picRespone.status_code == 200:
  93. with open('voice.mp3', 'wb') as f:
  94. f.write(picRespone.content)
  95. else:
  96. print("第{}次重试".format(times))
  97. continue
  98. time.sleep(0.3)
  99. return text
  100. text = "错误: 已达到最大重试次数"
  101. print (text)
  102. return text
  103. def savePage(self, text, file):
  104. with open(file, "w") as f:
  105. f.write(text)
  106. def api(self):
  107. app = Flask(__name__)
  108. @app.route("/")
  109. def index():
  110. que = request.args.get("que")
  111. ans = self.chat(que)
  112. return jsonify(ans)
  113. app.run()
  114. if __name__ == '__main__':
  115. xb = xiaoiceApi()
  116. xb.api()