Guest User

python terminal client for GMR (Giant Multiplayer Robot)

a guest
Apr 5th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.05 KB | None | 0 0
  1. import requests, json, datetime, urllib2, os
  2.  
  3. authKey = "YourKeyHere"
  4. #-----> PATH TO YOUR CIV SAVES <-----
  5. savepath = "/home/maxe/.local/share/Aspyr/Sid Meier's Civilization 5/Saves/hotseat/"
  6.  
  7. playerID = ""
  8. mygames = []
  9.  
  10. def start():  
  11.     print "...checking authKey and getting playerID..."
  12.     r = requests.get('http://multiplayerrobot.com/api/' +
  13.                      'Diplomacy/AuthenticateUser?authKey=' + authKey)
  14.     global playerID
  15.     playerID = r.text
  16.     #TODO validate playerID --> should be 64bit integer
  17.     update(False);      
  18.  
  19. def update(raw):
  20.     global mygames
  21.     print "...updating game overview..."
  22.     print '------------start of list----------'
  23.     r = requests.get('http://multiplayerrobot.com/api/Diplomacy/' +
  24.                      'GetGamesAndPlayers?playerIDText=' + playerID +
  25.                      '&authKey=' + authKey)
  26.    
  27.     if raw == True:
  28.         print r.text
  29.         return
  30.  
  31.     mygames = []
  32.     answer = json.loads(r.text)
  33.     #list my current turns
  34.     counter = 1
  35.     for game in answer["Games"]:
  36.         if int(game["CurrentTurn"]["UserId"]) == int(playerID):
  37.             turn = str(game["CurrentTurn"]["Number"])
  38.            
  39.             #calculate remaining turntimer
  40.             expires = game["CurrentTurn"]["Expires"]
  41.             if expires != None:
  42.                 expires = datetime.datetime.strptime(expires,"%Y-%m-%dT%H:%M:%S.%f")
  43.                 expires = expires - datetime.datetime.utcnow()
  44.             print str(counter) + ") " + game["Name"] + " _time remaining: " + str(expires)
  45.             mygames.append({"GameId" : game["GameId"],"Name" : game["Name"],
  46.                             "Remaining" : expires, "Counter" : counter,
  47.                             "Turn" : turn, "TurnID" : game["CurrentTurn"]["TurnId"]})
  48.             counter += 1
  49.     print '------------end of list----------'
  50.     #TODO sort by remaining time
  51.     menu()
  52.  
  53. def upload():
  54.     #find uploadable save files
  55.     print "-------------------------------------"
  56.     print "Saves must be named: [GameID]-[Turn]-u.Civ5Save"
  57.     print "You basically just need to add '-u' when you save in Civ after you played your turn..."
  58.     print "... finding uploadable saves now ..."
  59.     print "----------Start of list--------------"
  60.     counter = 1
  61.     choices = []
  62.     for root, dirs, files in os.walk(savepath, topdown=True):
  63.         for name in files:
  64.             if name[-11:] == "-u.Civ5Save":
  65.                 try:
  66.                     gameID, turn, rest = name.split("-")
  67.                     canBeUploaded = False
  68.                     selectedgame = None
  69.                     for game in mygames:
  70.                         if int(game["GameId"]) == int(gameID):
  71.                             canBeUploaded = True
  72.                             selectedgame = game
  73.                     if canBeUploaded:
  74.                         print "["+str(counter)+"] "+selectedgame["Name"]+" --> TURN "+turn
  75.                         choices.append({"TurnID" : selectedgame["TurnID"], "counter" : counter, "fileName" : name})
  76.                         counter += 1
  77.                     else:
  78.                         print '--> not in your current list of games' + name
  79.                 except:
  80.                     print '--> not named after upload convention: ' + name
  81.                     pass
  82.             else:
  83.                 print '--> not named after upload convention: ' + name
  84.                 pass
  85.         break
  86.     print '-----------------End of list----------------------'
  87.     print 'Which file do you want to upload? [c] to cancel...'
  88.  
  89.     response = raw_input()
  90.     if response == "c":
  91.         menu()
  92.     else:
  93.         try:
  94.             file = savepath + choices[int(response)-1]["fileName"]
  95.             url = "http://multiplayerrobot.com/api/Diplomacy/SubmitTurn?authKey="+authKey+"&turnId="+ \
  96.                   str(choices[int(response)-1]["TurnID"])
  97.             #TODO needs a progress bar! https://github.com/niltonvolpato/python-progressbar
  98.             print "sending file now.... this might take a while..."
  99.             r = requests.post(url, files={'upload.Civ5Save': open(file, 'rb')})
  100.             print r.text
  101.         except:
  102.             print "Sorry, something went wrong... Upload didnt work."
  103.             menu()
  104.         menu()
  105.        
  106. def download():
  107.     print '---------download list ------------'
  108.     counter = 1
  109.     for game in mygames:
  110.         print "[" + str(counter) + "] " + game["Name"]
  111.         counter += 1
  112.     print '---------end of list ------------'
  113.     print 'please choose your game - [c]ancel'
  114.  
  115.     response = raw_input()
  116.     if response == "c":
  117.         menu()
  118.  
  119.     game = mygames[int(response)-1]
  120.     url = "http://multiplayerrobot.com/api/Diplomacy/" + \
  121.                      "GetLatestSaveFileBytes?authKey=" + authKey + \
  122.                      "&gameId=" + str(game["GameId"])
  123.     file_name = savepath + str(game["GameId"]) + "-" + \
  124.                 str(game["Turn"]) + ".Civ5Save"
  125.     download_file(url, file_name)
  126.     menu()
  127.  
  128. def download_file(url, file_name):
  129.     u = urllib2.urlopen(url)
  130.     f = open(file_name, 'wb')
  131.     meta = u.info()
  132.     file_size = int(meta.getheaders("Content-Length")[0])
  133.     print "Downloading: %s Bytes: %s" % (file_name, file_size)
  134.  
  135.     file_size_dl = 0
  136.     block_sz = 8192
  137.     while True:
  138.         buffer = u.read(block_sz)
  139.         if not buffer:
  140.             break
  141.  
  142.         file_size_dl += len(buffer)
  143.         f.write(buffer)
  144.         status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
  145.         status = status + chr(8)*(len(status)+1)
  146.         print status,
  147.  
  148.     f.close()
  149.  
  150. def menu():
  151.     print "----------- What do you want do to next? ------------"
  152.     print "[r]efresh - [u]pload - [d]ownload - [j]son-dump - e[x]it"
  153.     response = raw_input()
  154.     if response == "r":
  155.         update(False)
  156.     elif response == "u":
  157.         upload()
  158.     elif response == "d":
  159.         download()
  160.     elif response == "j":
  161.         update(True)
  162.     elif response == "x":
  163.         return
  164.     else:
  165.         print "What? Try again!"
  166.         menu()
  167.        
  168. start()
Advertisement
Add Comment
Please, Sign In to add comment