示例#1
0
    def kickPlayerNow(self, player, kickType=None):
        """Kick a player."""
        if kickType is None:
            if not hasattr(player, 'mmKickType'):
                kickType = mm_utils.KickBanType.rcon
            else:
                kickType = player.mmKickType

        if kickType != mm_utils.KickBanType.rcon:
            mm.warn("Unsupported kick type '%d' (using %d instead)" %
                    (kickType, mm_utils.KickBanType.rcon))

        if self.__kickTimers.has_key(player.index):
            self.__kickTimers[player.index].destroy()
            del self.__kickTimers[player.index]

        # Log the kick
        if hasattr(player, 'mmKickReason'):
            reason = self.validateKickReason(player.mmKickReason)
        else:
            reason = self.validateKickReason(None)

        self.mm.info("Kicked '%s'[%d] => '%s'" %
                     (player.getName(), player.getProfileId(), reason))

        # Kick the player
        host.rcon_invoke("admin.kickPlayer %d" % (player.index))
示例#2
0
def onChatMessage(player_id, text, channel, flags):

    # pull the potential prefix off the text line
    text = text.replace("HUD_TEXT_CHAT_TEAM", "")
    text = text.replace("HUD_TEXT_CHAT_SQUAD", "")
    text = text.replace("*\xA71DEAD\xA70*", "")

    # unless the first character is ! don't do anything
    if text[0:1] == "!":
        decho("dc_irs: the first character of %s was !" % text, 5)

        # grab the parts of the chatline I need with a REGEX
        pattern = re.compile(r'!(\w*) ?(.*)')
        matches = pattern.findall(text)
        command = matches[0][0]
        decho("dc_irs: command = %s" % command, 5)

        # grab a parameter, if any
        if matches[0][1] != "":
            parameter = matches[0][1]
            decho("dc_irs: parameter = %s" % parameter, 5)
        else:
            parameter = None
            decho("dc_irs: no parameter given", 5)

        if command == "nextmap":
            decho(
                'The next map is %s' %
                host.rcon_invoke('maplist.list').splitlines()[int(
                    host.rcon_invoke('admin.nextLevel').strip())].split()
                [1].strip('"').replace('_', ' ').title(), 1)
        elif command == "time":
            decho('The time is: %s' % time.strftime('%H:%M %p %Z'), 1)
        else:
            decho('ERROR: invalid command', 1)
示例#3
0
def KickerSystem(player):
    global playerKickList, HOW_MANY_KILLS_TO_KICK, RESTRICTED_WEAPON_KICK_MSG, RESTRICTED_WEAPON_KICK_REASON, WARNING_AFTER_FRAG, RESTRICTED_WEAPON_KICK_IN_MINUTES
    playerId = player.getProfileId()
    t = 0
    for temp_player in playerKickList:
        if (int(playerId) == int(temp_player[0])):
            temp_player[1] += 1
            if (temp_player[1] >= HOW_MANY_KILLS_TO_KICK):
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(RESTRICTED_WEAPON_KICK_MSG) % (player.getName()), 0)
                host.rcon_invoke("pb_sv_kick \"" + str(player.getName()) +
                                 "\" " +
                                 str(RESTRICTED_WEAPON_KICK_IN_MINUTES) +
                                 " \"" + str(RESTRICTED_WEAPON_KICK_REASON) +
                                 "\"")
                del playerKickList[playerKickList.index(
                    [playerId, temp_player[1]])]
                t = 1

            else:
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(WARNING_AFTER_FRAG) % (player.getName()), 0)
                t = 1

    if not (t):
        playerKickList.append([playerId, 1])
        host.sgl_sendTextMessage(0, 12, 1,
                                 str(WARNING_AFTER_FRAG) % (player.getName()),
                                 0)
        t = 0
示例#4
0
	def kickPlayerNow( self, player, kickType=None ):
		"""Kick a player."""
		if kickType is None:
			if not hasattr( player, 'mmKickType' ):
				kickType = mm_utils.KickBanType.rcon
			else:
				kickType = player.mmKickType				

		if kickType != mm_utils.KickBanType.rcon:
			mm.warn( "Unsupported kick type '%d' (using %d instead)" % ( kickType, mm_utils.KickBanType.rcon ) )

		if self.__kickTimers.has_key( player.index ):
			self.__kickTimers[player.index].destroy()
			del self.__kickTimers[player.index]

		# Log the kick
		if hasattr( player, 'mmKickReason' ):
			reason = self.validateKickReason( player.mmKickReason )			
		else:
			reason = self.validateKickReason( None )

		self.mm.info( "Kicked '%s'[%d] => '%s'" % ( player.getName(), player.getProfileId(), reason ) )

		# Kick the player
		host.rcon_invoke( "admin.kickPlayer %d" % ( player.index ) )
示例#5
0
    def __removeBan(self, banKey, unBanReason=None, skipSave=False):
        """Unban a player."""
        banKey = self.validateBanAddressOrKey(banKey)

        if banKey is None:
            self.mm.error("Invalid unban request ( Ban key / address blank )")
            return False

        unBanReason = self.validateUnBanReason(unBanReason)
        self.mm.info("Removing ban '%s' (%s)" % (banKey, unBanReason))

        # N.B. We do this blindly to to ensure that its done
        if not self.mm.isBattleFieldHeroes():
            host.rcon_invoke("admin.removeAddressFromBanList %s" % (banKey))
        host.rcon_invoke("admin.removeKeyFromBanList %s" % (banKey))

        # Remove any unban timer
        if self.__unBanTimers.has_key(banKey):
            self.__unBanTimers[banKey].destroy()
            del self.__unBanTimers[banKey]

        if self.__bans.has_key(banKey):
            del self.__bans[banKey]

            if skipSave:
                return True
            # Persist the banlist
            return self.saveBanlist()
        else:
            self.mm.warn("Ban '%s' not found" % banKey)

        return False
示例#6
0
def sendMessageToAll(msg):
    try:
        host.rcon_invoke("game.sayAll \"" + str(msg) + "\"")
    except:
        host.rcon_invoke("game.sayAll \"" +
                         'sendMessageToAll(): failed to display message' +
                         "\"")
示例#7
0
def echoMessage(msg):
    try:
        host.rcon_invoke("echo \"" + str(msg) + "\"")
    except:
        host.rcon_invoke("echo \"" +
                         'sendMessageToAll(): failed to display message' +
                         "\"")
示例#8
0
def example_callback():
    if not hasattr(example_callback, 'buf'):
        return

    data = example_callback.buf[0xf00:]
    event = struct.unpack('<Q', data[:8])[0]
    event_data = getbuf(event, 0x50)

    opt = ord(event_data[0x2a:][:1])
    sender = ord(event_data[0x28:][:1])

    radio = {
        0xe5: 'backup',
        0xdf: 'pickup',
        0xd0: 'roger',
        0xd1: 'negative',
        0xd2: 'thanks',
        0xd3: 'sorry',
        0xe4: 'medic',
        0xe7: 'ammo',
        0xec: 'go',
        0xdb: 'spot',
        0xef: 'follow',
    }

    if opt in radio:
        selection = radio[opt]
    else:
        selection = str(opt)

    host.rcon_invoke('game.sayall %s_%d\n' % (selection, sender))
示例#9
0
def onCommander(teamid, oldCommanderPlayerObject, player):
    global OLDSCHOOL_LEVEL
    if (OLDSCHOOL_LEVEL != 0):
        global ANTICOMMANDER
        if (
                ANTICOMMANDER
        ):  #yeap. Double check. Unfortunately DICE forgot to implement host.UNregisterHandler... And this is the only way to disable anticommander (and other) 'on the fly' by using remote rcon command. Sorry :P
            global COMMANDER_AUTOKICK
            if (COMMANDER_AUTOKICK == 1):
                global COMMANDER_KICK_MSG, COMMANDER_KICK_REASON, COMMANDER_KICK_TIME_IN_MINUTES
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(COMMANDER_KICK_MSG) % (player.getName()), 0)
                host.rcon_invoke("pb_sv_kick \"" + str(player.getName()) +
                                 "\" " + str(COMMANDER_KICK_TIME_IN_MINUTES) +
                                 " \"" + str(COMMANDER_KICK_REASON) + "\"")
            else:
                global COMMANDER_MSG
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(COMMANDER_MSG) % (player.getName()), 0)
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(COMMANDER_MSG) % (player.getName()), 0)
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(COMMANDER_MSG) % (player.getName()), 0)
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(COMMANDER_MSG) % (player.getName()), 0)
                host.sgl_sendTextMessage(
                    0, 12, 1,
                    str(COMMANDER_MSG) % (player.getName()), 0)
