Beispiel #1
0
	def mainloop(self,messagecb,eventcb):
		try:
			while self.running:
				try:
					data, address = self.s.recvfrom(8192)
				except socket.timeout:
					if self.running:
						continue
					else:
						break
				self.addr = address
				event = ord(data[0])
				#print "Received event %i from %s" % (event,str(address))
				if event == 10:
					n = ord(data[1])
					name = data[2:]
					self.players.update([(n,name)])
				if event == 13:
					n = ord(data[1])
					text = data[3:]
					if not text.lower().startswith("a:"):
						messagecb(self.players[n],text)
				if event == 3: #gameover
					self.sayingame("/kill")
				eventcb(ord(data[0]),data[1:])
		except Exception, e:
			Log.exception( e )
Beispiel #2
0
 def mainloop(self, messagecb, eventcb):
     try:
         while self.running:
             try:
                 data, address = self.s.recvfrom(8192)
             except socket.timeout:
                 if self.running:
                     continue
                 else:
                     break
             self.addr = address
             event = ord(data[0])
             #print "Received event %i from %s" % (event,str(address))
             if event == 10:
                 n = ord(data[1])
                 name = data[2:]
                 self.players.update([(n, name)])
             if event == 13:
                 n = ord(data[1])
                 text = data[3:]
                 if not text.lower().startswith("a:"):
                     messagecb(self.players[n], text)
             if event == 3:  #gameover
                 self.sayingame("/kill")
             eventcb(ord(data[0]), data[1:])
     except Exception, e:
         Log.exception(e)
Beispiel #3
0
 def __init__(self, port, messagecb, eventcb):
     self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.addr = ("localhost", int(port))
     self.s.bind(self.addr)
     self.players = dict()
     thread.start_new_thread(self.mainloop, (messagecb, eventcb))
     Log.info("UDP Listening on port " + str(port))
Beispiel #4
0
		def disqus_matches():
			try:
				return dict([ (int(x['identifiers'][0][6:]),x['posts']) for x in self._disqus.forums.listThreads(forum=self.forum) if x['identifiers'][0][:5] == 'match' ])
			except APIError,a: 
				if str(a.code) != '5':
					raise a
				else:
					Log.error('Invalid disqus api-keys')
Beispiel #5
0
	def add_vote(self,user,score):
		try:
			def signum(x):
				return (x > 0) - (x < 0)
			score = int(score)
			self.votes[user] = signum(score) 
		except Exception:
			Log.debug('Vote by %s failed'%user)
			raise VoteFailed(self.question,user, score)
Beispiel #6
0
 def GetPrintableRepresentation(self, rank_list, db):
     if len(rank_list) < 1:
         return "no ranks to represent"
     else:
         el = rank_list[0]
         for algo in self.algos.values():
             if isinstance(el, algo.GetDbEntityType()):
                 return algo.GetPrintableRepresentation(rank_list, db)
         Log.error("no suitable algo for printing rank list found ", "Ranking")
         return ""
Beispiel #7
0
	def Update(self,ladder_id,match,db):
		#print 'match id %d'%match.id
		scores, result_dict = calculateWinnerOrder(match,db)
		session = db.session()

		teams = defaultdict(tuple)
		player_id_map = defaultdict(list)
		def constant_factory(value):
			import itertools
			return itertools.repeat(value).next
		minteam_score = defaultdict(constant_factory(100000))
		for name,result in result_dict.iteritems():
			score = scores[name] * -1
			player_id = session.query( Player ).filter( Player.nick == name ).first().id
			rank = session.query( TrueskillRanks ).filter( TrueskillRanks.ladder_id == ladder_id ).filter( TrueskillRanks.player_id == player_id ).first()
			if not rank:
				rank = TrueskillRanks()
				rank.ladder_id = ladder_id
				rank.player_id = player_id
			session.add(rank)

			rank.rank = score
			l = list(teams[result.team])
			l.append(rank.rating)
			teams[result.team] = tuple(l)
			player_id_map[result.team].append(player_id)
			minteam_score[result.team] = min(minteam_score[result.team],score)
		session.commit()

		ordered_teams = []
		ordered_minteam_score = []
		team_ids = teams.keys()
		team_ids.sort()
		for i in range(len(teams)):
			ordered_teams.append(teams[team_ids[i]])
			ordered_minteam_score.append(minteam_score[team_ids[i]])
		i = 0
		if len(ordered_teams) < 2:
			Log.error('less than 2 teams, cannot update ranking')
			raise Exception('not enough teams')
		for team_ratings in trueskill.transform_ratings(ordered_teams,ordered_minteam_score):
			j = 0
			current_team = team_ids[i]
			q = session.query( TrueskillRanks ).filter( TrueskillRanks.ladder_id == ladder_id )
			for rating in team_ratings:
				pids = player_id_map[current_team]
				pid = pids[j]
				rank = q.filter( TrueskillRanks.player_id == pid ).one()
				rank.rating = rating
				session.add( rank )
				j += 1
			i += 1
		session.commit()
		session.close()
