def ui_elapsedTime(etime): if isinstance(etime, int): return elapsedTime(Now(), etime) elif isinstance(etime, str): return elapsedTime(Now(), int(etime)) elif isinstance(etime, date): ftime = datetime.combine(etime, time.min) gtime = datetimeto(ftime, fmt="epoch") return elapsedTime(Now(), int(gtime))
async def currentlottery(): now = Now('dt') lottery = await webapp.db.fetchone( f"""SELECT * FROM lotteryinfo WHERE completed = False and winner = 'Incomplete' and startdate <= '{now}' ORDER BY id DESC""" ) if not lottery: nextlotterystart = await webapp.db.fetchone( f"""SELECT startdate from lotteryinfo WHERE completed = False and winner = 'Incomplete' and startdate > '{now}' ORDER BY id DESC""" ) if nextlotterystart: return { "active": False, "playercount": 0, "payout": 0, "ends": elapsedTime(nextlotterystart["startdate"], Now(), nowifmin=False), } else: return { "active": False, "playercount": 0, "payout": 0, "ends": "1 Hour", } else: lotterynames = await webapp.db.fetchall( f"SELECT playername FROM lotteryplayers ORDER BY TIMESTAMP ASC" ) resp = [] for player in iter(lotterynames): resp.append(player["playername"].title()) return { "active": True, "playercount": lottery["players"], "payout": lottery["payout"], "ends": elapsedTime(lottery["startdate"] + timedelta(hours=lottery["days"]), Now(), nowifmin=False), "players": ", ".join(resp), }
def format(self, value): linfo = dbquery( "SELECT date FROM %s WHERE value != 0 ORDER BY date DESC LIMIT 1" % (value, ), db="statsdb", ) return elapsedTime(time.time(), int(linfo[0]))
def whenlastplayersvr(inst): linfo = dbquery( "SELECT date FROM %s WHERE value != 0 ORDER BY date DESC LIMIT 1" % (inst, ), db="statsdb", fetch="one", ) return elapsedTime(time.time(), int(linfo[0]))
async def eventinfo(): event = await asyncgetcurrenteventinfo() if not event: event = await asyncgetnexteventinfo() return { 'active': False, 'title': event['title'], 'description': event['description'], 'timeleft': elapsedTime(d2dt_maint(event['starttime']), Now()) } else: return { 'active': True, 'title': event['title'], 'description': event['description'], 'timeleft': elapsedTime(d2dt_maint(event['endtime']), Now()) }
def test_elapsedTime(): with pytest.raises(TypeError): timehelper.elapsedTime([1, 3]) timehelper.elapsedTime((1, 3)) assert timehelper.elapsedTime(1541300681, 1541300689) == "now" assert timehelper.elapsedTime(1541300681, 1541300689, nowifmin=False) == "8 seconds" assert (timehelper.elapsedTime("1541300689", "1541300681", nowifmin=False) == "8 seconds") assert (timehelper.elapsedTime(1541300681.012124, 1541300689.523465, nowifmin=False) == "8 seconds") assert timehelper.elapsedTime(1541288689, 1541300681) == "3 hours, 19 minutes"
def ui_getplayerlasttime(steamid): return elapsedTime( Now(), int( dbquery( "SELECT lastseen FROM players WHERE steamid = '%s'" % (steamid,), fmt="string", fetch="one", ) ), )
async def asyncgetlastseen(seenname): player = await db.fetchone( f"SELECT * FROM players WHERE playername = '{seenname}' ORDER BY lastseen DESC" ) if not player: return "No player found with that name" else: plasttime = elapsedTime(Now(), float(player["lastseen"])) if plasttime != "now": return f'{player["playername"].title()} was last seen {plasttime} ago on {player["server"].title()}' else: return f'{player["playername"].title()} is online now on {player["server"].title()}'
async def instancestats(): instancedata = await webapp.db.fetchall( f"SELECT name, lastdinowipe, lastrestart, lastvote, restartreason, arkversion, rank, score, votes, connectingplayers, activeplayers, isup, arkbuild, hostname FROM instances ORDER BY name DESC" ) returnlist = [] for idata in instancedata: returnlist.append({ 'name': idata['name'], 'lastdinowipe': elapsedTime(Now(), int(idata['lastdinowipe'])), 'lastrestart': elapsedTime(Now(), int(idata['lastrestart'])), 'lastvote': elapsedTime(Now(), int(idata['lastvote'])), 'restartreason': idata['restartreason'], 'arkversion': idata['arkversion'], 'rank': idata['rank'], 'score': idata['score'], 'votes': idata['votes'], 'connectingplayers': idata['connectingplayers'], 'activeplayers': idata['activeplayers'], 'isup': idata['isup'], 'arkbuild': idata['arkbuild'], 'hostname': idata['hostname'] }) return returnlist
def whenlastplayerall(): instances = dbquery("SELECT name from instances") a = 0 for each in instances: lastone = dbquery( "SELECT date FROM %s WHERE value != 0 ORDER BY date DESC" % (each[0], ), db="statsdb", fetch="one", ) if a == 0: lastdate = lastone[0] else: if lastone[0] > lastdate: lastdate = lastone[0] a += 1 if lastdate < time.time() - 300: return elapsedTime(time.time(), int(lastdate)) else: return "Now"
async def asyncstartlottery(lottoinfo): lend = elapsedTime( datetimeto(lottoinfo["startdate"] + timedelta(hours=lottoinfo["days"]), fmt="epoch"), Now(), ) if lottoinfo["announced"] is False: log.log( "LOTTO", f'New lottery has started. Buyin: {lottoinfo["buyin"]} Starting: {lottoinfo["payout"]} Length: {lottoinfo["days"]}', ) bcast = f"""<RichColor Color="0.0.0.0.0.0"> </>\n<RichColor Color="0,1,0,1"> A new points lottery has started! {lottoinfo['buyin']} points to enter in this lottery </>\n\n<RichColor Color="1,1,0,1"> Starting pot {lottoinfo['payout']} points and grows as players enter </>\n Lottery Ends in {lend}\n\n Type !lotto for more info or !lotto enter to join""" await asyncwriteglobal("ALERT", "LOTTERY", bcast) await asyncwritediscord(f'{lottoinfo["payout"]}', Now(), name=f"{lend}", server="LOTTOSTART") await db.update( f"UPDATE lotteryinfo SET announced = True WHERE id = {lottoinfo['id']}" ) asyncio.create_task(asynclotteryloop(lottoinfo))
async def asyncprocesscmdline(minst, eline): dline = eline.decode().replace('"', "").strip() lines = dline.split("\n") for line in lines: inst = minst if ( len(line) < 3 or line.startswith("Running command") or line.startswith("Command processed") or isserver(line) or line.find("Force respawning Wild Dinos!") != -1 ): pass elif line.find("[TCsAR]") != -1: dfg = line.split("||") dfh = dfg[1].split("|") tcdata = {} for each in dfh: ee = each.strip().split(": ") if len(ee) > 1: tcdata.update({ee[0]: ee[1]}) if "SteamID" in tcdata: await processtcdata(minst, tcdata) elif line.find("left this ARK!") != -1: await playerleave(line, minst) elif line.find("joined this ARK!") != -1: await playerjoin(line, minst) elif ( line.find("AdminCmd:") != -1 or line.find("Admin Removed Soul Recovery Entry:") != -1 ): await addgamelog(inst, "ADMIN", line) elif line.find(" demolished a '") != -1 or line.find("Your Tribe killed") != -1: await addgamelog(inst, "DEMO", line) elif line.find("released:") != -1: await addgamelog(inst, "RELEASE", line) elif line.find("trapped:") != -1: await addgamelog(inst, "TRAP", line) elif line.find(" was killed!") != -1 or line.find(" was killed by ") != -1: await addgamelog(inst, "DEATH", line) elif line.find("Tamed a") != -1: await addgamelog(inst, "TAME", line) elif line.find(" claimed '") != -1 or line.find(" unclaimed '") != -1: await addgamelog(inst, "CLAIM", line) elif ( line.find(" was added to the Tribe by ") != -1 or line.find(" was promoted to ") != -1 or line.find(" was demoted from ") != -1 or line.find(" uploaded a") != -1 or line.find(" downloaded a dino:") != -1 or line.find(" requested an Alliance ") != -1 or line.find(" Tribe to ") != -1 or line.find(" was removed from the Tribe!") != -1 or line.find(" set to Rank Group ") != -1 or line.find(" requested an Alliance with ") != -1 or line.find(" was added to the Tribe!") != -1 ): await addgamelog(inst, "TRIBE", line) elif line.find("starved to death!") != -1: await addgamelog(inst, "DECAY", line) elif ( line.find("was auto-decay destroyed!") != -1 or line.find("was destroyed!") != -1 ): await addgamelog(inst, "DECAY", line) elif line.startswith("Error:"): await addgamelog(inst, "UNKNOWN", line) else: chatdict = deconstructchatline(line) whoasked = chatdict["name"] log.trace(f"chatline who: {whoasked}") incmd = chatdict["line"] if incmd.startswith("!test"): log.log( "CMD", f"Responding to a [!test] request from [{whoasked.title()}] on [{minst.title()}]", ) message = "hi" bcast = f"""<RichColor Color="0.0.0.0.0.0"> </>\r<RichColor Color="1,0.65,0,1"> A Wild dino wipe vote has finished</>\n\n<RichColor Color="1,1,0,1"> NO votes have won!</>\n <RichColor Color="1,0,0,1"> Wild dinos will NOT be wiped</>\n\n You must wait 10 minutes before you can start another vote""" await asyncserverbcast(minst, bcast) elif incmd.startswith("!help"): message = f"Commands: @all, !who, !lasthour, !lastday, !timeleft, !myinfo, !myhome, !lastwipe," await asyncserverchat(inst, message) message = f"!lastrestart, !vote, !tip, !lottery, !lastseen <playername>, !playtime <playername>" await asyncserverchat(inst, message) log.log( "CMD", f"Responded to a [!help] request from [{whoasked.title()}] on [{minst.title()}]", ) elif incmd.startswith(("/kit", "!kit")): log.log( "CMD", f"Responding to a kit request from [{whoasked.title()}] on [{minst.title()}]", ) message = f"To view kits you must make a level 1 rewards vault and hang it on a wall or foundation. Free starter items and over 80 kits available. !help for more commands" await asyncserverchat(inst, message) elif incmd.startswith("/"): message = f"Commands in this cluster start with a ! (Exclimation Mark) Type !help for a list of commands" await asyncserverchat(inst, message) elif incmd.startswith(("!lastdinowipe", "!lastwipe")): lastwipe = elapsedTime(Now(), await asyncgetlastwipe(minst)) message = f"Last wild dino wipe was {lastwipe} ago" await asyncserverchat(inst, message) log.log( "CMD", f"Responding to a [!lastwipe] request from [{whoasked.title()}] on [{minst.title()}]", ) elif incmd.startswith("!lastrestart"): lastrestart = elapsedTime(Now(), await asyncgetlastrestart(minst)) message = f"Last server restart was {lastrestart} ago" await asyncserverchat(inst, message) log.log( "CMD", f"Responding to a [!lastrestart] request from [{whoasked.title()}] on [{minst.title()}]", ) elif incmd.startswith("!lastseen"): rawseenname = line.split(":") orgname = rawseenname[1].strip() lsnname = rawseenname[2].split("!lastseen") if len(lsnname) > 1: seenname = lsnname[1].strip().lower() message = await asyncgetlastseen(seenname) log.log( "CMD", f"Responding to a [!lastseen] request for [{seenname.title()}] from [{orgname.title()}] on [{minst.title()}]", ) else: message = f"You must specify a player name to search" log.log( "CMD", f"Responding to a invalid [!lastseen] request from [{orgname.title()}] on [{minst.title()}]", ) await asyncserverchat(minst, message) elif incmd.startswith("!playedtime"): rawseenname = line.split(":") orgname = rawseenname[1].strip() lsnname = rawseenname[2].split("!playedtime") seenname = lsnname[1].strip().lower() if lsnname: message = await asyncgettimeplayed(seenname) else: message = await asyncgettimeplayed(whoasked) await asyncserverchat(inst, message) log.log( "CMD", f"Responding to a [!playedtime] request for [{whoasked.title()}] on [{minst.title()}]", ) elif incmd.startswith(("!recent", "!whorecent", "!lasthour")): rawline = line.split(":") lastlline = rawline[2].strip().split(" ") if len(lastlline) == 2: ninst = lastlline[1] else: ninst = minst log.log( "CMD", f"Responding to a [!recent] request for [{whoasked.title()}] on [{minst.title()}]", ) await whoisonlinewrapper(ninst, minst, whoasked, 2) elif incmd.startswith(("!today", "!lastday")): rawline = line.split(":") lastlline = rawline[2].strip().split(" ") if len(lastlline) == 2: ninst = lastlline[1] else: ninst = minst log.log( "CMD", f"Responding to a [!today] request for [{whoasked.title()}] on [{minst.title()}]", ) await whoisonlinewrapper(ninst, minst, whoasked, 3) elif incmd.startswith(("!tip", "!justthetip")): log.log( "CMD", f"Responding to a [!tip] request from [{whoasked.title()}] on [{minst.title()}]", ) tip = await asyncgettip(db) message = tip await asyncserverchat(inst, message) elif incmd.startswith(("!mypoints", "!myinfo")): log.log( "CMD", f"Responding to a [!myinfo] request from [{whoasked.title()}] on [{minst.title()}]", ) await asyncrespmyinfo(minst, whoasked) elif incmd.startswith(("!players", "!whoson", "!who")): rawline = line.split(":") lastlline = rawline[2].strip().split(" ") if len(lastlline) == 2: ninst = lastlline[1] else: ninst = minst log.log( "CMD", f"Responding to a [!who] request for [{whoasked.title()}] on [{minst.title()}]", ) await whoisonlinewrapper(ninst, minst, whoasked, 1) elif incmd.startswith(("!myhome", "!transfer", "!home", "!sethome")): rawline = line.split(":") lastlline = rawline[2].strip().split(" ") if len(lastlline) == 2: ninst = lastlline[1] else: ninst = "" log.log( "CMD", f"Responding to a [!myhome] request for [{whoasked.title()}] on [{minst.title()}]", ) message = "The Home command is disabled for repairs" await asyncserverchat(inst, message) # await asynchomeserver(minst, whoasked, ninst) elif incmd.startswith(("!vote", "!startvote", "!wipe")): log.debug( f"Responding to a [!vote] request from [{whoasked.title()}] on [{minst.title()}]" ) await asyncstartvoter(minst, whoasked) elif incmd.startswith(("!agree", "!yes")): log.debug(f"responding to YES vote on {minst} from {whoasked}") await asynccastedvote(minst, whoasked, True) elif incmd.startswith(("!disagree", "!no")): log.log( "VOTE", f"Responding to NO vote on [{minst.title()}] from [{whoasked.title()}]", ) await asynccastedvote(minst, whoasked, False) elif incmd.startswith(("!timeleft", "!restart")): log.log( "CMD", f"Responding to a [!timeleft] request from [{whoasked.title()}] on [{minst.title()}]", ) await asyncresptimeleft(minst, whoasked) elif incmd.startswith(("!linkme", "!link")): log.log( "CMD", f"Responding to a [!linkme] request from [{whoasked.title()}] on [{minst.title()}]", ) await asynclinker(minst, whoasked) elif incmd.startswith(("!lottojoin", "!lottoenter")): await asynclottery(whoasked, True, minst) elif incmd.startswith(("!lottery", "!lotto")): rawline = line.split(":") if len(rawline) > 2: lastlline = rawline[2].strip().split(" ") if len(lastlline) == 2: lchoice = lastlline[1] else: lchoice = False await asynclottery(whoasked, lchoice, minst) elif incmd.startswith(("!lastlotto", "!winner")): log.log( "CMD", f"Responding to a [!lastlotto] request from [{whoasked.title()}] on [{minst.title()}]", ) await asynclastlotto(minst, whoasked) elif incmd.startswith("!"): steamid = await asyncgetsteamid(whoasked) log.warning( f"Invalid command request [{incmd}] from [{whoasked.title()}] on [{minst.title()}]" ) message = "Invalid command. Try !help" await asyncserverchatto(inst, steamid, message) elif incmd.startswith(globvars.atinstances): newchatline = chatdict["line"].split(" ", 1)[1] tstamp = chatdict["time"].strftime("%m-%d %I:%M%p") await asyncwriteglobal(minst, chatdict["name"], newchatline) await asyncwritechat( "generalchat", chatdict["name"], newchatline, tstamp ) else: await asyncchatlinedetected(inst, chatdict)
async def asyncplayergreet(steamid, steamname, inst): xferpoints = 0 log.trace(f"processing greeting for [{steamname}]") if await asynccheckifbanned(steamid): log.warning( f"BANNED player [{steamname}] [{steamid}] has tried to connect or is online on [{inst.title()}]. kicking and banning." ) await asyncserverchatto(inst, steamid, "You are not welcome here. Goodbye") await asyncio.sleep(3) await asyncserverrconcmd(inst, f"kickplayer {steamid}") # subprocess.run("""arkmanager rconcmd 'banplayer %s' @%s""" % (steamid, inst), shell=True) else: player = await db.fetchone(f"SELECT * FROM players WHERE steamid = '{steamid}'") if not player: asyncio.create_task(asyncnewplayer(steamid, steamname, inst)) else: if player["homeserver"] == inst: xfertable = await db.fetchall( f"""SELECT * FROM transferpoints WHERE steamid = '{player["steamid"]}'""" ) xferpoints = 0 for each in xfertable: xferpoints = xferpoints + int(each["points"]) xferpoints = xferpoints + int(player["transferpoints"]) await db.update( f"""UPDATE players SET transferpoints = 0 WHERE steamid = '{player["steamid"]}'""" ) if xferpoints != 0: await db.update( f"""DELETE FROM transferpoints WHERE steamid = '{player["steamid"]}'""" ) log.log( "POINTS", f"Transferred {xferpoints} non-home server points for [{player[1].title()}] on [{inst.title()}]", ) await asyncserverscriptcmd( inst, f"tcsar addarctotal {steamid} {xferpoints}" ) if player["homemovepoints"] != 0 and player["homeserver"] == inst: homemovepoints = int(player["homemovepoints"]) log.log( "POINTS", f"Transferred {homemovepoints} points for [{player[1].title()}] on [{inst.title()}] from a home server move", ) await db.update( f"UPDATE players SET homemovepoints = 0 WHERE steamid = '{steamid}'" ) await asyncserverscriptcmd( inst, f"tcsar addarctotal {steamid} {homemovepoints}" ) if not player["welcomeannounce"]: # existing online player log.trace( f"Existing online player [{player[1].title()}] was found on [{inst.title()}]. updating info." ) await db.update( f"UPDATE players SET online = True, lastseen = '{Now()}', server = '{inst}' WHERE steamid = '{steamid}'" ) await asynclottodeposits(player, inst) else: # new player connection log.debug( f"New connected player [{player[1].title()}] was found on [{inst.title()}]. updating info." ) await db.update( f"UPDATE players SET online = True, welcomeannounce = False, lastseen = '{Now()}', server = '{inst}', connects = {int(player[7]) + 1}, lastconnect = '{Now(fmt='dt')}', refreshauctions = True, refreshsteam = True WHERE steamid = '{steamid}'" ) laston = elapsedTime(Now(), int(player["lastseen"])) totplay = playedTime(int(player[4])) newpoints = int(player[5]) + xferpoints mtxt = f"Welcome back {player[1].title()}, you have {newpoints} reward points on {player[15].capitalize()}, last online {laston} ago, total time played {totplay}" await asyncserverchatto(inst, steamid, mtxt) await asyncio.sleep(1) serverplayers = await db.fetchall( f"SELECT * FROM players WHERE server = '{inst}' AND steamid != '{steamid}' AND online = True" ) playerlist = "" for splayer in serverplayers: if playerlist == "": playerlist = f'{splayer["playername"].title()}' else: playerlist = playerlist + f', {splayer["playername"].title()}' if len(serverplayers) != 0: msg = f"There are {len(serverplayers)} other players online: {playerlist}" else: msg = f"There are no other players are online on this server." await asyncserverchatto(inst, steamid, msg) await asyncio.sleep(2) if int(player[14]) == 1 and int(player[13]) == 1 and player[3] == inst: mtxt = f"WARNING: Server has restarted since you logged in, reset your primordials if they are not stored in a soul terminal" await asyncserverchatto(inst, steamid, mtxt) await asyncresetplayerbit(steamid) if player[8] == "": await asyncio.sleep(3) mtxt = f"Your player is not linked with a discord account yet. type !linkme in global chat" await asyncserverchatto(inst, steamid, mtxt) if not await asyncisinlottery(steamid): await asyncio.sleep(3) mtxt = f"A lottery you have not entered yet is underway. Type !lotto for more information" await asyncserverchatto(inst, steamid, mtxt) currentevent = await asynciseventtime() if currentevent: await asyncio.sleep(3) mtxt = f"{currentevent[4]} event is currently active!" await asyncserverchatto(inst, steamid, mtxt) annc = await db.fetchone("SELECT announce FROM general") if annc and annc[0] is not None: await asyncio.sleep(2) mtxt = annc[0] await asyncserverchatto(inst, steamid, mtxt) await asyncserverisinrestart(steamid, inst, player) if xferpoints != 0: await asyncio.sleep(5) mtxt = f"{xferpoints} rewards points were transferred to you from other cluster servers" await asyncserverchatto(inst, steamid, mtxt) if int(player["homemovepoints"]) != 0: await asyncio.sleep(5) mtxt = f"{xferpoints} rewards points were transferred here from a home server move" await asyncserverchatto(inst, steamid, mtxt) await asynclottodeposits(player, inst) globvars.greetings.remove(steamid)
def format(self, value): return elapsedTime(float(time.time()), float(value))