示例#10
0
	def __removeBan( self, ban, unBanReason=None, skipSave=False ):
		"""Unban a player."""
		ban = self.validateBanAddressOrKey( ban )

		if ban is None:
			self.mm.error( "Invalid unban request ( Ban key / address blank )")
			return False

		unBanReason = self.validateUnBanReason( unBanReason )
		self.mm.info( "Removing ban '%s' (%s)" % ( ban, unBanReason ) )

		# N.B. We do this blindly to to ensure that its done
		if not self.mm.isBattleFieldHeroes():
			host.rcon_invoke( "admin.removeAddressFromBanList %s" % ( ban ) )
		host.rcon_invoke( "admin.removeKeyFromBanList %s" % ( ban ) )

		# Remove any unban timer
		if self.__unBanTimers.has_key( ban ):
			self.__unBanTimers[ban].destroy()
			del self.__unBanTimers[ban]

		if self.__bans.has_key( ban ):
			del self.__bans[ban]

			if skipSave:
				return True
			# Persist the banlist
			return self.saveBanlist()
		else:
			self.mm.warn( "Ban '%s' not found" % ban )

		return False
示例#11
0
def echoMessage(msg):
    try:
        host.rcon_invoke("echo \"" + str(msg) + "\"")
    except:
        host.rcon_invoke(
            "echo \"" +
            'sendMessageToAll(): failed to display message' +
            "\"")
示例#12
0
 def onGameStatusChanged(self, status):
     if status == bf2.GameStatus.PreGame:
         # Fixes that bot's are endless spamming sentry drones.
         # They're disabled for bots.
         host.rcon_invoke(
             "ObjectTemplate.activeSafe GenericFireArm Unl_Drone_Sentry_Detonator"
         )
         host.rcon_invoke("ObjectTemplate.aiTemplate \"\"")
示例#13
0
def sendMessageToAll(msg):
    try:
        host.rcon_invoke("game.sayAll \"" + str(msg) + "\"")
    except:
        host.rcon_invoke(
            "game.sayAll \"" +
            'sendMessageToAll(): failed to display message' +
            "\"")
def onPlayerNameValidated(realNick, oldNick, realPID, oldPID, player):
	if realNick != oldNick:
		message = "Player: %s, real name %s, was kicked and banned for using Name Hacks" % (oldNick, realNick)
	elif realPID != oldPID:
		message = "Player: %s tried to use wrong PlayerID %d (real PID %d); kicked and banned for using PID Hacks" % (oldNick, oldPID, realPID)
	else:
		return
	host.rcon_invoke("admin.banPlayer %d %d" % (player.index, BANTIME))
	host.sgl_sendTextMessage(0, 12, 1, message, 0)
示例#15
0
def getServerInfo(self, ctx, cmd):
    output = (
        'servername\tplayers_connected\tplayers_joining\tmod_dir\t'
        'mapname\tnextmap\tteam1_name\tteam2_name\tteam1_tickets\tteam2_tickets\t'
        'team1_defaulttickets\tteam2_defaulttickets\tticketratio\tteamratio\t'
        'numplayers\tmaxplayers\tgamemode\ttimelimit\tscorelimit\t'
        'autobalanceteam\ttkpunishenabled\ttknumpunishtokick\ttkpunishbydefault\t'
        'useglobalrank\tuseglobalunlocks\n')

    connected = 0
    joining = 0
    try:
        for p in bf2.playerManager.getPlayers():
            if p.isConnected():
                connected += 1
            else:
                joining += 1
    except:
        pass

    numplayers = joining + connected
    try:
        output += host.rcon_invoke('sv.serverName').strip()
        output += '\t' + str(connected)
        output += '\t' + str(joining)
        output += '\t' + str(bf2.gameLogic.getModDir())
        output += '\t' + str(bf2.gameLogic.getMapName().replace('_',
                                                                ' ').title())
        output += '\t' + str(
            host.rcon_invoke('maplist.list').splitlines()[int(
                host.rcon_invoke('admin.nextLevel').strip())].split()[1].strip(
                    '"').replace('_', ' ').title())
        output += '\t' + str(bf2.gameLogic.getTeamName(1))
        output += '\t' + str(bf2.gameLogic.getTeamName(2))
        output += '\t' + str(bf2.gameLogic.getTickets(1))
        output += '\t' + str(bf2.gameLogic.getTickets(2))
        output += '\t' + str(bf2.gameLogic.getDefaultTickets(1))
        output += '\t' + str(bf2.gameLogic.getDefaultTickets(2))
        output += '\t' + str(bf2.serverSettings.getTicketRatio())
        output += '\t' + str(bf2.serverSettings.getTeamRatioPercent())
        output += '\t' + str(numplayers)
        output += '\t' + str(bf2.serverSettings.getMaxPlayers())
        output += '\t' + str(bf2.serverSettings.getGameMode())
        output += '\t' + str(bf2.serverSettings.getTimeLimit())
        output += '\t' + str(bf2.serverSettings.getScoreLimit())
        output += '\t' + str(bf2.serverSettings.getAutoBalanceTeam())
        output += '\t' + str(bf2.serverSettings.getTKPunishEnabled())
        output += '\t' + str(bf2.serverSettings.getTKNumPunishToKick())
        output += '\t' + str(bf2.serverSettings.getTKPunishByDefault())
        output += '\t' + str(bf2.serverSettings.getUseGlobalRank())
        output += '\t' + str(bf2.serverSettings.getUseGlobalUnlocks())
        output += '\n'
    except:
        output = 'Error retriving server information.'

    ctx.write(output)
示例#16
0
def GetServerNextMap():
	mi = int( host.rcon_invoke('admin.nextLevel') )
	sml = []
	for x in [x[ x.find(':') + 1 :].strip() for x in host.rcon_invoke('mapList.list').split('\n')[:-1]]:
		spl = x.split()
		sml += ['%s %s %s' % (spl[0][1:-1], spl[1], spl[2])]
		
	Debug('Getting server next map. Next map index is %s. Server maplist is %s' % (mi, sml))
	
	return sml[mi][ len('') :]
示例#17
0
 def queryRun(self):
     for command in self.settings.keys():
         args = self.settings[command]
         args = '/'.join(args)
         host.rcon_invoke("""
             ObjectTemplate.active %s
             ObjectTemplate.%s %s
             """ % (self.template, attribute, args))
         D.debugMessage('ObjectTemplate.active %s\nObjectTemplate.%s %s' % (
             self.template, command, args))
示例#18
0
	def clearBanList( self ):
		"""Clears all bans."""
		self.mm.info( "Clearing banlist")
		host.rcon_invoke( "admin.clearBanList" )
		self.__bans = {}
		self.__roundBans = {}
		for timer in self.__unBanTimers:
			self.__unBanTimers[timer].destroy()
		self.__unBanTimers = {}

		return self.saveBanlist()
示例#19
0
def init():
	global OLDSCHOOL_LEVEL, PUNISH_METHOD, ANTICOMMANDER
	if OLDSCHOOL_LEVEL != 0:
		if ANTICOMMANDER == 1: host.registerHandler('ChangedCommander', onCommander, 1)
		if PUNISH_METHOD == 2: host.registerHandler('PlayerKilled', onPlayerKilled, 1)
		if PUNISH_METHOD == 0 or PUNISH_METHOD == 1 and OLDSCHOOL_LEVEL != 3: host.registerHandler('PlayerChangeWeapon', onPlayerChangeWeapon, 1)
		host.registerHandler('RemoteCommand', onRemoteCommand, 1)
		host.registerGameStatusHandler(onGameStatusChange)
		host.rcon_invoke('echo "bf2_oldschool.py by MisiekBest loaded"')
	else:
		host.rcon_invoke('echo "bf2_oldschool.py by MisiekBest loaded, script DISABLED by config!"')
