Skip to content

Instantly share code, notes, and snippets.

@zyuiop
Created September 19, 2015 22:56
Show Gist options
  • Save zyuiop/d73a017d5ab008c62ff9 to your computer and use it in GitHub Desktop.
Save zyuiop/d73a017d5ab008c62ff9 to your computer and use it in GitHub Desktop.
import time
import mcstatus
import json
from os import path
import shutil
import sys
import datetime
PATH = path.dirname(path.abspath(__file__))
PINGS_PATH = PATH + "/pings.txt"
PING_LIST = {"SamaGames" : "mc.samagames.net", "EpiCube" : "play.epicube.fr", "UHCGames" : "mc.uhcgames.com", "FantaBobWorld" : "play.fantabobworld.com"}
def getPlayers(ip):
mc = mcstatus.MinecraftServer.lookup(ip)
status = mc.status()
return status.players.online
class Logger:
def __init__(self):
self.file = open(PATH + "/logs.txt", "a")
def log(self, level, text, end = "\n"):
self.writeRaw("[" + time.strftime("%X") + " " + level + "] " + text, end=end)
def writeRaw(self, text, end = "\n"):
self.file.write(text + end)
print(text, end=end)
def info(self, text, end = "\n"):
self.log("INFO", text, end)
def error(self, text, end = "\n"):
self.log("ERROR", text, end)
def warning(self, text, end = "\n"):
self.log("WARNING", text, end)
def close(self):
self.file.close()
logger = Logger()
logger.info("Initializing server pings...")
pingData = {}
if path.isfile(PINGS_PATH):
logger.info("Found existing pings, loading them.")
try:
with open(PINGS_PATH, "r") as f:
pingData = json.load(f)
except Exception as e:
logger.error("Can not read file ! Backing it up." + str(e))
try:
shutil.copy(PINGS_PATH, "./" + time.strftime("%X") + ".backup")
logger.info("Backup successfully done.")
except Exception as err:
logger.error("Backup failed, aborting.")
sys.exit(0)
thisPingData = {}
for serverName, serverIp in PING_LIST.items():
logger.info("Pinging " + serverName + " (" + serverIp + ")... ", end="")
players = "ERROR"
try:
players = str(getPlayers(serverIp))
logger.writeRaw("Received " + players + " players.")
except Exception as e:
logger.writeRaw("Error.")
logger.warning("Ping failed : " + str(e))
thisPingData[serverName] = players
logger.info("Done, saving data.")
now = str(datetime.datetime.now())
time = str(time.time())
pingData[time] = {"date" : now, "data" : thisPingData}
with open(PINGS_PATH, "w") as f:
json.dump(pingData, f)
logger.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment