xiaobing.py 2.6 KB

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