Beispiel #8
0
	def __init__(self,port,messagecb,eventcb):
		self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		self.s.settimeout(5.0)
		self.addr = ("localhost",int(port))
		self.s.bind(self.addr)
		self.players = dict()
		self.running = True
		self.port = port
		thread.start_new_thread(self.mainloop,(messagecb,eventcb))
		Log.info("UDP Listening on port "+str(port))
Beispiel #9
0
    def LoadCFG(self):
        self.Debug("Load CFG")
        try:
            self.Server.Config = localconfig.Server
        except:
            Log.Error('using default server config')
            self.Server.Config = {
                'LobbyServer': {
                    'Host': 'springrts.com',
                    'Port': 8200
                },
                'MainAccount': '[pyah]Master',
                'UnitsyncPath': '/usr/lib/libunitsync.so',
                'SpringExec': '/usr/bin/spring-dedicated'
            }
        try:
            self.Server.Groups = localconfig.Groups
        except:
            Log.Error('using default server config')
            self.Server.Groups = {
                'pyah': {
                    'Mod': 'Evolution RTS - v1.5',
                    'Map': 'Comet Catcher Redux',
                    'ChannelsReport': [['autohostdev']],
                    'Accounts': [('[pyah]Host_01', 'PASSWORD', 0)]
                },
            }
        self.IP = localconfig.IP

        self.Server.AccessCommands = {
            'code': ['owner', 'admin'],
            'udp': ['owner'],
            'start': ['owner', 'admin', '%BattlePlayer%'],
            'kick': ['owner', 'admin', 'operator'],
            'ring': ['admin', 'operator', '%BattlePlayer%', '%GamePlayer%'],
        }
        self.Server.AccessRoles = {
            'owner': {
                '[CN]Zydox': 1,
                '_koshi_': 1,
                'BrainDamage': 1,
            },
            'admin': {
                '[CN]Zydox': 1,
                '_koshi_': 1,
                'BrainDamage': 1,
            },
            'operator': {},
        }
Beispiel #10
0
	def oncommandfromserver(self,command,args,socket):
		if command == "JOINED" :
			chan = args[0]
			nick = args[1]
			if chan in self.modchannels:
				self.db.SetPrimaryGame( nick, self.modname )
				try:
					user = self.db.GetUser( nick )
					#Log.info('%s -- %d -- %d'%(nick, user.welcome_sent,user.rank ))
					if not user.welcome_sent and user.rank < 1:
						#socket.send('say %s hello first time visitor %s\n'%(chan,nick) )
						#user.welcome_sent = True
						self.db.SetUser( user )
				except Exception, e:
					Log.exception(e)

			elif chan in self.channels:
				self.db.SetPrimaryGame( nick, 'multiple' )
Beispiel #11
0
 def __init__(self, output, ladder_id, config, db):
     super(AutomaticMatchToDbWrapper, self).__init__(db)
     self.config = config
     if os.path.exists(output):
         self.replay = output
     else:
         log_start = "[f=0000000] recording demo: "
         datapath = config.get("tasbot", "springdatapath")
         for line in output.split("\n"):
             if line.startswith(log_start):
                 self.replay = os.path.join(datapath, line[len(log_start) :].split("\n")[0])
                 break
         try:
             os.path.exists(self.replay)
         except Exception, e:
             Log.error("match has no replay")
             Log.exception(e)
             raise e
