def parseAdminCommand(wormid, message):
    global kickedUsers
    try:  # Do not check on msg size or anything, exception handling is further down
        if (not message.startswith(cfg.ADMIN_PREFIX)):
            return False  # normal chat

        cmd = message.split(" ")[0]
        cmd = cmd.replace(cfg.ADMIN_PREFIX, "", 1).lower()  #Remove the prefix

        if wormid >= 0:
            io.messageLog(
                "%i:%s issued %s" % (wormid, hnd.worms[wormid].Name,
                                     cmd.replace(cfg.ADMIN_PREFIX, "", 1)),
                io.LOG_ADMIN)
        else:
            io.messageLog("ded admin issued %s" % cmd, io.LOG_USRCMD)

        # Unnecesary to split multiple times, this saves CPU.
        params = message.split(" ")[1:]

        if cmd == "help":
            adminCommandHelp(wormid)
        elif cmd == "kick":
            kickTime = cfg.VOTING_KICK_TIME
            if len(params) > 1:  # Time for kick
                kickTime = float(params[1])
            wormIP = io.getWormIP(int(params[0])).split(":")[0]
            if wormIP != "127.0.0.1":
                kickedUsers[wormIP] = time.time() + kickTime * 60
            if len(params) > 2:  # Given some reason
                io.kickWorm(int(params[0]), " ".join(params[2:]))
            else:
                io.kickWorm(int(params[0]))
        elif cmd == "ban":
            if len(params) > 1:  # Given some reason
                io.banWorm(int(params[0]), " ".join(params[1:]))
            else:
                io.banWorm(int(params[0]))
        elif cmd == "mute":
            io.muteWorm(int(params[0]))
        elif cmd == "preset":
            preset = -1
            for p in range(len(hnd.availablePresets)):
                if hnd.availablePresets[p].lower().find(
                        params[0].lower()) != -1:
                    preset = p
                    break
            if preset == -1:
                io.privateMsg(
                    wormid, "Invalid preset, available presets: " +
                    ", ".join(hnd.availablePresets))
            else:
                hnd.selectPreset(Preset=hnd.availablePresets[preset])
        elif cmd == "mod":
            mod = ""
            for m in io.listMods():
                if m.lower().find(" ".join(params[0:]).lower()) != -1:
                    mod = m
                    break
            if mod == "":
                io.privateMsg(
                    wormid,
                    "Invalid mod, available mods: " + ", ".join(io.listMods()))
            else:
                hnd.selectPreset(Mod=mod)
        elif cmd == "map":
            level = ""
            for l in io.listMaps():
                if l.lower().find(" ".join(params[0:]).lower()) != -1:
                    level = l
                    break
            if level == "":
                io.privateMsg(
                    wormid,
                    "Invalid map, available maps: " + ", ".join(io.listMaps()))
            else:
                hnd.selectPreset(Level=level)
        elif cmd == "lt":
            hnd.selectPreset(LT=int(params[0]))
        elif cmd == "start":
            io.startGame()
        elif cmd == "stop":
            io.gotoLobby()
        elif cmd == "pause":
            io.privateMsg(wormid, "Ded script paused")
            hnd.scriptPaused = True
        elif cmd == "unpause":
            io.privateMsg(wormid, "Ded script continues")
            hnd.scriptPaused = False
        elif cmd == "setvar":
            io.setvar(params[0],
                      " ".join(params[1:]))  # In case value contains spaces
        elif cmd == "authorize":
            try:
                wormID = int(params[0])
                if not hnd.worms[wormID].isAdmin:
                    hnd.worms[wormID].isAdmin = True
                    io.authorizeWorm(wormID)
                    io.messageLog(
                        "Worm %i (%s) added to admins by %i (%s)" %
                        (wormID, hnd.worms[wormID].Name, wormid,
                         hnd.worms[wormid].Name), io.LOG_INFO)
                    io.privateMsg(
                        wormID, "%s made you admin! Type %shelp for commands" %
                        (hnd.worms[wormid].Name, cfg.ADMIN_PREFIX))
                    io.privateMsg(
                        wormid, "%s added to admins." % hnd.worms[wormID].Name)
            except KeyError:
                io.messageLog(
                    "parseAdminCommand: Our local copy of wormses doesn't match the real list.",
                    io.LOG_ERROR)
        elif parseAdminCommand_Preset and parseAdminCommand_Preset(
                wormid, cmd, params):
            pass
        else:
            raise Exception, "Invalid admin command"

    except:  # All python classes derive from main "Exception", but confused me, this has the same effect.
        if wormid >= 0:
            io.privateMsg(wormid, "Invalid admin command")
        io.messageLog(formatExceptionInfo(),
                      io.LOG_ERROR)  #Helps to fix errors
        return False
    return True