示例#20
0
 def run(self):
     for attribute in self.settings.keys():
         values = self.settings[attribute]
         values = '/'.join(values)
         host.rcon_invoke("""
             ObjectTemplate.active %s
             ObjectTemplate.%s %s
             """ % (self.template, attribute, values))
         #D.debug('InvokeCommand:: host.rcon_invoke()')
         D.debug('ObjectTemplate.active %s' % (self.template))
         D.debug('ObjectTemplate.%s %s' % (attribute, values))
示例#21
0
    def execRcon(self):
        decho('dc_ass: entering execRcon() method', 5)
        if self.prepExec():
            decho('dc_ass: Running rcon command: %s' % self.command.rconString,
                  2)

            if self.command.arguments == None:
                unused = host.rcon_invoke(self.command.rconString)
            else:
                unused = host.rcon_invoke(self.command.rconString + ' ' +
                                          self.command.arguments)
示例#22
0
    def clearBanList(self):
        """Clears all bans."""
        self.mm.info("Clearing banlist")
        host.rcon_invoke("admin.clearBanList")
        self.__bans = {}
        self.__roundBans = {}
        for timer in self.__unBanTimers:
            self.__unBanTimers[timer].destroy()
        self.__unBanTimers = {}

        return self.saveBanlist()
def onPlayerNameValidated(realNick, oldNick, realPID, oldPID, player):
    if realNick != oldNick:
        message = "Player: %s, real name %s, was kicked and banned for using Name Hacks" % (
            oldNick, realNick)
    elif realPID != oldPID:
        message = "Player: %s tried to use wrong PlayerID %d (real PID %d); kicked and banned for using PID Hacks" % (
            oldNick, oldPID, realPID)
    else:
        return
    host.rcon_invoke("admin.banPlayer %d %d" % (player.index, BANTIME))
    host.sgl_sendTextMessage(0, 12, 1, message, 0)
示例#24
0
def pauseGame():
	global gstatus
	if (gstatus == 0):
		host.rcon_invoke("gameLogic.togglePause")
		sayAll("Game paused!")
		sayAll("!!! You can now communicate with others. Open console and type:")
		sayAll("rcon _your_message_")
		sayAll("Admins can unpause the game by typing in console: rcon unpause")
		gstatus = 1
	else:
		host.rcon_invoke("gameLogic.togglePause")
		gstatus = 0
示例#25
0
def rconExec(cmd):
    """
    Calls host.rcon_invoke.
    """
    global rconlog
    if rconlog: print >>rconlog, '$', cmd
    out = host.rcon_invoke(cmd).strip()
    if len(out) > 0 and rconlog: print >>rconlog, out
    if 'Unauthorised' in out:
        if rconlog: print >>rconlog, '! Unauthorised; console.access is', host.rcon_invoke('console.access').strip()
        return ''
    return out
示例#26
0
	def __updateServerPassword( self ):
		"""Sets or removes the password on the server depending on the state."""
		if not host.ss_getParam('ranked') and self.__config['privatePassword']:
			# We can password the server as its not ranked
			( needed_slots, remaining_slots ) = self.__neededRemainingSlots()
			if not needed_slots:
				# dont need any reserved slots remove the password
				host.rcon_invoke( 'sv.password ""' )
			else:
				host.rcon_invoke( 'sv.password "%s"' % self.__config['privatePassword'] )

		return 1
示例#27
0
    def __updateServerPassword(self):
        """Sets or removes the password on the server depending on the state."""
        if not host.ss_getParam('ranked') and self.__config['privatePassword']:
            # We can password the server as its not ranked
            (needed_slots, remaining_slots) = self.__neededRemainingSlots()
            if not needed_slots:
                # dont need any reserved slots remove the password
                host.rcon_invoke('sv.password ""')
            else:
                host.rcon_invoke('sv.password "%s"' %
                                 self.__config['privatePassword'])

        return 1
示例#28
0
def pauseGame():
    global gstatus
    if (gstatus == 0):
        host.rcon_invoke("gameLogic.togglePause")
        sayAll("Game paused!")
        sayAll(
            "!!! You can now communicate with others. Open console and type:")
        sayAll("rcon _your_message_")
        sayAll(
            "Admins can unpause the game by typing in console: rcon unpause")
        gstatus = 1
    else:
        host.rcon_invoke("gameLogic.togglePause")
        gstatus = 0
示例#29
0
    def setupDefaultQueries(self):
        del self.queries
        self.queries = []

        for vehicle in C.DEFAULT_QUERIES:
            D.debugMessage('QueryManager::parsing %s' % (vehicle))
            for vehicle_part in C.DEFAULT_QUERIES[vehicle]:
                invoke_string = ('ObjectTemplate.active %s' %
                                 (str(vehicle_part)))
                host.rcon_invoke(invoke_string)
                D.debugMessage(invoke_string)
                for param in C.DEFAULT_QUERIES[vehicle][vehicle_part]:
                    host.rcon_invoke(param)
                    D.debugMessage(param)
示例#30
0
    def loadBans(self):
        """Load the server bans."""
        if not mm_utils.fileexists(self.__banFileName):
            self.mm.info("Importing legacy ban information")
            # We dont currently have a ban file so check for legacy bans
            # read in server bans
            # N.B.  these will be overwritten later if we have full information about
            # them
            ban_re = re.compile('(Key|AccountId):\s+(\S+)\s+(\S+)')
            for line in host.rcon_invoke('admin.listBannedKeys').split('\n'):
                line = line.strip()
                match = ban_re.search(line)
                if match is not None:
                    cdkeyhash = self.validateBanCdKeyHash(match.group(2))
                    self.__addBan(mm_utils.BanMethod.key, None, match.group(3),
                                  None, cdkeyhash, None, None, None, None,
                                  True)
                elif line:
                    self.mm.error("BanManager: Unknown ban format '%s'" % line)

            if not self.mm.isBattleFieldHeroes():
                ban_re = re.compile('IP:\s+(\S+)\s+(\S+)')
                for line in host.rcon_invoke(
                        'admin.listBannedAddresses').split('\n'):
                    line = line.strip()
                    match = ban_re.search(line)
                    if match is not None:
                        address = self.validateBanAddress(match.group(1))
                        self.__addBan(mm_utils.BanMethod.address, None,
                                      match.group(2), address, None, None,
                                      None, None, None, True)
                    elif line:
                        self.mm.error("BanManager: Unknown ban format '%s'" %
                                      line)
        else:
            # Clear all legacy bans
            host.rcon_invoke("admin.clearBanList")

        # Ensure the ban file exists
        # Note: we dont use 'r' and test for errno.ENOENT as that may be incorrect
        # if a subdir doesnt exist
        try:
            banFile = open(self.__banFileName, 'a+')

        except RuntimeError, detail:
            self.mm.error(
                "Failed to open '%s' (%s)" % (self.__banFileName, detail),
                True)
            return False
示例#31
0
def onRestart(data):
    global TIME_TO_RESTART
    global temp_time
    global timer
    global inCounting

    if (temp_time > 0):
        host.sgl_sendTextMessage(0, 12, 1, "... %s " % (temp_time), 0)
        temp_time = temp_time - 1
    else:
        timer.destroy()
        timer = None
        temp_time = TIME_TO_RESTART
        inCounting = False
        host.rcon_invoke("admin.restartMap")
示例#32
0
def onRestart(data):
	global TIME_TO_RESTART
	global temp_time
	global timer
	global inCounting
	
	if (temp_time>0):
		host.sgl_sendTextMessage( 0, 12, 1, "... %s "  % (temp_time), 0)
		temp_time = temp_time - 1
	else:
		timer.destroy()
		timer = None
		temp_time = TIME_TO_RESTART
		inCounting = False
		host.rcon_invoke("admin.restartMap")