Beispiel #12
0
	def SubmitLadderReplay( self, replaypath, ladderid, do_validation=True ):
		try:
			if not self.db.LadderExists( ladderid ):
				Log.error( "Error: ladder %d does not exist" % ( ladderid ) )
				return False
			else:
				try:
					open(replaypath).close()
					mr = AutomaticMatchToDbWrapper(replaypath, ladderid, self.config, self.db)
					return self.db.ReportMatch( mr, do_validation )
				except UnterminatedReplayException:
					Log.error('skipping unterminated replay %s'%replaypath, 'ReplayReporter')
				except Exception,e:
					Log.error('reporting match failed', 'ReplayReporter')
					Log.exception(e)
				return False
		except Exception, e:
			Log.exception(e)
			return False
Beispiel #13
0
 def run(self):
     self.Start()
     while 1:
         try:
             time.sleep(1)
         except SystemExit:
             self.Shutdown()
             return
         except KeyboardInterrupt:
             #error("SIGINT, Exiting")
             self.Shutdown()
             return
         except Exception, e:
             #error("parsing command line")
             Log.Except(e)
Beispiel #14
0
	def sayingame(self,text):
		#print "Sending %s to spring" % text
		try:
			self.s.sendto(text,self.addr)
		except Exception, e:
			Log.exception( e )
Beispiel #15
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys


import tasbot
from tasbot.customlog import Log

if __name__=="__main__":
	tasbot.check_min_version((1,))
	r = False
	for arg in sys.argv:
		if arg.strip() == "-r":
			r = True
			Log.notice("Registering account")
	slave = False
	try:
		idx = sys.argv.index('-c')
		configfile = sys.argv[idx+1]
		slave = True
	except Exception,e:
		configfile = "Main.conf"
	print('using configfile %s'%configfile)

	config = tasbot.config.Config(configfile)
	Log.init(config.get('tasbot', 'logfile', 'ladderbot.log'),
			 config.get('tasbot', 'loglevel', 'info'), True )
	if slave:
		pidfile = config.get('tasbot','pidfile','ladderbot.pid')
	else:
		pidfile = config.get('tasbot','pidfile','ladderbot.pid2')
Beispiel #16
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

import tasbot
from tasbot.customlog import Log

if __name__ == "__main__":
    tasbot.check_min_version((1, ))
    configfile = "Main.conf"
    config = tasbot.config.Config(configfile)
    Log.init(config.get('tasbot', 'logfile', 'relayhost.log'),
             config.get('tasbot', 'loglevel', 'info'), True)

    r = False
    for arg in sys.argv:
        if arg.strip() == "-r":
            r = True
            Log.Notice("Registering account")
    pidfile = config.get('tasbot', 'pidfile', 'relayhost.pid')
    print 'using pidfile %s' % pidfile
    inst = tasbot.DefaultApp(configfile, pidfile, r, True)
    if int(config.get('tasbot', 'debug', 0)):
        inst.run()  #exec in fg
    else:
        inst.start()
