def __init__(self, conf): # valve server maybe inactive self.__host = conf self.__server = ServerQuerier((conf['host'], conf['port'])) self.game = self.__server.info().values super().__init__(conf)
def remote_info(self): q = ServerQuerier(self.full_address) data = {} try: data['info'] = q.get_info() data['players'] = q.get_players() except: pass return data
def get_server_stats(address): server = ServerQuerier(address, timeout=SERVER_TIMEOUT) try: info = server.info() logging.info( u'{player_count},{max_players},{server_name}'.format(**info)) return True except (NotImplementedError, NoResponseError, BrokenMessageError): pass
def get_server_stats(address: List[str]): server = ServerQuerier(address, timeout=SERVER_TIMEOUT) try: info = server.info() # rules = server.rules() logging.info(u'Updated {0}:{1} █ {player_count}/{max_players} players █ {server_name} █ {map} █ {server_type}'.format( address[0], address[1], **info) ) # logging.info(u'Rules {rules} \n'.format(**rules)) return True except (NotImplementedError, NoResponseError, BrokenMessageError): pass
def _query(self): try: server = ServerQuerier((self.address, self.port)) info = server.get_info() self.name = info['server_name'] self.map = info['map'] self.game = info['game'] self.version = info['version'] self.players = info['player_count'] self.maxplayers = info['max_players'] self.last_checked = datetime.now() self.status = True except (gaierror, NoResponseError): pass
class ServerLib(object): def __init__(self, address): self.address = address self.server = ServerQuerier(address) self.server.ping() def getInfo(self): _ = self.server.info() return _.values def getPlayers(self): rv = [] _ = self.server.players() for player in _['players']: rv.append(player.values) return rv
def source_query(ip, port, retry=1): while True: try: return dict(ServerQuerier((ip, port),).info()) except Exception as exc: retry -= 1 if retry <= 0: raise
def server(self) -> Optional[ServerQuerier]: if self.is_query_enabled(): if self._servers.get(self.server_name) is None: self._servers[self.server_name] = ServerQuerier(( self.config.steam_query_ip, int(self.config.steam_query_port), ), ) return self._servers[self.server_name] return None
class SourceServer(BaseSSH): """ Obtain information from Source Server and systemd """ def __init__(self, conf): # valve server maybe inactive self.__host = conf self.__server = ServerQuerier((conf['host'], conf['port'])) self.game = self.__server.info().values super().__init__(conf) def __del__(self): if self.__server: self.__server.close() super().__del__() def parse_info(self): """ process gathered and form it to dict. :return: json """ game = L4D2.get(self.game['app_id']) name = self.game['server_name'] h = self.__host address = f"{h['host']}:{h['port']}" map_name = L4D2.get(self.game['map'].lower(), self.game['map']) player = f"{self.game['player_count']}/{self.game['max_players']}" cpu, memory, _, status_bool, status_msg = self.systemd_info() response = dict(app_id=self.__host['app_id'], game=game, name=name, address=address, map=map_name, player=player, cpu=cpu, memory=memory, status=[status_bool, status_msg, time.time()]) return response
def get_server_info(address, csv_writer): server = ServerQuerier(address) try: info = server.info() del info['response_type'] del info['vac_enabled'] del info['version'] del info['protocol'] csv_writer.writerow(info) logging.info(u'Updated {0}:{1} {2}'.format(address[0], address[1], info['server_name'])) return True except ValueError as e: logging.exception(e) return None except (NotImplementedError, NoResponseError, BrokenMessageError): pass
def query_server(ip, port): """Queries a server with the given IP and port""" try: with ServerQuerier((ip, int(port)), timeout=60) as server: log.info(f"Queried server {ip}:{port}!") return server.info() except NoResponseError: log.error(f"No response received from {ip}!") return None except gaierror: log.error(f"Couldn't get server info from {ip}!") return None
async def serverstatsupdate(): await bot.wait_until_ready() while not bot.is_closed(): try: with ServerQuerier(config.SERVER_ADDRESS) as server: channel = bot.get_channel(chanID) await channel.edit(name=f"{emoji.emojize(':eggplant:')} In-Game: {server.info()['player_count']}" +" / 10") except NoResponseError: print(Fore.RED + await timenow(), 'No reply from A2S, retrying (30s)...' + Style.RESET_ALL) channel = bot.get_channel(chanID) await channel.edit(name=f"{emoji.emojize(':cross_mark:')} Server Offline") await asyncio.sleep(30)
async def writecsv(): while True: try: with ServerQuerier(config.SERVER_ADDRESS) as server: with open('csv/playerstats.csv', 'a', newline='') as f: csvup = csv.writer(f, delimiter=',') curtime, players = await timenow(), server.info( )['player_count'] csvup.writerow([curtime, players]) print(curtime, players) except NoResponseError: with open('csv/playerstats.csv', 'a', newline='') as f: csvup = csv.writer(f, delimiter=',') curtime, players = await timenow(), '0' csvup.writerow([curtime, players]) print(curtime, 'Cannot connect to server') await asyncio.sleep(60)
def runner(self): # Setup valve server querier addr = (self.config['address'], self.config['port']) server_info = None with ServerQuerier(addr, self.config['timeout']) as server: while getattr(self, 'shutdown', True): try: server_info = server.info() except (NoResponseError, gaierror): self.connection_lost_event() sleep(self.config['timeout']) continue if server_info['app_id'] != int(self.config['app_id']): raise WatcherException( f'Wrong app id on server: {server_info["app_id"]}') self._updatePlayers(server.players()['players']) self.connection_reaquired_event()
async def serverinfo(self, ctx): # Valve Module error a2a.py ping function -> monotoic and t_send !!!!!!!!!!!!!!!!!! global servers #servers = await load_json('./json/servers.json') for server in servers: channel_id = servers[server]["discord_channel_id"] if ctx.channel.id == channel_id: addr = server.split(":") addr = (addr[0], int(addr[1])) with ServerQuerier(addr) as server_queri: server_info = server_queri.info() ping = server_queri.ping() embed = discord.Embed(title=server_info["server_name"], description=server) embed.add_field(name='Game', value=server_info["game"], inline=False) embed.add_field(name='Map', value=server_info["map"], inline=False) embed.add_field(name='Players Online', value=server_info["player_count"] - server_info["bot_count"], inline=False) embed.add_field(name='Latency', value=f"{round(ping)} ms.", inline=False) embed.add_field(name='Bot Count', value=server_info["bot_count"], inline=False) embed.add_field( name='Vac Enabled', value=True if server_info["vac_enabled"] == 1 else False, inline=False) embed.add_field(name='Version', value=server_info["version"], inline=False) await ctx.send(embed=embed) break
def __init__(self, address): self.address = address self.server = ServerQuerier(address) self.server.ping()
def players(server: ServerQuerier) -> Tuple[PlayerInfo]: """Player infos. """ return (PlayerInfo(**i) for i in server.players()['players'])
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from flask import * from mcstatus import MinecraftServer from valve.source.a2s import ServerQuerier mc_server = MinecraftServer.lookup("pegelcraft.de") gmod_server = ServerQuerier(["gmod.pegelf.de", 27015]) app = Flask(__name__) @app.route("/mc", methods=["GET"]) def get_mc_server(): query = mc_server.query() blub = {} blub["motd"] = query.motd blub["map"] = query.map blub["players"] = query.players.names blub["max_players"] = query.players.max # blub["plugins"] = query.software.plugins blub["version"] = query.software.version blub["brand"] = query.software.brand return Response(json.dumps(blub, indent=4, separators=(',', ': ')), mimetype='application/json') @app.route("/gmod", methods=["GET"]) def get_gmod_server(): blub = {} for x in gmod_server.get_info():
# -*- coding: utf-8 -*- import pprint from valve.source.a2s import ServerQuerier server = ServerQuerier(('dyn.momoka.net', 27016)) _ = server.ping() print(_) _ = server.info() pprint.pprint(_.values) _ = server.players() for player in _['players']: pprint.pprint(player.values)
def server_querier(): """Server querier for app.""" return ServerQuerier( (APP.config['SERVER_ADDRESS'], APP.config['QUERY_SERVER_PORT']), timeout=APP.config['QUERY_SERVER_TIMEOUT'])