示例#33
0
    def _getPlayerList(self):
        rawData = host.rcon_invoke( 'admin.listplayers' )
        # this patern is for line 0 of the output for each player
        # pattern1 = re.compile(r'''^Id:\ +(\d+)\ -\ (\S+)\ is\ remote\ ip:\ (\d+\.\d+\.\d+\.\d+):(\d+)''', re.VERBOSE)
        pattern1 = re.compile(r'''^Id:\ +(\d+)\ -\ (.*?)\ is\ remote\ ip:\ (\d+\.\d+\.\d+\.\d+):(\d+)''', re.VERBOSE)
        # this patern is for line 1 of the output for each player
        pattern2 = re.compile(r'''(?:.*hash:\ (\w{32}))?''', re.VERBOSE)
        players = {}
        
        i = 0
        for line in rawData.split("\n"):
            # if we're looking at a "line 0"
            if i == 0:
                matches = pattern1.findall(line)
                if len(matches) != 0:
                    p_id = int(matches[0][0])
                    players[p_id] = []
                    players[p_id].append(matches[0][1])
                    players[p_id].append(matches[0][2])
                    players[p_id].append(matches[0][3])
 
            # if we're looking at a "line 1"
            elif i == 1:
                matches = pattern2.findall(line)
                players[p_id].append(matches[0])
 
            # flop the value of the iter
            i ^= 1
        
        return players
示例#34
0
def get_cd_key_hash(player):
    """Determine the players CDKey hash."""

    # Only BF2 doesnt getCDKeyHash
    if not mm.isBattleField2():
        return player.getCDKeyHash()

    # Players CDKey's dont change so check for it on the the player object
    if hasattr(player, 'mmCdKeyHash'):
        return player.mmCdKeyHash

    id_re = re.compile("Id:\s+%d\s+-" % player.index)
    found = False
    for line in host.rcon_invoke("admin.listPlayers").split('\n'):
        line = line.strip()
        match = id_re.search(line)
        if match is not None:
            # This is the player we are interested in
            found = True
        elif found:
            # the next line is the cdkey hash
            # Store it on the player object for fast access next time
            player.mmCdKeyHash = line[len("CD-key hash:"):].strip()
            return player.mmCdKeyHash

    return None
示例#35
0
    def getPlayerList(self):
        decho('dc_ass: entering getPlayerList() method', 5)
        rawData = host.rcon_invoke('admin.listplayers')
        # this pattern is for line 0 of the output for each player
        # pattern1 = re.compile(r'''^Id:\ +(\d+)\ -\ (\S+)\ is\ remote\ ip:\ (\d+\.\d+\.\d+\.\d+):(\d+)''', re.VERBOSE)
        pattern1 = re.compile(
            r'''^Id:\ +(\d+)\ -\ (.*?)\ is\ remote\ ip:\ (\d+\.\d+\.\d+\.\d+):(\d+)''',
            re.VERBOSE)
        # this pattern is for line 1 of the output for each player
        pattern2 = re.compile(r'''(?:.*hash:\ (\w{32}))?''', re.VERBOSE)
        players = {}

        i = 0
        for line in rawData.split("\n"):
            # if we're looking at a "line 0"
            if i == 0:
                matches = pattern1.findall(line)
                if len(matches) != 0:
                    p_id = int(matches[0][0])
                    players[p_id] = []
                    players[p_id].append(matches[0][1])
                    players[p_id].append(matches[0][2])
                    players[p_id].append(matches[0][3])

            # if we're looking at a "line 1"
            elif i == 1:
                matches = pattern2.findall(line)
                players[p_id].append(matches[0])

            # flop the value of the iter
            i ^= 1

        decho('dc_ass: exiting getPlayerList() method', 5)
        return players
示例#36
0
def get_player_details():
    """Returns the list of players with mmCDKeyHash set."""

    allset = True
    players_hash = {}
    for player in bf2.playerManager.getPlayers():
        if not hasattr(player, 'mmDetails'):
            allset = False
            break
        players_hash[player.index] = player

    if allset:
        return players_hash.values()

    rawData = host.rcon_invoke("admin.listplayers")

    # Thanks Woody http://bf2.fun-o-matic.org/index.php/Cookbook:Accessing_CD_Key_Hash
    pattern = re.compile(
        r'''^Id:\ +(\d+)					# PlayerID
				\ -\ (.*?)									# Player Name
				\ is\ remote\ ip:\ (\d+\.\d+\.\d+\.\d+):	# IP Address
				(\d+)										# Port Number
				(?:.*?hash:\ (\w{32}))?						# CD Key Hash
				''', re.DOTALL | re.MULTILINE | re.VERBOSE)

    players = []
    for data in pattern.findall(rawData):
        player = players_hash[int(data[0])]
        player.mmDetails = {'cdkeyhash': data[4], 'port': data[3]}
        # we do this just in case we have a miss match between
        # players_hash and the rawData
        players.append(player)

    return players
示例#37
0
def onChatMessage(player_id, text, channel, flags):
    
    # pull the potential prefix off the text line
    text = text.replace("HUD_TEXT_CHAT_TEAM", "")
    text = text.replace("HUD_TEXT_CHAT_SQUAD", "")
    text = text.replace("*\xA71DEAD\xA70*", "")
    
    # unless the first character is ! don't do anything 
    if text[0:1] == "!":
        decho("dc_irs: the first character of %s was !" % text, 5)
 
        # grab the parts of the chatline I need with a REGEX
        pattern = re.compile(r'!(\w*) ?(.*)')
        matches = pattern.findall(text)
        command = matches[0][0]
        decho("dc_irs: command = %s" % command, 5)  
 
        # grab a parameter, if any
        if matches[0][1] != "":
            parameter = matches[0][1]
            decho("dc_irs: parameter = %s" % parameter, 5)
        else:
            parameter = None
            decho("dc_irs: no parameter given", 5)
 
        if command == "nextmap":
            decho('The next map is %s' % host.rcon_invoke('maplist.list').splitlines()[int(host.rcon_invoke('admin.nextLevel').strip())].split()[1].strip('"').replace('_', ' ').title(), 1)
        elif command == "time":
            decho('The time is: %s' % time.strftime('%H:%M %p %Z'), 1)
        else:
            decho('ERROR: invalid command', 1)
示例#38
0
    def onPlayerSpawn(self, player, soldier):
        """Do something when a player spawns."""
        if 1 != self.__state:
            return 0

        try:
            players = bf2.playerManager.getPlayers()
            num_players = len(players)
            max_players = bf2.serverSettings.getMaxPlayers()
            if num_players > max_players:
                self.mm.warn("Too may players %d > %d (fixing)" %
                             (num_players, max_players))
                players_to_kick = num_players - max_players
                reason = self.__config['kickMessage']

                # Need to check the reserved slots for sorting
                self.__reservedSlots = {}
                for nick in host.rcon_invoke('reservedSlots.list').split('\n'):
                    self.__reservedSlots[nick] = True

                # Sort so we kick the last player to join
                players.sort(self.sortByConnected)
                for p in players:
                    self.mm.banManager().kickPlayer(p, reason)
                    players_to_kick -= 1
                    if 0 == players_to_kick:
                        return 1
        except Exception, detail:
            self.mm.error("Error (%s)" % (detail), True)
            return False
示例#39
0
	def onPlayerSpawn( self, player, soldier ):
		"""Do something when a player spawns."""
		if 1 != self.__state:
			return 0

		try:
			players = bf2.playerManager.getPlayers()
			num_players = len( players )
			max_players = bf2.serverSettings.getMaxPlayers()
			if num_players > max_players:
				self.mm.warn( "Too may players %d > %d (fixing)" % ( num_players, max_players ) )
				players_to_kick = num_players - max_players
				reason = self.__config['kickMessage']

				# Need to check the reserved slots for sorting
				self.__reservedSlots = {}
				for nick in host.rcon_invoke( 'reservedSlots.list' ).split( '\n' ):
					self.__reservedSlots[nick] = True
					
				# Sort so we kick the last player to join
				players.sort( self.sortByConnected )
				for p in players:
					self.mm.banManager().kickPlayer( p, reason )
					players_to_kick -= 1
					if 0 == players_to_kick:
						return 1
		except Exception, detail:
			self.mm.error( "Error (%s)" % ( detail ), True )
			return False