Beispiel #17
0
    def ParseSpringOutput(self):
        with open(self.replay, "rb") as demofile:
            parser = demoparser.DemoParser(demofile)
            open("/tmp/sc.txt", "w").write(parser.getScript())
            script = Script(parser.getScript())
            self.players = script.players
            self.bots = script.bots
            self.teams = script.teams
            self.allies = script.allies
            self.options = dict(script.modoptions.items() + script.other.items() + script.mapoptions.items())
            self.restrictions = script.restrictions
            self.gameid = "no game id found"
            packet = True
            currentFrame = 0
            playerIDToName = {}
            kop = open("/tmp/msg.data", "w")

            def _invalidPlayer(name):
                return name in script.spectators.keys() or name not in self.players

            while packet:
                packet = parser.readPacket()
                try:
                    messageData = demoparser.parsePacket(packet)
                    kop.write(str(messageData))
                    kop.write("\n")

                    def clean(name):
                        return name.replace("\x00", "")

                    if messageData:
                        try:
                            clean_name = clean(messageData["playerName"])
                        except:
                            pass
                        if messageData["cmd"] == "keyframe":
                            currentFrame = messageData["framenum"]
                        elif messageData["cmd"] == "setplayername":
                            if _invalidPlayer(clean_name):
                                continue
                            playerIDToName[messageData["playerNum"]] = clean_name
                            self.players[clean_name].connected = True
                        elif messageData["cmd"] == "startplaying" and messageData["countdown"] == 0:
                            self.game_started = True
                        elif messageData["cmd"] == "gameover":
                            print("GAMEOVER")
                            if not self.game_started:
                                Log.error("game not started on gameover found", "Match.py")
                            else:
                                self.game_over = currentFrame
                        elif messageData["cmd"] == "gameid":
                            self.gameid = messageData["gameID"]
                        elif messageData["cmd"] == "playerleft":
                            playername = clean(messageData["playerName"])
                            if _invalidPlayer(clean_name):
                                continue
                            if messageData["bIntended"] == 0:
                                self.players[playername].timeout = True
                            if messageData["bIntended"] == 1:
                                self.players[playername].quit = True
                            if messageData["bIntended"] == 2:
                                self.players[playername].kicked = True
                        elif messageData["cmd"] == "team":
                            if clean_name in script.spectators.keys():
                                continue
                            if messageData["action"] == "team_died":  # team died event
                                deadTeam = messageData["param"]
                                for name, rank in self.players.iteritems():
                                    if rank.team == deadTeam:
                                        self.players[name].died = currentFrame
                            elif messageData["action"] == "giveaway":
                                # giving everything away == death
                                self.players[clean_name].died = currentFrame
                except Exception, e:
                    Log.exception(e)
                    raise e

            kop.close()
            # if self.game_over < 0 or len(self.teams) < 2:
            # raise UnterminatedReplayException( self.gameid, self.ladder_id )
            print("game over %d" % self.game_over)
Beispiel #18
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

import tasbot
from tasbot.customlog import Log

if __name__=="__main__":
	tasbot.check_min_version((1,))
	configfile = "Main.conf"
	config = tasbot.config.Config(configfile)
	Log.init( config.get('tasbot','logfile','relaymanager.log'), 'info', True )
	
	r = False
	for arg in sys.argv:
		if arg.strip() == "-r":
			r = True
			Log.Notice("Registering account")
	pidfile = config.get('tasbot','pidfile','relaymanager.pid')
	print 'using pidfile %s'%pidfile
	inst = tasbot.DefaultApp(configfile,pidfile,r,True)
	if int(config.get( 'tasbot','debug', 0 )):
		inst.run()#exec in fg
	else:
		inst.start()

Beispiel #19
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

import tasbot
from tasbot.customlog import Log

if __name__=="__main__":
	tasbot.check_min_version((1,))
	configfile = "Main.conf"
	config = tasbot.config.Config(configfile)
	Log.init(config.get('tasbot', 'logfile', 'relayhost.log'),
			 config.get('tasbot', 'loglevel', 'info'), True )

	r = False
	for arg in sys.argv:
		if arg.strip() == "-r":
			r = True
			Log.Notice("Registering account")
	pidfile = config.get('tasbot','pidfile','relayhost.pid')
	print 'using pidfile %s'%pidfile
	inst = tasbot.DefaultApp(configfile,pidfile,r,True)
	if int(config.get( 'tasbot','debug', 0 )):
		inst.run()#exec in fg
	else:
		inst.start()
Beispiel #20
0
 def sayingame(self, text):
     #print "Sending %s to spring" % text
     try:
         self.s.sendto(text, self.addr)
     except Exception, e:
         Log.exception(e)
Beispiel #21
0
def mError( msg ):
	Log.error( msg, '[LadderManager]' )