Beispiel #2
0
def controlHandlerDefault():

    global worms, gameState, lobbyChangePresetTimeout, lobbyWaitBeforeGame, lobbyWaitAfterGame
    global lobbyWaitGeneral, lobbyEnoughPlayers, oldGameState, scriptPaused, sentStartGame
    global currentAutocyclePreset, currentAutocycleMap
    global vote_locked, shuffle_counter

    if scriptPaused:
        return

    curTime = time.time()

    if gameState == GAME_LOBBY:

        # Do not check ping in lobby - it's wrong

        if oldGameState != GAME_LOBBY:
            lobbyEnoughPlayers = False  # reset the state
            lobbyWaitGeneral = curTime + cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
            lobbyWaitAfterGame = curTime
            if oldGameState == GAME_PLAYING:
                lobbyWaitAfterGame = curTime + cfg.WAIT_AFTER_GAME

            #Reset shuffle counter
            shuffle_counter = 0

            #Update votes when game ends
            updateResult = updateVotes(send_msg=("map", "mod", "teams"))
            #Autocycle if not voted
            #Advance autocycle counters first
            if not updateResult[0]:
                currentAutocycleMap += 1
                if currentAutocycleMap >= len(cfg.LEVELS):
                    currentAutocycleMap = 0
            if not updateResult[1]:
                currentAutocyclePreset += 1
                if currentAutocyclePreset >= len(cfg.PRESETS):
                    currentAutocyclePreset = 0
            ##Map
            if not updateResult[0]:
                io.setvar("GameOptions.GameInfo.LevelName",
                          cfg.LEVELS[currentAutocycleMap])
            ##Mod (preset)
            if not updateResult[1]:
                loadPreset(cfg.PRESETS[currentAutocyclePreset])

            #Check if teams are balanced
            ##This should be done because teams may become uneven if people leave during game and BALANCE_TEAMS_INGAME is not set
            if io.getGameType() == 1:
                io.chatMsg("Checking if teams are even...")
                balanceTeams(bmsg="game ended")

        if lobbyWaitAfterGame <= curTime:

            if not lobbyEnoughPlayers and lobbyWaitGeneral <= curTime:
                lobbyWaitGeneral = curTime + cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
                io.chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)

            if not lobbyEnoughPlayers and len(
                    worms
            ) >= cfg.MIN_PLAYERS:  # Enough players already - start game
                lobbyEnoughPlayers = True
                io.chatMsg(cfg.WAIT_BEFORE_GAME_MESSAGE)
                lobbyWaitBeforeGame = curTime + cfg.WAIT_BEFORE_GAME

            if lobbyEnoughPlayers and len(
                    worms
            ) < cfg.MIN_PLAYERS:  # Some players left when game not yet started
                lobbyEnoughPlayers = False
                io.chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)

            if lobbyEnoughPlayers and not sentStartGame:

                if lobbyWaitBeforeGame <= curTime:  # Start the game

                    #Starting game...		##NOTE Removed team check from here - teams should be assigned before the round starts
                    if io.startGame():
                        if cfg.ALLOW_TEAM_CHANGE and len(
                                worms) >= cfg.MIN_PLAYERS_TEAMS:
                            io.chatMsg(cfg.TEAM_CHANGE_MESSAGE)
                        sentStartGame = True
                        vote_locked = True  #Lock vote-able settings when starting
                        clearVotes()  #Clear votes when starting
                    else:
                        io.messageLog("Game could not be started",
                                      io.LOG_ERROR)  #Log these errors!
                        io.chatMsg("Game could not be started")
                        oldGameState == GAME_PLAYING  # hack that it resets at next control handler call

    if gameState == GAME_WEAPONS:

        # if we allow empty games, ignore this check
        if len(worms) < cfg.MIN_PLAYERS and not io.getVar(
                "GameOptions.GameInfo.AllowEmptyGames"
        ):  # Some players left when game not yet started
            io.chatMsg("Too few players -> back to lobby")
            io.gotoLobby()
            sentStartGame = False

    if gameState == GAME_PLAYING:

        if cfg.PING_CHECK:
            checkMaxPing()

    #Unlock voting when the game is safely running
    if (gameState == GAME_WEAPONS or gameState
            == GAME_PLAYING) and oldGameState != GAME_LOBBY and vote_locked:
        vote_locked = False