示例#40
0
    def checkPoints(self):
        decho('dc_ass: entering checkPoints() method', 5)
        for index, tracking in self.victimTracker.iteritems():
            # reset totalPoints for this victim (as we loop through them)
            # this variable hold the accumlative value of all points so far applied to a player
            totalPoints = self.getPointsFromIndex(index)

            # if we see any of our victims here lets print to the screen that they have new and shiny points
            if index in self.victimID:
                decho(
                    'dc_ass: %s now has %d of %d kick points' %
                    (bf2.PlayerManager.Player(index).getName(), totalPoints,
                     self.kickThreshold), 1)

            if totalPoints >= self.kickThreshold:
                # issue the kick command
                decho(
                    "dc_ass: Kicking player '%s' (%d) %s" %
                    (bf2.PlayerManager.Player(index).getName(), index,
                     self.command.reason), 1)
                # need to change this to show them ALL the reasons they were kicked
                unused = host.rcon_invoke(
                    'pb_sv_kick %d %d %s' %
                    (index + 1, self.command.length, self.command.reason))

        decho('dc_ass: exiting checkPoints() method', 5)
示例#41
0
def ReachedTimeLimit():
	global g_roundStartTime

	tlimit = float(host.rcon_invoke('sv.timeLimit'))
	
	if tlimit == 0:
		Debug("No time limit. Returning False")
		
		return False

	tel = host.timer_getWallTime() - g_roundStartTime - float(host.rcon_invoke('sv.startDelay'))
	res = tel >= tlimit
	
	Debug('ReachedTimeLimit> Time elapsed %s, time limit %s. Result %s' % (tel, tlimit, res))
	
	return res
示例#42
0
    def doSendMessage(self, msg, player=None, type=1):
        self.Debug("doSendMessage")
        if self.isPublicWarning == 1:
            type = 1

        if player == None:
            host.rcon_invoke('game.sayall "%s %s"' % (self.prefixMsg, msg))
        else:
            player_name = player.getName()
            self.Debug("Sending message: %s %s" % (player_name, msg))

            if type == 1:
                host.rcon_invoke('game.sayall "%s %s %s"' %
                                 (self.prefixMsg, player_name, msg))
            elif type == 2:
                mm_utils.PersonalMessage(
                    "%s %s %s" % (self.prefixMsg, player_name, msg), player)
示例#43
0
def init():
    global OLDSCHOOL_LEVEL, PUNISH_METHOD, ANTICOMMANDER
    if (OLDSCHOOL_LEVEL != 0):
        if (ANTICOMMANDER == 1):
            host.registerHandler('ChangedCommander', onCommander, 1)
        if (PUNISH_METHOD == 2):
            host.registerHandler('PlayerKilled', onPlayerKilled, 1)
        if (PUNISH_METHOD == 0
                or (PUNISH_METHOD == 1 and OLDSCHOOL_LEVEL != 3)):
            host.registerHandler('PlayerChangeWeapon', onPlayerChangeWeapon, 1)
        host.registerHandler('RemoteCommand', onRemoteCommand, 1)
        host.registerGameStatusHandler(onGameStatusChange)
        host.rcon_invoke('echo "bf2_oldschool.py by MisiekBest loaded"')
    else:
        host.rcon_invoke(
            'echo "bf2_oldschool.py by MisiekBest loaded, script DISABLED by config!"'
        )
示例#44
0
def onCommander(teamid, oldCommanderPlayerObject, player):
		global OLDSCHOOL_LEVEL
		if OLDSCHOOL_LEVEL != 0:	
			global ANTICOMMANDER
			if ANTICOMMANDER: #yeap. Double check. Unfortunately DICE forgot to implement host.UNregisterHandler... And this is the only way to disable anticommander (and other) 'on the fly' by using remote rcon command. Sorry :P
				global COMMANDER_AUTOKICK
				if COMMANDER_AUTOKICK == 1:
					global COMMANDER_KICK_MSG, COMMANDER_KICK_REASON, COMMANDER_KICK_TIME_IN_MINUTES
					host.sgl_sendTextMessage( 0, 12, 1, str(COMMANDER_KICK_MSG)  % (player.getName()), 0)
					host.rcon_invoke("pb_sv_kick \""+str(player.getName())+"\" "+str(COMMANDER_KICK_TIME_IN_MINUTES)+" \""+str(COMMANDER_KICK_REASON)+"\"")
				else:
					global COMMANDER_MSG
					host.sgl_sendTextMessage( 0, 12, 1, str(COMMANDER_MSG)  % (player.getName()), 0)
					host.sgl_sendTextMessage( 0, 12, 1, str(COMMANDER_MSG)  % (player.getName()), 0)
					host.sgl_sendTextMessage( 0, 12, 1, str(COMMANDER_MSG)  % (player.getName()), 0)
					host.sgl_sendTextMessage( 0, 12, 1, str(COMMANDER_MSG)  % (player.getName()), 0)
					host.sgl_sendTextMessage( 0, 12, 1, str(COMMANDER_MSG)  % (player.getName()), 0)
示例#45
0
def getCurrentRound():
    """
    Returns a 3 tuple of map, gamemode, size (str, str, int).
    """
    maplist = getMapList()
    current = int(host.rcon_invoke('maplist.currentMap').strip())
    if current >= len(maplist):
        return ('unknown', 'gpm_cq', 16)
    return maplist[current]
示例#46
0
def decho(msg, level=1):
    # 1 = info w/ in-game feedback
    # 2 = info
    # 5 = debug

    if debug_level > 0 and debug_level >= level:
        string = time.strftime('%Y-%m-%d %H:%M:%S') + ' - ' + msg

        if log_to_stdout:
            print string

        if log_to_file:
            fh = open(log_filename, 'a')
            fh.write(string + '\n')
            fh.close()

        if level == 1:
            host.rcon_invoke('game.sayall "%s"' % msg)
示例#47
0
	def unpause( self ):
		"""Unpause the game."""
		if bf2.GameStatus.Paused == self.currentGameStatus:
			msg = host.rcon_invoke( 'gameLogic.togglePause' )
			# TODO: remove when fixed
			self.onGameStatusChanged( bf2.GameStatus.Playing )
		else:
			msg = ''

		return msg
示例#48
0
	def __setConfigFile( self ):
		"""Determines where our config file is."""
		try:
			# Try 2142 way
			self.__configPath = host.sgl_getOverlayDirectory()
			try:
				test = bf2.stats.constants.TYPE_BFHEROES
				self.__gameString = self.__bfheroesString
				self.__gameId = self.__bfheroesId
			except:
				try:
					test = bf2.stats.constants.ARMY_US
					self.__gameString = self.__bfp4fString
					self.__gameId = self.__bfp4fId
				except:
					self.__gameString = self.__bf2142String
					self.__gameId = self.__bf2142Id
		except:
			# Failed 2142 so fall back to determining from the config
			self.__gameString = self.__bf2String
			self.__gameId = self.__bf2Id
			configFileParts = host.rcon_invoke( 'sv.configFile' ).replace( '\\', '/' ).split( '/' );
			del configFileParts[len( configFileParts ) - 1]

			self.__configPath = "/".join( configFileParts )

		if self.__configPath.startswith( '@HOME@' ):
			# since we have no access to the environment and cant
			# do any directory listings atm we have to just guess
			self.warn( "Guessing '@HOME@' = '%s'" % self.homeGuess )
			self.__configPath = "%s%s" % ( self.homeGuess, self.__configPath[5:] )

		filename = "%s/%s.con" % ( self.__configPath, __name__ )

		# lets check
		try:
			check = open( filename, 'r' )
		except:
			# nope no good so lets check in the standard place
			self.__configPath = "%s/settings" % host.sgl_getModDirectory().replace( '\\', '/' )
			filename = "%s/%s.con" % ( self.__configPath, __name__ )

			try:
				check = open( filename, 'r' )
			except:
				self.error( "Failed to determine location of '%s.con'" % __name__ )
			else:
				self.__configFile = filename
				self.warn( "Using config file '%s'" % filename )
				check.close()
		else:
			check.close()
			self.__configFile = filename
