idlechampaccount.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import requests
  2. import urllib
  3. import os
  4. from pprint import pprint
  5. class ICAccount:
  6. API_URL = "https://idlechampions.gamepedia.com/api.php"
  7. PARAMS_0 = {
  8. 'format': 'json',
  9. 'formatversion': '2',
  10. 'maxlag': '5',
  11. }
  12. PARAMS_1 = {
  13. 'action': 'query',
  14. 'meta': 'tokens',
  15. 'type': 'login',
  16. 'format': 'json',
  17. 'formatversion': '2',
  18. 'maxlag': '5',
  19. }
  20. PARAMS_2 = {
  21. 'action': 'query',
  22. 'meta': 'tokens',
  23. 'type': 'csrf',
  24. 'format': 'json',
  25. 'formatversion': '2',
  26. 'maxlag': '5',
  27. }
  28. def __init__(self):
  29. self.un = os.environ['IDLEWIKIUSER']
  30. self.pw = os.environ['IDLEWIKIPASS']
  31. self.result = None
  32. self.S = requests.Session()
  33. self.S.headers = {'User-Agent': 'IC_Parse_Uploader'}
  34. def get(self, param={}):
  35. _param = param
  36. _param.update(ICAccount.PARAMS_0)
  37. R = self.S.get(ICAccount.API_URL, params=_param)
  38. return R
  39. def post(self, data={}, param={}, head={}, files={}):
  40. _param = param
  41. _param.update(ICAccount.PARAMS_0)
  42. _param = urllib.parse.urlencode(_param)
  43. _data = data
  44. _files = files
  45. _R = self.S.get(url=ICAccount.API_URL, params=ICAccount.PARAMS_2)
  46. DATA = _R.json()
  47. LOGIN_TOKEN = DATA['query']['tokens']['csrftoken']
  48. _data.update({'token': LOGIN_TOKEN})
  49. # _head = head
  50. # _head.update({'Content-Type': 'application/x-www-form-urlencoded'})
  51. if files == {}:
  52. R = self.S.post(ICAccount.API_URL, params=_param, data=_data)
  53. else:
  54. R = self.S.post(ICAccount.API_URL, params=_param, data=_data, files=_files)
  55. return R
  56. def login(self):
  57. # Retrieve login token first
  58. R = self.S.get(url=ICAccount.API_URL, params=ICAccount.PARAMS_1)
  59. DATA = R.json()
  60. LOGIN_TOKEN = DATA['query']['tokens']['logintoken']
  61. # print(LOGIN_TOKEN)
  62. # Send a post request to login. Using the main account for login is not
  63. # supported. Obtain credentials via Special:BotPasswords
  64. # (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
  65. PARAMS = {
  66. 'action': 'login',
  67. 'lgname': self.un,
  68. 'lgpassword': self.pw,
  69. 'lgtoken': LOGIN_TOKEN,
  70. 'format': 'json',
  71. 'formatversion': '2',
  72. 'maxlag': '5',
  73. }
  74. R = self.S.post(ICAccount.API_URL, data=PARAMS)
  75. DATA = R.json()
  76. if R.status_code == 200:
  77. print('Logged in!')
  78. # print(DATA)
  79. if __name__ == '__main__':
  80. instance = ICAccount()
  81. instance.login()