def parseAdminCommand(wormid,message):
	global kickedUsers
	try: # Do not check on msg size or anything, exception handling is further down
		if (not message.startswith(cfg.ADMIN_PREFIX)):
			return False # normal chat

		cmd = message.split(" ")[0]
		cmd = cmd.replace(cfg.ADMIN_PREFIX,"",1).lower() #Remove the prefix

		if wormid >= 0:
			io.messageLog("%i:%s issued %s" % (wormid,hnd.worms[wormid].Name,cmd.replace(cfg.ADMIN_PREFIX,"",1)),io.LOG_ADMIN)
		else:
			io.messageLog("ded admin issued %s" % cmd, io.LOG_USRCMD)

		# Unnecesary to split multiple times, this saves CPU.
		params = message.split(" ")[1:]

		if cmd == "help":
			adminCommandHelp(wormid)
		elif cmd == "kick":
			kickTime = cfg.VOTING_KICK_TIME
			if len(params) > 1: # Time for kick
				kickTime = float(params[1])
			wormIP = io.getWormIP(int( params[0] )).split(":")[0]
			if wormIP != "127.0.0.1":
				kickedUsers[ wormIP ] = time.time() + kickTime*60
			if len(params) > 2: # Given some reason
				io.kickWorm( int( params[0] ), " ".join(params[2:]) )
			else:
				io.kickWorm( int( params[0] ) )
		elif cmd == "ban":
			if len(params) > 1: # Given some reason
				io.banWorm( int( params[0] ), " ".join(params[1:]) )
			else:
				io.banWorm( int( params[0] ) )
		elif cmd == "mute":
			io.muteWorm( int( params[0] ) )
		elif cmd == "preset":
			preset = -1
			for p in range(len(hnd.availablePresets)):
				if hnd.availablePresets[p].lower().find(params[0].lower()) != -1:
					preset = p
					break
			if preset == -1:
				io.privateMsg(wormid,"Invalid preset, available presets: " + ", ".join(hnd.availablePresets))
			else:
				hnd.selectPreset( Preset = hnd.availablePresets[preset] )
		elif cmd == "mod":
			mod = ""
			for m in io.listMods():
				if m.lower().find(" ".join(params[0:]).lower()) != -1:
					mod = m
					break
			if mod == "":
				io.privateMsg(wormid,"Invalid mod, available mods: " + ", ".join(io.listMods()))
			else:
				hnd.selectPreset( Mod = mod )
		elif cmd == "map":
			level = ""
			for l in io.listMaps():
				if l.lower().find(" ".join(params[0:]).lower()) != -1:
					level = l
					break
			if level == "":
				io.privateMsg(wormid,"Invalid map, available maps: " + ", ".join(io.listMaps()))
			else:
				hnd.selectPreset( Level = level )
		elif cmd == "lt":
			hnd.selectPreset( LT = int(params[0]) )
		elif cmd == "start":
			io.startGame()
		elif cmd == "stop":
			io.gotoLobby()
		elif cmd == "pause":
			io.privateMsg(wormid,"Ded script paused")
			hnd.scriptPaused = True
		elif cmd == "unpause":
			io.privateMsg(wormid,"Ded script continues")
			hnd.scriptPaused = False
		elif cmd == "setvar":
			io.setvar(params[0], " ".join(params[1:])) # In case value contains spaces
		elif cmd == "authorize":
			try:
				wormID = int(params[0])
				if not hnd.worms[wormID].isAdmin:
					hnd.worms[wormID].isAdmin = True
					io.authorizeWorm(wormID)
					io.messageLog( "Worm %i (%s) added to admins by %i (%s)" % (wormID,hnd.worms[wormID].Name,wormid,hnd.worms[wormid].Name),io.LOG_INFO)
					io.privateMsg(wormID, "%s made you admin! Type %shelp for commands" % (hnd.worms[wormid].Name,cfg.ADMIN_PREFIX))
					io.privateMsg(wormid, "%s added to admins." % hnd.worms[wormID].Name)
			except KeyError:
				io.messageLog("parseAdminCommand: Our local copy of wormses doesn't match the real list.",io.LOG_ERROR)
		elif parseAdminCommand_Preset and parseAdminCommand_Preset(wormid, cmd, params):
			pass
		else:
			raise Exception, "Invalid admin command"

	except: # All python classes derive from main "Exception", but confused me, this has the same effect.
		if wormid >= 0:
			io.privateMsg(wormid, "Invalid admin command")
		io.messageLog(formatExceptionInfo(),io.LOG_ERROR) #Helps to fix errors
		return False
	return True