示例#49
0
def KickerSystem(player):
	global playerKickList, HOW_MANY_KILLS_TO_KICK, RESTRICTED_WEAPON_KICK_MSG, RESTRICTED_WEAPON_KICK_REASON, WARNING_AFTER_FRAG, RESTRICTED_WEAPON_KICK_IN_MINUTES
	playerId = player.getProfileId()
	t = 0
	for temp_player in playerKickList:
		if int(playerId) == int(temp_player[0]):
			temp_player[1]+=1;
			if temp_player[1] >= HOW_MANY_KILLS_TO_KICK:
				host.sgl_sendTextMessage( 0, 12, 1, str(RESTRICTED_WEAPON_KICK_MSG)  % (player.getName()), 0)
				host.rcon_invoke("pb_sv_kick \""+str(player.getName())+"\" "+str(RESTRICTED_WEAPON_KICK_IN_MINUTES)+" \""+str(RESTRICTED_WEAPON_KICK_REASON)+"\"")
				playerKickList.remove([playerId,temp_player[1]])
				t = 1
				
			else:
				host.sgl_sendTextMessage( 0, 12, 1, str(WARNING_AFTER_FRAG)  % (player.getName()), 0)
				t = 1
			
	if not t: 
		playerKickList.append([playerId, 1])
		host.sgl_sendTextMessage( 0, 12, 1, str(WARNING_AFTER_FRAG)  % (player.getName()), 0)
		t = 0
示例#50
0
    def onGameStatusChanged(self, status):
        if status == bf2.GameStatus.Playing:  # TODO: This should never be done if maplist module is loaded manually or reloaded!
            # Only shuffle maplist once after server startup if shuffle flag is set
            if not self.__shuffle:
                return
            if self.__initShuffledMapList:
                return

            maps = readMaps(self.__maplistPath +
                            self.__maplists[self.__nextMapList])
            maps = shuffleMaps(maps,
                               "gpm_ti")  # TODO: Create modmanager setting
            loadMaps(maps)
            host.rcon_invoke("admin.runNextLevel")
            self.__initShuffledMapList = True
        elif status == bf2.GameStatus.EndGame:
            if self.__currentMapList == self.__nextMapList:
                return

            if self.__shuffle:
                maps = readMaps(self.__maplistPath +
                                self.__maplists[self.__nextMapList])
                maps = shuffleMaps(maps,
                                   "gpm_ti")  # TODO: Create modmanager setting
                loadMaps(maps)
            else:
                host.rcon_invoke("maplist.configFile " + self.__maplistPath +
                                 self.__maplists[self.__nextMapList])
                host.rcon_invoke("maplist.load")
            self.__currentMapList = self.__nextMapList
示例#51
0
    def onGameStatusChanged(self, status):
        """Removes old round bans."""
        try:
            if bf2.GameStatus.PreGame == status:
                # Starting a new round remove old round bans
                for banKey in self.__roundBans:
                    self.expireBan(banKey, True)

                self.__roundBans = {}

                self.saveBanlist()

            # BF2 reloads banlist.con from disk on change so correct what its got by clearing
            # and reloading our banlist
            host.rcon_invoke("admin.clearBanList")

            by_key = mm_utils.BanMethod.key
            for banKey in self.__bans:
                ban = self.__bans[banKey]
                if by_key == ban['method']:
                    host.rcon_invoke("admin.addKeyToBanList %s %s" %
                                     (ban['cdkeyhash'], ban['period']))
                else:
                    host.rcon_invoke("admin.addAddressToBanList %s %s" %
                                     (ban['address'], ban['period']))

        except Exception, details:
            self.mm.error("Oooops: %s" % details, True)
示例#52
0
	def loadBans( self ):
		"""Load the server bans."""
		if not mm_utils.fileexists( self.__banFileName ):
			self.mm.info( "Importing legacy ban information" )
			# We dont currently have a ban file so check for legacy bans
			# read in server bans
			# N.B. these will be overwritten later if we have full information about them
			ban_re = re.compile( '(Key|AccountId):\s+(\S+)\s+(\S+)' )
			for line in host.rcon_invoke( 'admin.listBannedKeys' ).split( '\n' ):
				line = line.strip()
				match = ban_re.search( line )
				if match is not None:
					cdkeyhash = self.validateBanCdKeyHash( match.group(2) )
					self.__addBan( mm_utils.BanMethod.key, None, match.group(3), None, cdkeyhash, None, None, None, None, True )
				elif line:
					self.mm.error( "BanManager: Unknown ban format '%s'" % line )

			if not self.mm.isBattleFieldHeroes():
				ban_re = re.compile( 'IP:\s+(\S+)\s+(\S+)' )
				for line in host.rcon_invoke( 'admin.listBannedAddresses' ).split( '\n' ):
					line = line.strip()
					match = ban_re.search( line )
					if match is not None:
						address = self.validateBanAddress( match.group(1) )
						self.__addBan( mm_utils.BanMethod.address, None, match.group(2), address, None, None, None, None, None, True )
					elif line:
						self.mm.error( "BanManager: Unknown ban format '%s'" % line )
		else:
			# Clear all legacy bans
			host.rcon_invoke( "admin.clearBanList" )

		# Ensure the ban file exists
		# Note: we dont use 'r' and test for errno.ENOENT as that may be incorrect
		# if a subdir doesnt exist
		try:
			banFile = open( self.__banFileName, 'a+' )

		except RuntimeError, detail:
			self.mm.error( "Failed to open '%s' (%s)" % ( self.__banFileName, detail ), True )
			return False
示例#53
0
	def onGameStatusChanged( self, status ):
		"""Removes old round bans."""
		try:
			if bf2.GameStatus.PreGame == status:
				# Starting a new round remove old round bans
				for banKey in self.__roundBans:
					self.expireBan( banKey, True )

				self.__roundBans = {}

				self.saveBanlist()

			# BF2 reloads banlist.con from disk on change so correct what its got by clearing
			# and reloading our banlist
			host.rcon_invoke( "admin.clearBanList" )

			by_key = mm_utils.BanMethod.key
			for banKey in self.__bans:
				ban = self.__bans[banKey]
				if by_key == ban['method']:
					host.rcon_invoke( "admin.addKeyToBanList %s %s" % ( ban['cdkeyhash'], ban['period'] ) )
				else:
					host.rcon_invoke( "admin.addAddressToBanList %s %s" % ( ban['address'], ban['period'] ) )

		except Exception, details:
			self.mm.error( "Oooops: %s" % details, True )
示例#54
0
def setNextMap(admin):
    # default restltValue
    result = False
    argSize = None
    argGPM = None
    argName = None
 
    # split our args
    splitArgs = admin.splitArguments(admin.command.arguments)
    splitArgsLen = len(splitArgs)
 
    # this is for future use, right now we just use the argName
    if splitArgsLen > 2:
        argSize = splitArgs[2]
    if splitArgsLen > 1:
        argGPM = splitArgs[1]
    if splitArgsLen > 0:
        argName = splitArgs[0]
 
    if argName == None:
        decho( 'dc_ass: (ERROR) at least one argument is required', 1 ) 
    else:
        # set a centinal value for id so we know if we've found a map yet
        id = -1
        mapList = admin.getMapList()
    
        # search our maplist
        for mapID, mapData in mapList.iteritems():
            if mapData['name'].lower().find( argName.lower() ) != -1:
                decho( 'dc_ass: %s loosely matches %s' % ( argName, mapData['name'] ), 5 )
                # if this is the first map we've found...
                if id == -1:
                    decho( 'dc_ass: found %s in %s' % ( argName, mapData['name'] ), 5 )
                    id = mapID
                    result = True
                # if we've gotten another possible match...
                else:
                    result = False
                    break
 
        if id != -1:
            if result:
                decho( 'dc_ass: mapID found @ %d' % id, 5 )
                if host.rcon_invoke('admin.nextLevel %d' % id):
                    decho( 'dc_ass: nextmap will be %s' % mapList[id]['name'], 1 )
                else:
                    decho( 'dc_ass: (ERROR) failed to set nextmap', 1 )
            else:
                decho( 'dc_ass: %s is ambiguous.' % argName, 1 )
        else:
            decho( 'dc_ass: no maps can be matched to %s' % argName, 1 )
示例#55
0
def getMapList():
    maplist = host.rcon_invoke('maplist.list').strip()
    out = []
    for l in maplist.split('\n'):
        bits = l.split()
        if len(bits) == 3:
            idx, mapname, gamemode = bits
            size = '64'
        else:
            idx, mapname, gamemode, size = l.split()
        mapname = mapname[1:-1].lower()
        
        out.append([mapname, gamemode, size])
    return out