Beispiel #22
0
	def oncommandfromuser(self,fromwho,fromwhere,ispm,command,args,socket):
		try:
			if fromwho == self.app.config.get('tasbot', "nick"):
				return
			if len(command) > 0 and command[0] == "!":
				if not self.db.AccessCheck( -1, fromwho, Roles.User ):
					self.sayPermissionDenied( socket, command, fromwho, fromwhere, ispm )
					#log
					return
			else:
				return

			# !TODO refactor to use function dict
			if command == "!ladder":
				if not self.enabled and not self.db.AccessCheck( -1, fromwho, Roles.GlobalAdmin ):
					self.notifyuser( socket, fromwho, fromwhere, ispm, "Ladder functionality is temporarily disabled." )
					return
				ladderid = -1
				battleid = -2
				password = ""
				if len(args) > 0:
					if args[0].isdigit():
						ladderid = int(args[0])
						if len(args) > 1:
							password = "******".join(args[1:])
					else:
						password = "******".join(args[0:])
				try:
					battleid = self.tsc.users[fromwho].battleid
				except Exception:
					Log.bad("User " + fromwho + " not found")
				if ( battleid < 0 ):
					self.notifyuser( socket, fromwho, fromwhere, ispm, "You are not in a battle." )
				else:
					if not self.db.AccessCheck( ladderid, fromwho, Roles.User ):
						self.sayPermissionDenied( socket, command, fromwho, fromwhere, ispm )
						#log
						return
					if ( battleid in self.battleswithbots ):
						self.notifyuser( socket, fromwho, fromwhere, ispm, "A ladder bot is already present in your battle." )
					else:
						if ( ladderid == -1 or self.db.LadderExists( ladderid ) ):
							self.spawnbot( socket, battleid, password, fromwho, ladderid )
						else:
							self.notifyuser( socket, fromwho, fromwhere, ispm, "Invalid ladder ID." )
			if command == "!ladderjoinchannel":
				if not self.db.AccessCheck( -1, fromwho, Roles.GlobalAdmin ):
					self.sayPermissionDenied( socket, command, fromwho, fromwhere, ispm )
					#log
					return
				if len(args) < 1:
					self.notifyuser( socket, fromwho, fromwhere, ispm, "Invalid command syntax, check !ladderhelp for usage." )
				else:
					channel = " ".join(args[0:])
					socket.send("JOIN " + channel + "\n")
					if not channel in self.channels:
						self.channels.append(channel)
						self.app.config.set('join_channels',"channels", ','.join(self.channels))
						self.app.SaveConfig()
			if command == "!ladderleavechannel":
				if not self.db.AccessCheck( -1, fromwho, Roles.GlobalAdmin ):
					self.sayPermissionDenied( socket, command, fromwho, fromwhere, ispm )
					#log
					return
				if len(args) != 1:
					self.notifyuser( socket, fromwho, fromwhere, ispm, "Invalid command syntax, check !ladderhelp for usage." )
				else:
					channel = args[0]
					if channel in self.channels:
						socket.send("LEAVE " + channel + "\n")
						self.channels.remove(channel)
						self.app.config.set('join_channels',"channels", ','.join(self.channels))
						self.app.SaveConfig()
			if command == "!ladderlist":
				self.notifyuser( socket, fromwho, fromwhere, ispm, "Available ladders, format name: ID:" )
				for l in self.db.GetLadderList(Ladder.name):
					self.notifyuser( socket, fromwho, fromwhere, ispm, "%s: %d" %(l.name, l.id ) )
			if command == "!ladderadd":
				if not self.db.AccessCheck( -1, fromwho, Roles.GlobalAdmin ):
					self.sayPermissionDenied( socket, command, fromwho, fromwhere, ispm )
					#log
					return
				if len(args) < 1:
					self.notifyuser( socket, fromwho, fromwhere, ispm, "Ladder name can't be empty." )
				else:
					try:
						laddername = " ".join(args[0:])
						ladderid = self.db.AddLadder( laddername )
						self.notifyuser( socket, fromwho, fromwhere, ispm, "New ladder created, ID: " + str(ladderid) )
					except ElementExistsException, e:
						Log.error(e)
			if command == "!ladderremove":
				if not self.db.AccessCheck( -1, fromwho, Roles.GlobalAdmin ):
					self.sayPermissionDenied( socket, command, fromwho, fromwhere, ispm )
					#log
					return
				if len(args) != 1 or not args[0].isdigit():
					self.notifyuser( socket, fromwho, fromwhere, ispm, "Invalid command syntax, check !ladderhelp for usage." )
				else:
					ladderid = int(args[0])
					try:
						self.db.RemoveLadder( args[0] )
						self.notifyuser( socket, fromwho, fromwhere, ispm, "Ladder removed." )
					except ElementNotFoundException, e:
						self.notifyuser( socket, fromwho, fromwhere, ispm, "Invalid ladder ID." )