def controlHandlerDefault():

    global worms, gameState, lobbyChangePresetTimeout, lobbyWaitBeforeGame, lobbyWaitAfterGame
    global lobbyWaitGeneral, lobbyEnoughPlayers, oldGameState, scriptPaused, sentStartGame
    global presetCicler, modCicler, mapCicler, LT_Cicler
    global videoRecorder, videoRecorderSignalTime

    if scriptPaused:
        return

    curTime = time.time()
    cmds.recheckVote(False)

    if gameState == GAME_LOBBY:

        # Do not check ping in lobby - it's wrong

        if oldGameState != GAME_LOBBY:
            mapCicler.check()
            modCicler.check()
            LT_Cicler.check()
            presetCicler.check()
            lobbyEnoughPlayers = False  # reset the state
            lobbyWaitGeneral = curTime + cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
            lobbyWaitAfterGame = curTime
            if oldGameState == GAME_PLAYING:
                lobbyWaitAfterGame = curTime + cfg.WAIT_AFTER_GAME
            if videoRecorder:
                os.kill(
                    videoRecorder.pid, signal.SIGINT
                )  # videoRecorder.send_signal(signal.SIGINT) # This is available only on Python 2.6
                videoRecorderSignalTime = time.time()
                io.chatMsg("Waiting for video recorder to finish")

        canStart = True
        if videoRecorder and videoRecorder.returncode == None:
            canStart = False
            videoRecorder.poll()
            if time.time(
            ) - videoRecorderSignalTime > cfg.TIME_TO_KILL_VIDEORECORDER:
                io.chatMsg("Video recorder stalled, killing")
                os.kill(videoRecorder.pid, signal.SIGKILL)
                videoRecorder.poll()
            if videoRecorder.returncode != None:
                io.chatMsg("Video recorder encoding took " +
                           str(int(time.time() - videoRecorderSignalTime)) +
                           " secs")
                canStart = True
                videoRecorder = None

        if lobbyWaitAfterGame <= curTime:

            if not lobbyEnoughPlayers and lobbyWaitGeneral <= curTime:
                lobbyWaitGeneral = curTime + cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
                io.chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)

            if not lobbyEnoughPlayers and len(
                    worms
            ) >= cfg.MIN_PLAYERS:  # Enough players already - start game
                lobbyEnoughPlayers = True
                io.chatMsg(cfg.WAIT_BEFORE_GAME_MESSAGE)
                lobbyWaitBeforeGame = curTime + cfg.WAIT_BEFORE_GAME

            if lobbyEnoughPlayers and len(
                    worms
            ) < cfg.MIN_PLAYERS:  # Some players left when game not yet started
                lobbyEnoughPlayers = False
                io.chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)

            if lobbyEnoughPlayers and not sentStartGame:

                if lobbyWaitBeforeGame <= curTime and canStart:  # Start the game

                    if io.getGameType() in ["Death Match", "Team Death Match"]:
                        if len(worms
                               ) >= cfg.MIN_PLAYERS_TEAMS:  # Split in teams
                            setvar("GameOptions.GameInfo.GameType",
                                   "Team Death Match")
                            if not cfg.ALLOW_TEAM_CHANGE:
                                counter = 0
                                for w in worms.values():
                                    if w.iID != -1:
                                        io.setWormTeam(w.iID,
                                                       counter % cfg.MAX_TEAMS)
                                        counter += 1
                        else:
                            io.setvar("GameOptions.GameInfo.GameType",
                                      "Death Match")

                    if io.startGame():
                        if cfg.ALLOW_TEAM_CHANGE and len(
                                worms) >= cfg.MIN_PLAYERS_TEAMS:
                            io.chatMsg(cfg.TEAM_CHANGE_MESSAGE)
                        sentStartGame = True
                        if cfg.RECORD_VIDEO:
                            try:
                                #io.messageLog("Running dedicated-video-record.sh, curdir " + os.path.abspath(os.path.curdir) ,io.LOG_INFO)
                                videoRecorder = subprocess.Popen(
                                    [
                                        "./dedicated-video-record.sh",
                                        "./dedicated-video-record.sh"
                                    ],
                                    stdin=open("/dev/null", "r"),
                                    stdout=open("../../../dedicatedVideo.log",
                                                "w"),
                                    stderr=subprocess.STDOUT,
                                    cwd="..")
                            except:
                                io.messageLog(formatExceptionInfo(),
                                              io.LOG_ERROR)
                    else:
                        io.chatMsg("Game could not be started")
                        oldGameState == GAME_PLAYING  # hack that it resets at next control handler call

    if gameState == GAME_WEAPONS:

        #checkMaxPing()

        # if we allow empty games, ignore this check
        if len(worms) < cfg.MIN_PLAYERS and not io.getVar(
                "GameOptions.GameInfo.AllowEmptyGames"
        ):  # Some players left when game not yet started
            io.chatMsg("Too less players -> back to lobby")
            io.gotoLobby()
            sentStartGame = False

    if gameState == GAME_PLAYING:

        checkMaxPing()