示例#56
0
    def checkPoints(self):
        for index, tracking in self.victim_tracker.iteritems():
            # reset total_points for this victim
            total_points = 0
 
            # added up all the points being applied to this victim
            for unused_key, points in tracking.iteritems():
                total_points += points    
                
            if index in self.victim_id:
                decho( "dc_ass: %s now has %d of %d kick points" % (bf2.PlayerManager.Player(index).getName(), total_points, self.kick_threshold), 1 )
 
            if total_points >= self.kick_threshold:
                self.reason += " - see dontcamp.com/forums for discussion"
                # issue the kick command
                decho( "dc_ass: Kicking player '%s' (%d) %s" % (bf2.PlayerManager.Player(index).getName(), index, self.reason), 1 ) 
                unused = host.rcon_invoke('pb_sv_kick %d %d %s' % (index + 1, self.length, self.reason) )
示例#57
0
 def kickPlayers(data):
    # Loops through 'kicklist', and kicks players accordingly.
    #print "IDLEKICK: kickPlayers..."
    global kicklist, KickTimer
    
    for i in kicklist:
       p = bf2.playerManager.getPlayerByIndex(i[0])
       # Make sure we're not kicking a player that has gotten an already disconnected "violater's" index:
       if not p.getProfileId() == i[1]: continue
       # Check if this player indeed has reached the limit for maximum warnings
       if warnings <= p.idleWarnings:
          # Kick if limit is reached:
          if g_debug or xlr_debug: print "IDLEKICK: Kicking player " + p.getName() + " for being idle."
          result = host.rcon_invoke("admin.kickPlayer " + str(p.index)) 
    kicklist = []
    KickTimer.destroy()
    KickTimer = None
 # ------------------------------------------------------------------------
示例#58
0
	def onGameStatusChanged( self, status ):
		"""Make a note of the game status"""
		self.debug( 1, "STATUS: %d = %s" % ( status, mm_utils.status_name( status ) ) )
		if bf2.GameStatus.EndGame == status:
			self.__playCount = 0
			self.__pauseStart = 0
			self.__timeLimit = 0
			self.gamePlaying = False
			self.roundStarted = False

		elif bf2.GameStatus.Playing == status:
			self.gamePlaying = True
			now = int( host.timer_getWallTime() )

			if bf2.GameStatus.PreGame == self.currentGameStatus:
				# normal transition i.e. not pause
				start_delay = int( host.rcon_invoke( 'sv.startDelay' ) )
				self.__playCount += 1
				self.__timeLimit = host.ss_getParam( 'timeLimit' )
				self.__matchTimeLost = 0
				self.startTimeUTC = int( time.time() ) + start_delay
				self.startTimeWall = now + start_delay
				if 2 == self.__playCount:
					# We see state change from PreGame -> Playing twice before the round really starts
					self.roundStarted = True

			elif bf2.GameStatus.Paused == self.currentGameStatus:
				self.__matchTimeLost += ( now - self.__pauseStart )
				self.__pauseStart = 0

		elif bf2.GameStatus.Paused == status:
			self.__pauseStart = int( host.timer_getWallTime() )

		else:
			self.__pauseStart = 0

		self.lastGameStatus = self.currentGameStatus
		self.currentGameStatus = status