Beispiel #23
0
from beaker.util import parse_cache_config_options
import os
from bottle import static_file

from tasbot.customlog import Log
from tasbot.config import Config

from disqus import Disqus
import ladderdb 
from myutils import mkdir_p

		
cache_opts = {
    'cache.type': 'memory',
    'cache.data_dir': 'tmp/cache/data',
    'cache.lock_dir': 'tmp/cache/lock'
}

config = Config( 'Main.conf' )
Log.init( 'website.log' )
db = ladderdb.LadderDB(config.get('tasbot','alchemy-uri'))
env = Environment(loader=FileSystemLoader('templates'))
staging = config.get_bool('tasbot','staging')
cache = CacheManager(**parse_cache_config_options(cache_opts))
disqus = Disqus(config,cache)
mkdir_p(config.get('ladder','base_dir'))

def local_file(filename, sub, **kwargs):
	path = os.path.join(config.get('ladder','base_dir'),sub) 
	return static_file(filename, root=path)
Beispiel #24
0
    def Shutdown(self):
        try:
            for name, host in self.Hosts.iteritems():
                host.Shutdown()
            self.Master.Shutdown()
            sys.exit(0)
        except:
            sys.exit(-1)

    def run(self):
        self.Start()
        while 1:
            try:
                time.sleep(1)
            except SystemExit:
                self.Shutdown()
                return
            except KeyboardInterrupt:
                #error("SIGINT, Exiting")
                self.Shutdown()
                return
            except Exception, e:
                #error("parsing command line")
                Log.Except(e)


if __name__ == '__main__':
    Log.Init('server.log', 'info', True)
    S = Server()
    S.run()
Beispiel #25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tasbot, sys
from tasbot.customlog import Log

if __name__ == "__main__":
    configfile = "Main.conf"
    config = tasbot.ParseConfig.Config(configfile)
    Log.Init(config['logfile'], 'info', True)

    r = False
    for arg in sys.argv:
        if arg.strip() == "-r":
            r = True
            Log.Notice("Registering account")
    pidfile = config['pidfile']
    print 'using pidfile %s' % pidfile
    inst = tasbot.DefaultApp(configfile, pidfile, r, True)
    if bool(config.GetSingleOption('debug', False)):
        inst.run()  #exec in fg
    else:
        inst.start()
