|
- #!/usr/bin/python3
- # NationStates Login Script
- import requests
- import time
- import xml.etree.cElementTree as ET
- import json
-
- # Config
- with open('config.json', 'r') as f:
- config = json.load(f)
- my_nation = config['main-nation']
- my_password = config['password']
- # End Config
-
-
- def main():
- """Logs into into all nations in the login.txt file, with the format nation;password, one per line."""
- user_agent = my_nation
- main_password = my_password
- ejected_nations = get_ejected_nations()
- canonicalized_ejected = [fix(e_nation) for e_nation in ejected_nations]
- # open the file with nation and passwords
- with open('login.txt', 'r') as f:
- for line in f:
- # Check if the line is a comment
- if line[0] != "#":
- # Assuming the password is the usual password
- if line.find(';') == -1:
- nation = line.strip()
- password = main_password
- # Otherwise, a unique password is specified
- else:
- # get nation and password
- nation, password = line.strip().split(';')
- # make request
- login(nation, password, user_agent)
- if fix(nation) in canonicalized_ejected:
- write_out(nation, 0)
- else:
- continue
-
-
- def fix(s):
- """Formats a string the NS way, lowercase underscore."""
- return s.lower().replace(' ', '_')
-
-
- def get_ejected_nations():
- """"Return all ejected nations."""
- time.sleep(0.7)
- r = requests.get("https://www.nationstates.net/cgi-bin/api.cgi?region=the_rejected_realms&q=nations",
- headers={"User-Agent": f"<Nation: {my_nation}> Login Script"})
- root = ET.fromstring(r.text)
- return root[0].text.split(':')
-
-
- def write_out(nation, status):
- """Write login failures and ejected nations to out."""
- # Ejected Nations
- if status == 0:
- with open("output/ejected.txt", "a") as f:
- f.write('{}\n'.format(nation))
- # Failed to login
- elif status == 1:
- with open("output/failed_login.txt", "a") as f:
- f.write('{}\n'.format(nation))
-
-
- def login(nation, password, agent):
- """Given the nation and password, query to the NS API with a ping request."""
- # take a break first
- rate = 0.7
- time.sleep(rate)
- # set the user agent to abide by rules, and password to ping properly
- r_headers = {'User-Agent': 'login2.py in use by <Nation: {}>'.format(agent),
- 'X-Password': password}
- r = requests.get('https://www.nationstates.net/cgi-bin/api.cgi?nation={}&q=ping'.format(fix(nation)),
- headers=r_headers)
- try:
- r.raise_for_status()
- print("Logged into {}.".format(nation))
- except requests.exceptions.HTTPError:
- print("Error logging into {}.".format(nation))
- write_out(nation, 1)
-
-
- if __name__ == '__main__':
- main()
|