def controlHandlerDefault():

	global worms, gameState, lobbyChangePresetTimeout, lobbyWaitBeforeGame, lobbyWaitAfterGame
	global lobbyWaitGeneral, lobbyEnoughPlayers, oldGameState, scriptPaused, sentStartGame
	global presetCicler, modCicler, mapCicler, LT_Cicler
	global videoRecorder, videoRecorderSignalTime
	
	if scriptPaused:
		return

	curTime = time.time()
	cmds.recheckVote(False)
	
	if gameState == GAME_LOBBY:

		# Do not check ping in lobby - it's wrong

		if oldGameState != GAME_LOBBY:
			mapCicler.check()
			modCicler.check()
			LT_Cicler.check()
			presetCicler.check()
			lobbyEnoughPlayers = False # reset the state
			lobbyWaitGeneral = curTime + cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
			lobbyWaitAfterGame = curTime
			if oldGameState == GAME_PLAYING:
				lobbyWaitAfterGame = curTime + cfg.WAIT_AFTER_GAME
			if videoRecorder:
				os.kill(videoRecorder.pid, signal.SIGINT)  # videoRecorder.send_signal(signal.SIGINT) # This is available only on Python 2.6
				videoRecorderSignalTime = time.time()
				io.chatMsg("Waiting for video recorder to finish")

		canStart = True
		if videoRecorder and videoRecorder.returncode == None:
			canStart = False
			videoRecorder.poll()
			if time.time() - videoRecorderSignalTime > cfg.TIME_TO_KILL_VIDEORECORDER:
				io.chatMsg("Video recorder stalled, killing")
				os.kill(videoRecorder.pid, signal.SIGKILL)
				videoRecorder.poll()
			if videoRecorder.returncode != None:
				io.chatMsg("Video recorder encoding took " + str(int(time.time() - videoRecorderSignalTime)) + " secs")
				canStart = True
				videoRecorder = None

		if lobbyWaitAfterGame <= curTime:

			if not lobbyEnoughPlayers and lobbyWaitGeneral <= curTime:
				lobbyWaitGeneral = curTime + cfg.WAIT_BEFORE_SPAMMING_TOO_FEW_PLAYERS_MESSAGE
				io.chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)

			if not lobbyEnoughPlayers and len(worms) >= cfg.MIN_PLAYERS: # Enough players already - start game
				lobbyEnoughPlayers = True
				io.chatMsg(cfg.WAIT_BEFORE_GAME_MESSAGE)
				lobbyWaitBeforeGame = curTime + cfg.WAIT_BEFORE_GAME

			if lobbyEnoughPlayers and len(worms) < cfg.MIN_PLAYERS: # Some players left when game not yet started
				lobbyEnoughPlayers = False
				io.chatMsg(cfg.TOO_FEW_PLAYERS_MESSAGE)

			if lobbyEnoughPlayers and not sentStartGame:

				if lobbyWaitBeforeGame <= curTime and canStart: # Start the game

					if io.getGameType() in ["Death Match","Team Death Match"]:
						if len(worms) >= cfg.MIN_PLAYERS_TEAMS: # Split in teams
							setvar("GameOptions.GameInfo.GameType", "Team Death Match")
							if not cfg.ALLOW_TEAM_CHANGE:
								counter = 0
								for w in worms.values():
									if w.iID != -1:
										io.setWormTeam( w.iID, counter % cfg.MAX_TEAMS )
										counter += 1
						else:
							io.setvar("GameOptions.GameInfo.GameType", "Death Match")

					if io.startGame():
						if cfg.ALLOW_TEAM_CHANGE and len(worms) >= cfg.MIN_PLAYERS_TEAMS:
							io.chatMsg(cfg.TEAM_CHANGE_MESSAGE)
						sentStartGame = True
						if cfg.RECORD_VIDEO:
							try:
								#io.messageLog("Running dedicated-video-record.sh, curdir " + os.path.abspath(os.path.curdir) ,io.LOG_INFO)
								videoRecorder = subprocess.Popen( ["./dedicated-video-record.sh", "./dedicated-video-record.sh"],
												stdin=open("/dev/null","r"), stdout=open("../../../dedicatedVideo.log","w"),
												stderr=subprocess.STDOUT, cwd=".." )
							except:
								io.messageLog(formatExceptionInfo(),io.LOG_ERROR)
					else:
						io.chatMsg("Game could not be started")
						oldGameState == GAME_PLAYING # hack that it resets at next control handler call
					
	if gameState == GAME_WEAPONS:

		#checkMaxPing()

		# if we allow empty games, ignore this check
		if len(worms) < cfg.MIN_PLAYERS and not io.getVar("GameOptions.GameInfo.AllowEmptyGames"): # Some players left when game not yet started
			io.chatMsg("Too less players -> back to lobby")
			io.gotoLobby()
			sentStartGame = False

	if gameState == GAME_PLAYING:

		checkMaxPing()