Beispiel #26
0
	def ParseSpringOutput(self):
		with open(self.replay, 'rb') as demofile:
			parser = demoparser.DemoParser(demofile)
			open('/tmp/sc.txt', 'w').write(parser.getScript())
			script = Script(parser.getScript())
			self.players = script.players
			self.bots = script.bots
			self.teams = script.teams
			self.allies = script.allies
			self.options = dict(script.modoptions.items() 
							+ script.other.items() + script.mapoptions.items())
			self.restrictions = script.restrictions
			self.gameid = 'no game id found'
			packet = True
			currentFrame = 0
			playerIDToName = {}
			kop = open('/tmp/msg.data','w')
			def _invalidPlayer(name):
				return name in script.spectators.keys() or name not in self.players
			while packet:
				packet = parser.readPacket()
				try:
					messageData = demoparser.parsePacket(packet)
					kop.write(str(messageData))
					kop.write('\n')
					def clean(name):
						return name.replace('\x00','')
					if messageData:
						try:
							clean_name = clean(messageData['playerName'])
						except:
							pass
						if messageData['cmd'] == 'keyframe':
							currentFrame = messageData['framenum']
						elif messageData['cmd'] == 'setplayername':
							if _invalidPlayer(clean_name):
								continue 
							playerIDToName[messageData['playerNum']] = clean_name 
							self.players[clean_name].connected = True
						elif messageData['cmd'] == 'startplaying' and messageData['countdown'] == 0:
							self.game_started = True
						elif messageData['cmd'] == 'gameover':
							if not self.game_started:
								Log.error( 'game not started on gameover found', 'Match.py' )
							else:
								self.game_over = currentFrame
						elif messageData['cmd'] == 'gameid':
							self.gameid = messageData['gameID']
						elif messageData['cmd'] == 'playerleft':
							playername = clean(messageData['playerName'])
							if _invalidPlayer(clean_name):
								continue
							if messageData['bIntended'] == 0:
								self.players[playername].timeout = True
							if messageData['bIntended'] == 1:
								self.players[playername].quit = True
							if messageData['bIntended'] == 2:
								self.players[playername].kicked = True
						elif messageData['cmd'] == 'team':
							if clean_name in script.spectators.keys():
								continue
							if messageData['action'] == 'team_died': #team died event
								deadTeam = messageData['param']
								for name,rank in self.players.iteritems():
									if rank.team == deadTeam:
										self.players[name].died = currentFrame
							elif messageData['action'] == 'giveaway': 
								#giving everything away == death 
								self.players[clean_name].died = currentFrame
				except Exception, e:
					Log.exception(e)
					raise e
	
			kop.close()
			if self.game_over < 0:
				raise UnterminatedReplayException( self.gameid, self.ladder_id )
Beispiel #27
0
def notice( msg ):
	Log.info( msg, '[LadderManager]' )
Beispiel #28
0
	def oncommandfromserver(self,command,args,socket):
		try:
			if command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!enable" and args[0] in self.app.admins:
				self.disabled = False
				socket.send("MYSTATUS %i\n" % int(int(self.listfull)+int(self.disabled)*2))
				socket.send("SAYPRIVATE %s %s\n" % (args[0],"Hosting new games enabled"))
				self.app.config.set('autohost', "enabled", "1")
				self.app.SaveConfig()
			elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!disable" and args[0] in self.app.admins:
				self.disabled = True
				socket.send("MYSTATUS %i\n" % int(int(self.listfull)+int(self.disabled)*2))
				socket.send("SAYPRIVATE %s %s\n" % (args[0],"Hosting new games disabled"))
				self.app.config.set('autohost', "enabled", "0")
				self.app.SaveConfig()
			elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!listbans" and args[0] in self.app.admins:
				x = 0
				l0 = []
				for b in self.bans:
					l0.append(b)
					x += 1
					if x >= 5:
						socket.send("SAYPRIVATE %s %s\n" % (args[0],' | '.join(l0)))
						x = 0
						l0 = []
				socket.send("SAYPRIVATE %s %s\n" % (args[0],' | '.join(l0)))
			elif command == "SAIDPRIVATE" and len(args) >= 3 and args[1] == "!ban" and args[0] in self.app.admins:
				toban = args[2:]
				for b in toban:
					if not b in self.bans:
						self.bans.append(b)
						socket.send("SAYPRIVATE %s %s\n" % (args[0],b+" Banned"))
					else:
						socket.send("SAYPRIVATE %s %s\n" % (args[0],b+" is already banned"))
				self.app.config.set('autohost', "bans", ','.join(self.bans))
				self.app.SaveConfig()
				socket.send("SAYPRIVATE %s %s\n" % (args[0],"Done."))
			elif command == "SAIDPRIVATE" and len(args) >= 3 and args[1] == "!unban" and args[0] in self.app.admins:
				toban = args[2:]
				for b in toban:
					if not b in self.bans:
						socket.send("SAYPRIVATE %s %s\n" % (args[0],b+"is not currently banned"))
					else:
						self.bans.remove(b)
						socket.send("SAYPRIVATE %s %s\n" % (args[0],b+" has been unbanned"))
				self.app.config.set('autohost', "bans", ','.join(self.bans))
				self.app.SaveConfig()
				socket.send("SAYPRIVATE %s %s\n" % (args[0],"Done."))
			elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!registerall" and args[0] in self.app.admins:
				for b in self.botstatus:
					if not self.botstatus[b]:
						slot = b
						self.threads.append(thread.start_new_thread(self.botthread,(slot,self.an[slot],socket,args[0],self.ap,self)))
						self.botstatus[slot] = True
						time.sleep(1)
						if b + 1 == len(self.botstatus): # The bot spawned was the last one
							self.listfull = True
							socket.send("MYSTATUS 1\n")
			elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!spawn" and args[0] not in self.ul and not self.disabled:
				if args[0] in self.bans:
					socket.send("SAYPRIVATE %s %s\n" %(args[0],"\001 Error: You are banned!"))
					return
				freeslot = False
				slot = 0
				for b in self.botstatus:
					if not self.botstatus[b]:
						freeslot = True
						slot = b
						break
				if freeslot:
					self.threads.append(thread.start_new_thread(self.botthread,(slot,self.an[slot],socket,args[0],self.ap,self)))
					socket.send("SAYPRIVATE %s %s\n" %(args[0],self.an[slot]))
					self.ul.append(args[0])
					self.botstatus[slot] = True
					if b + 1 == len(self.botstatus): # The bot spawned was the last one
						self.listfull = True
						socket.send("MYSTATUS 1\n")
				else:
					socket.send("SAYPRIVATE %s %s\n" %(args[0],"\001 Error: All bots are spawned"))

			#elif command == "SAIDPRIVATE" and len(args) == 2 and args[1] == "!spawn" and len(self.ul) >= len(self.an):
			#	socket.send("SAYPRIVATE %s %s\n" %(args[0],"\001 Error: All bots are spawned"))
			#elif command == "SAIDPRIVATE" and len(args) >= 1 and :
			#	socket.send("SAYPRIVATE %s %s\n" %(args[0],"\002"))
			elif command == "LEFT" and args[0] == "autohost" and len(args) > 4 and args[3] == "inconsistent" and args[1] in self.bots:
				self.say_ah("Bot(%s) kicked by inconsistent data error , killing" % args[1])
				try:
					if platform.system() == "Windows":
					  handle = win32api.OpenProcess(1, 0, self.bots[args[1]])
					  win32api.TerminateProcess(handle, 0)
					else:
					  os.kill(self.bots[args[1]],signal.SIGKILL)
				except Exception, e:
					Log.exception(e)
		except Exception, e:
			exc = traceback.format_exception(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2])
			self.sayex_ah("*** EXCEPTION: BEGIN")
			for line in exc:
				self.sayex_ah(line)
			self.sayex_ah("*** EXCEPTION: END")
			Log.exception(e)
