xiaoiceapi.py 4.5 KB

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