示例#59
0
def execRconCmd(cmd):
	sc = str(cmd).split()
	if sc[0] == "bfo":
		if not isThirdArg(sc):
			if sc[1] == "status":
				global RESTRICTED_WEAPON_KICK_IN_MINUTES, HOW_MANY_KILLS_TO_KICK, OLDSCHOOL_LEVEL, NO_C4, NO_CLAYMORE, NO_MOUNTED_MGS, NO_TOW_MISSILE, PUNISH_METHOD, ANTICOMMANDER, COMMANDER_AUTOKICK, COMMANDER_KICK_TIME_IN_MINUTES
				host.rcon_invoke("game.sayAll \"MAIN CONFIG ==> OLDSCHOOL LEVEL: " + str(OLDSCHOOL_LEVEL) + ", PUNISH METHOD: " + str(PUNISH_METHOD) + ", NO CLAYMORE: " + str(NO_CLAYMORE) + ", NO C4: " + str(NO_C4) + ", NO MOUNTED MGS: " + str(NO_MOUNTED_MGS) + ", NO TOW: " + str(NO_TOW_MISSILE) + "\"")
				host.rcon_invoke("game.sayAll \"PUNISH METHOD 2 KICKER SYSTEM ==>  HOW MANY KILLS TO KICK: " + str(HOW_MANY_KILLS_TO_KICK) + ", RESTRICTED WEAPON KICK TIME: " + str(NO_C4) + "min.\"")
				host.rcon_invoke("game.sayAll \"ANTICOMM ==> ANTICOMMANDER: " + str(ANTICOMMANDER) + ", COMMANDER AUTOKICK: " + str(COMMANDER_AUTOKICK) + ", COMMANDER KICK TIME: " + str(COMMANDER_KICK_TIME_IN_MINUTES) + "min.\"")
			elif sc[1] == "punish":
				global PUNISH_METHOD
				host.rcon_invoke("game.sayAll \"BFO:::      PUNISH METHOD: " + str(PUNISH_METHOD) + "\"")
			elif sc[1] == "olevel":
				global OLDSCHOOL_LEVEL
				host.rcon_invoke("game.sayAll \"BFO:::      OLDSCHOOL LEVEL: " + str(OLDSCHOOL_LEVEL) + "\"")
			elif sc[1] == "c4":
				global NO_C4
				host.rcon_invoke("game.sayAll \"BFO:::      NO C4: " + str(NO_C4) + "\"")
			elif sc[1] == "claymore":
				global NO_CLAYMORE
				host.rcon_invoke("game.sayAll \"BFO:::      NO CLAYMORE: " + str(NO_CLAYMORE) + "\"")
			elif sc[1] == "mgs":
				global NO_MOUNTED_MGS
				host.rcon_invoke("game.sayAll \"BFO:::      NO MOUNTED MGS: " + str(NO_MOUNTED_MGS) + "\"")
			elif sc[1] == "tow":
				global NO_TOW_MISSILE
				host.rcon_invoke("game.sayAll \"BFO:::      NO TOW MISSILE: " + str(NO_TOW_MISSILE) + "\"")
			elif sc[1] == "kick_frags":
				global HOW_MANY_KILLS_TO_KICK
				host.rcon_invoke("game.sayAll \"BFO:::      KICK PLAYER AFTER: " + str(HOW_MANY_KILLS_TO_KICK) + " FRAGS.\"")
			elif sc[1] == "kick_time":
				global RESTRICTED_WEAPON_KICK_IN_MINUTES
				host.rcon_invoke("game.sayAll \"BFO:::      KICK PLAYER FOR: " + str(RESTRICTED_WEAPON_KICK_IN_MINUTES) + " MIN.\"")
			elif sc[1] == "anticomm":
				global ANTICOMMANDER
				host.rcon_invoke("game.sayAll \"BFO:::      ANTI COMMANDER: " + str(ANTICOMMANDER) + "\"")
			elif sc[1] == "commkick":
				global COMMANDER_AUTOKICK
				host.rcon_invoke("game.sayAll \"BFO:::      COMMANDER AUTOKICKER: " + str(COMMANDER_AUTOKICK) + "\"")
			elif sc[1] == "commkick_time":
				global COMMANDER_KICK_TIME_IN_MINUTES
				host.rcon_invoke("game.sayAll \"BFO:::      KICK COMMANDER FOR: " + str(COMMANDER_KICK_TIME_IN_MINUTES) + " MIN.\"")
			elif sc[1] == "help":
				sayAll("                             Ver 0.9 BETA Last changed: 25.Apr.2008")
				sayAll("                             For more info mail to: [email protected] or visit website: http://bfo.misiekbest.pl")
				sayAll("This help include all commands that can be executed in game console via rcon.")
				sayAll("TO EXECUTE COMMAND TYPE IN CONSOLE: rcon bfo [command] [value].")
				sayAll("")
				sayAll("############## OLDSCHOOL LEVEL ##############")
				sayAll("#############################################")
				sayAll("olevel         # Return number of oldschool level")
				sayAll("olevel [value] # Set oldschool level to given value")
				sayAll("Here are all oldschool levels:")
				sayAll("0 - Scrpit completely disabled.")
				sayAll("1 - ONLY MEDICS and MEDICS UNLOCKS")
				sayAll("2 - ONLY MEDICS and NO MEDICS UNLOCKS")
				sayAll("3 - ONLY KNIFE, PISTOL AND SHOCK PADDLES ALLOWED. NOTE: This level will only work with punish method set to 0 or 2")
				sayAll("4 - NO UNLOCKS")
				sayAll("5 - DONT USE OLDSCHOOL LEVEL, JUST CHECK OTHER THINGS LIKE NO C4 or NO CLAYMORE")
				sayAll("6 - NO SNIPERS")
				sayAll("")
				sayAll("############## PUNISH METHOD  ##############")
				sayAll("############################################")
				sayAll("punish         # Return number of punish method")
				sayAll("punish [value] # Set punish method to given value")
				sayAll("Here are all punish methods:")
				sayAll("0 - Only warning enabled. No other punishment")
				sayAll("1 - Kill player just after respawn with forbidden weapon. If restricted are c4 or claymore player will die after switching to them. This wont work for mounted mgs and tow. Sorry.")
				sayAll("2 - Kick player after previously given kick_frags variable. To set number of frags run: rcon bfo kick_frags [value]")
				sayAll("")
				sayAll("##############   MISC WEAPONS   ##############")
				sayAll("##############################################")
				sayAll("c4         # Return status of C4 restriction")
				sayAll("c4 [value] # Enable or disble C4 restriction. 0-Disable  1-Enable")
				sayAll("claymore         # Return status of CLAYMORE restriction")
				sayAll("claymore [value] # Enable or disble CLAYMORE restriction. 0-Disable  1-Enable")
				sayAll("mgs         # Return status of MOUNTED MGS restriction")
				sayAll("mgs [value] # Enable or disble MOUNTED MGS restriction. 0-Disable  1-Enable")
				sayAll("tow         # Return status of TOW MISSILE restriction")
				sayAll("tow [value] # Enable or disble TOW MISSILE restriction. 0-Disable  1-Enable")
				sayAll("")
				sayAll("##############   KICKER SYSTEM (punish 2)   ##############")
				sayAll("##########################################################")
				sayAll("kick_frags         # Return number of how many kills from restricted weapon to kick player")
				sayAll("kick_frags [value] # Set HOW_MANY_KILLS_TO_KICK to given value")
				sayAll("kick_time          # Return minutes for how long player should be kicked out.")
				sayAll("kick_time [value]  # Set minutes for how long player should be kicked out.")
				sayAll("")
				sayAll("##############    ANTI COMMANDER    ##############")
				sayAll("##################################################")
				sayAll("anticomm           # Return status of ANTICOMMANDER system")
				sayAll("anticomm [value]   # Enable or disble commander restriction. 0-Disable  1-Enable")
				sayAll("commkick           # Return status of COMMANDER KICKER system")
				sayAll("commkick [value]   # Enable or disble commander kicking. 0-Disable  1-Enable")
				sayAll("commkick_time          # Return minutes for how long commander should be kicked out.")
				sayAll("commkick_time [value]  # Set minutes for how long commander should be kicked out.")
				sayAll("")
				sayAll("")
				sayAll("")
				sayAll("")
				sayAll("HELP GENERATED. NOW OPEN YOUR CONSOLE TO SEE IT. YOU CAN NAVIGATE UP AND DOWN BY PRESSING PAGE UP AND PAGE DOWN ON YOUR KEYBOARD")
			else:
				host.rcon_invoke("game.sayAll \"BFO:::      !!!!ERROR!!!! Unknown command : " + str(sc[1]) + "\"")
				host.rcon_invoke("game.sayAll \"BFO:::      Use: status, punish, olevel, c4, claymore, mgs, tow, kick_frags, kick_time, anticomm, commkick, commkick_time\"")
		else:
			if isInt(sc[2]):
				if sc[1] == "punish":
					if 0<=int(sc[2])<=2:
						global PUNISH_METHOD
						PUNISH_METHOD = int(sc[2])
						if PUNISH_METHOD == 0 or PUNISH_METHOD == 1:
							try:
								host.registerHandler('PlayerChangeWeapon', onPlayerChangeWeapon, 1)
							except:
								pass
						else:
							try:
								host.registerHandler('PlayerKilled', onPlayerKilled, 1)
							except:
								pass
						host.rcon_invoke("game.sayAll \"BFO:::      PUNISH METHOD SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! Punish method must be 0, 1 or 2 ")
				elif sc[1] == "olevel":
					if 0<=int(sc[2])<=6:
						global OLDSCHOOL_LEVEL
						OLDSCHOOL_LEVEL = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      OLDSCHOOL LEVEL SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! oldschool level must be 0, 1, 2, 3, 4, 5 or 6")
				elif sc[1] == "c4":
					if 0<=int(sc[2])<=1:
						global NO_C4
						NO_C4 = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      NO C4 SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! C4 can be set only to 0 or 1")
				elif sc[1] == "claymore":
					if 0<=int(sc[2])<=1:
						global NO_CLAYMORE
						NO_CLAYMORE = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      NO CLAYMORE SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! CLAYMORE can be set only to 0 or 1")
				elif sc[1] == "mgs":
					if 0<=int(sc[2])<=1:
						global NO_MOUNTED_MGS
						NO_MOUNTED_MGS = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      NO MOUNTED MGS SET TO: " + str(sc[2]) + "\"")
						sayAll("BFO:::      !!!!ERROR!!!! MGS can be set only to 0 or 1")
				elif sc[1] == "tow":
					if 0<=int(sc[2])<=1:
						global NO_TOW_MISSILE
						NO_TOW_MISSILE = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      NO TOW MISSILE SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! TOW can be set only to 0 or 1")
				elif sc[1] == "kick_frags":
					if 0<=int(sc[2]):
						global HOW_MANY_KILLS_TO_KICK
						HOW_MANY_KILLS_TO_KICK = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      HOW MANY KILLS TO KICK SET TO: " + str(sc[2]) + " FRAGS\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! KICK_FRAGS must be greater than or equal to 0")
				elif sc[1] == "kick_time":
					if 0<=int(sc[2]):
						global RESTRICTED_WEAPON_KICK_IN_MINUTES
						RESTRICTED_WEAPON_KICK_IN_MINUTES = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      KICK PLAYER TIME SET TO: " + str(sc[2]) + " MIN.\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! KICK_TIME must be greater than or equal to 0")
				elif sc[1] == "anticomm":
					if 0<=int(sc[2])<=1:
						global ANTICOMMANDER
						ANTICOMMANDER = int(sc[2])
						if ANTICOMMANDER == 1:
							try:
								host.registerHandler('ChangedCommander', onCommander, 1)
							except:
								pass
						host.rcon_invoke("game.sayAll \"BFO:::      ANTI COMMANDER SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! ANTICOMM can be set only to 0 or 1")
				elif sc[1] == "commkick":
					if 0<=int(sc[2])<=1:
						global COMMANDER_AUTOKICK
						COMMANDER_AUTOKICK = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      COMMANDER AUTOKICK SET TO: " + str(sc[2]) + "\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! COMMKICK can be set only to 0 or 1")
				elif sc[1] == "commkick_time":
					if 0<=int(sc[2]):
						global COMMANDER_KICK_TIME_IN_MINUTES
						COMMANDER_KICK_TIME_IN_MINUTES = int(sc[2])
						host.rcon_invoke("game.sayAll \"BFO:::      COMMANDER KICK TIME SET TO: " + str(sc[2]) + " MIN.\"")
					else:
						sayAll("BFO:::      !!!!ERROR!!!! COMMKICK_TIME must be greater than or equal to 0")
				else:
					host.rcon_invoke("game.sayAll \"BFO:::      !!!!ERROR!!!! Unknown command : " + str(sc[2]) + "\"")
					host.rcon_invoke("game.sayAll \"BFO:::      Use: punish, olevel, c4, claymore, mgs, tow, kick_frags, kick_time, anticomm, commkick, commkick_time\"")
			else:
				host.rcon_invoke("game.sayAll \"BFO:::      !!!!ERROR!!!! Third argument must be numerical ammount! You wrote: " + str(sc[2]) + "\"")
示例#60
0
def sayAll(msg):
	host.rcon_invoke("game.sayAll \"" + str(msg) + "\"")