Beispiel #29
0
def mInfo( msg ):
	Log.info( msg, '[LadderManager]' )
Beispiel #30
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

import tasbot
from tasbot.customlog import Log

if __name__ == "__main__":
    tasbot.check_min_version((1, ))
    configfile = "Main.conf"
    config = tasbot.config.Config(configfile)
    Log.init(config.get('tasbot', 'logfile', 'faqbot.log'), 'info', True)

    r = False
    for arg in sys.argv:
        if arg.strip() == "-r":
            r = True
            Log.Notice("Registering account")
    pidfile = config.get('tasbot', 'pidfile', 'faqbot.pid')
    print 'using pidfile %s' % pidfile
    inst = tasbot.DefaultApp(configfile, pidfile, r, True)
    if config.get_bool('tasbot', 'debug', False):
        inst.run()  #exec in fg
    else:
        inst.start()
Beispiel #31
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

import tasbot
from tasbot.customlog import Log

if __name__=="__main__":
	tasbot.check_min_version((1,))
	configfile = "Main.conf"
	config = tasbot.config.Config(configfile)
	Log.init( config.get('tasbot','logfile','faqbot.log'), 'info', True )
	
	r = False
	for arg in sys.argv:
		if arg.strip() == "-r":
			r = True
			Log.Notice("Registering account")
	pidfile = config.get('tasbot','pidfile','faqbot.pid')
	print 'using pidfile %s'%pidfile
	inst = tasbot.DefaultApp(configfile,pidfile,r,True)
	if config.get_bool( 'tasbot','debug', False ):
		inst.run()#exec in fg
	else:
		inst.start()