def run(self): try: BotList = [] ssbot = SubspaceBot(False,False,self.MQueue,logging.getLogger("ML." +self.type +".Core")) ssbot.setBotInfo(self.type,self.description,self.owner) self.ssbot = ssbot ssbot.arena = self.arena# serexl's bots look at arena in init bot = None for m in self.modules: bot = LoadBot(ssbot,m[0],m[1],self.inifile,self.args,logging.getLogger("ML." +self.type +"."+ m[0])) if bot: BotList.append (bot) bot = None retry = 0 while self.keepgoing: ssbot.connectToServer(self.host, self.port, self.bname, self.bpassword, self.arena) while ssbot.isConnected() and self.keepgoing: retry = 0 event = ssbot.waitForEvent() for b in BotList: b.HandleEvents(ssbot,event); if ssbot.shouldReconnect() and retry < 6: self.logger.debug("Disconnected...") ssbot.resetState() retry +=1 time.sleep(60*retry) self.logger.debug("Reconnecting...") else: break except: LogException(self.logger) finally: if ssbot.isConnected(): ssbot.disconnectFromServer() for b in BotList: b.Cleanup()
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot announces kills to the arena') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_KILL: bot.sendArenaMessage(event.killer.name + ' killed ' + event.killed.name + '!') print "Bot disconnected"
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * class PlayerInfo(): def __init__(self): self.consecutive_kills = 0 if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot announces kill sprees to the arena') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_ENTER: event.player.player_info = PlayerInfo() if event.type == EVENT_KILL: # increment the killers consecutive kills and announce if its time p = event.killer pi = event.killer.player_info pi.consecutive_kills += 1 if pi.consecutive_kills >= 5 and pi.consecutive_kills % 5 == 0: bot.sendArenaMessage(event.killer.name + ' is on a spree with ' + str(pi.consecutive_kills) + ' kills!') # announce the end of a kill-streak if the player has one, then reset the killed players consecutive kill count p = event.killed pi = event.killed.player_info
def MasterMain(): try: #other bots use logging i dont want it to spamm the main logger rootlogger = logging.getLogger('') rootlogger.addHandler(NullHandler()) rootlogger.setLevel(logging.DEBUG) #logging.basicConfig(level=logging.ERROR, # format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', # datefmt='%m-%d %H:%M') logger = logging.getLogger("ML") logger.setLevel(logging.DEBUG) # set a format formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s:%(message)s') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.DEBUG) # tell the handler to use this format console.setFormatter(formatter) # add the handler to the mainloop logger logger.addHandler(console) filehandler = logging.FileHandler(os.path.join(os.getcwd(),"Bots.log"),mode='a') filehandler.setLevel(logging.ERROR) filehandler.setFormatter(formatter) logger.addHandler(filehandler) #command Line Options parser = OptionParser() parser.add_option("-c", "--ConfigFile", dest="ConfigFile", help="Load Configuration from a non default file", default=os.path.join(os.getcwd(),"Bots.json")) parser.add_option("-p", "--Password", dest="Password", help="pass sysop/smod pass by commandline instead of in config", default=None) (options, args) = parser.parse_args() Queue = MasterQue() ssbot = SubspaceBot(False,True,Queue,logging.getLogger("ML.Master.Core")) ssbot.setBotInfo("Master","MasterBot Manages the starting/stopping of bots", None) BotList = [ ] config = GlobalConfiguration(options.ConfigFile,options.Password) #this adds dir's to pythonpath so we can run the dev code out of seperate dirs for p in config.paths: sys.path.append(p) #get the module object for the current file... module = sys.modules[globals()['__name__']] #loads atleast the masterbot md = ModuleData("Master",module,"None",config.ConfigurationFile,"",logging.getLogger("ML.Master")) master = Bot(ssbot,md,config,Queue) BotList.append(master) #load any bots that are specified in the config bot = None for m in config.Modules: bot = LoadBot(ssbot,m[0],m[1],config.ConfigurationFile,"",logging.getLogger("ML.Master." + m[0])) if bot: BotList.append (bot) bot = None wait_time = 0 while ssbot.shouldReconnect(): ssbot.connectToServer(config.Host, config.Port, config.MasterName, config.MasterPassword, config.MasterArena) while ssbot.isConnected(): wait_time = 0 event = ssbot.waitForEvent() for b in BotList: b.HandleEvents(ssbot,event) logger.critical("Master disconnected") if ssbot.shouldReconnect(): ssbot.resetState() wait_time+=60 if wait_time > 600: #if wait is over 10 mins reset wait period wait_time = 0 time.sleep(wait_time) # wait a little longer if retry fails each time logger.critical("Reconnecting") except (KeyboardInterrupt, SystemExit): logger.critical("CTRL-c or System.exit() detected") except: logger.critical("Unhandled Exception") LogException(logger) finally: if ssbot.isConnected(): ssbot.disconnectFromServer() logger.info( "Master disconnected" ) logger.info( "Waiting For Bots to stop") logger.critical("Master shutting down") master.StopAllBots() logger.critical("Requested Stop for all active bots...") for b in BotList: b.Cleanup() logger.critical("Master Bot behaviors cleansed") filehandler.close() sys.exit(1)
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot gives you an arena list') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" arena_command_id = bot.registerCommand('!arena', 'List the arenas in the zone') requester_names = [] while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_COMMAND: if event.command.id == arena_command_id: requester_names.append(event.player.name) bot.sendPublicMessage("?arena") elif event.type == EVENT_ARENA_LIST: if len(requester_names) > 0: player_name = requester_names.pop(0) for arena_name, num_players in event.arena_list: bot.sendPrivateMessage( player_name, 'Arena: %s - %d' % (arena_name, num_players))
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot rolls a random number between 1 and 100') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" roll_command_id = bot.registerCommand('!roll', 'Roll a number between 1 and 100') while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_COMMAND: if event.command.id == roll_command_id: random_number = random.randrange(1, 101) bot.sendArenaMessage(event.player.name + ' rolled ' + str(random_number) + ' (1-100)') print "Bot disconnected"
True if player.x_pos >= self.ul_x and player.y_pos >= self.ul_y and player.x_pos < self.lr_x and player.y_pos < self.lr_y else False ) class PlayerInfo: def __init__(self): self.start_ticks = None if __name__ == "__main__": bot = SubspaceBot(botowner, "This bot rolls a random number between 1 and 100") bot.connectToServer("66.235.184.102", 7900, botname, botpassword, "#python") print "Bot connected to server" beginning_warpto = (512, 512) start = Rectangle(478, 510, 483, 514) finish = Rectangle(541, 510, 545, 514) roll_start_id = bot.registerCommand("!race", "Start the race") while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_ENTER: # initialize player info event.player.player_info = PlayerInfo()
def __init__(self, ul_tile_x, ul_tile_y, lr_tile_x, lr_tile_y): self.ul_x = ul_tile_x * 16 self.ul_y = ul_tile_y * 16 self.lr_x = lr_tile_x * 16 self.lr_y = lr_tile_y * 16 def containsPlayer(self, player): # check if the player is inside the rectangle return True if player.x_pos >= self.ul_x and player.y_pos >= self.ul_y and player.x_pos < self.lr_x and player.y_pos < self.lr_y else False class PlayerInfo: def __init__(self): self.start_ticks = None if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot rolls a random number between 1 and 100') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" beginning_warpto = (512, 512) start = Rectangle(478, 510, 483, 514) finish = Rectangle(541, 510, 545, 514) roll_start_id = bot.registerCommand('!race', 'Start the race') while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_ENTER: # initialize player info event.player.player_info = PlayerInfo()
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot changes ship and freq') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" ship_command_id = bot.registerCommand('!ship', 'Change ship') freq_command_id = bot.registerCommand('!freq', 'Change ship') setposition_command_id = bot.registerCommand('!setposition', 'Change position') while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_COMMAND: if event.command.id == ship_command_id: if len(event.arguments) == 1: bot.requestShipChange(int(event.arguments[0])) elif event.command.id == freq_command_id: if len(event.arguments) == 1: bot.requestFreqChange(int(event.arguments[0])) elif event.command.id == setposition_command_id: if len(event.arguments) == 4: bot.setPosition(int(event.arguments[0]), int(event.arguments[1]), int(event.arguments[2]), int(event.arguments[3])) print "Bot disconnected"
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot announces ship changes') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_CHANGE: if event.old_ship != event.player.ship: bot.sendArenaMessage(event.player.name + ' changed from ' + GetShipName(event.old_ship) + ' to ' + GetShipName(event.player.ship) + '!') print "Bot disconnected"
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot gives you an arena list') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" arena_command_id = bot.registerCommand('!arena', 'List the arenas in the zone') requester_names = [] while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_COMMAND: if event.command.id == arena_command_id: requester_names.append(event.player.name) bot.sendPublicMessage("?arena") elif event.type == EVENT_ARENA_LIST: if len(requester_names) > 0: player_name = requester_names.pop(0) for arena_name, num_players in event.arena_list: bot.sendPrivateMessage(player_name, 'Arena: %s - %d' % (arena_name, num_players)) print "Bot disconnected"
def AddToReactor(self, reactor): try: BotList = [] ssbot = SubspaceBot(self.host, self.port, self.bname, self.bpassword, self.arena, False, BM_SLAVE, self.MQueue, logging.getLogger("ML." + self.type + ".Core")) ssbot.setBotInfo(self.type, self.description, self.owner) self.ssbot = ssbot ssbot.arena = self.arena # serexl's bots look at arena in init bot = None for m in self.modules: bot = LoadBot( ssbot, m[0], m[1], self.inifile, self.args, logging.getLogger("ML." + self.type + "." + m[0])) if bot: BotList.append(bot) bot = None ssbot.setBotList(BotList) self.listeningport = reactor.listenUDP(0, ssbot) ssbot.setReactorData(reactor, self.listeningport) except: LogException(self.logger) finally: if ssbot.isConnected(): ssbot.disconnectFromServer() for b in BotList: b.Cleanup()
def MasterMain(): try: #other bots use logging i dont want it to spamm the main logger rootlogger = logging.getLogger('') rootlogger.addHandler(NullHandler()) rootlogger.setLevel(logging.DEBUG) #logging.basicConfig(level=logging.ERROR, # format='%(asctime)s:%(name)s:%(levelname)s:%(message)s', # datefmt='%m-%d %H:%M') logger = logging.getLogger("ML") logger.setLevel(logging.DEBUG) # set a format formatter = logging.Formatter( '%(asctime)s:%(name)s:%(levelname)s:%(message)s') # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.DEBUG) # tell the handler to use this format console.setFormatter(formatter) # add the handler to the mainloop logger logger.addHandler(console) filehandler = logging.FileHandler(os.path.join(os.getcwd(), "Bots.log"), mode='a') filehandler.setLevel(logging.ERROR) filehandler.setFormatter(formatter) logger.addHandler(filehandler) #command Line Options parser = OptionParser() parser.add_option("-c", "--ConfigFile", dest="ConfigFile", help="Load Configuration from a non default file", default=os.path.join(os.getcwd(), "Bots.json")) parser.add_option( "-p", "--Password", dest="Password", help="pass sysop/smod pass by commandline instead of in config", default=None) (options, args) = parser.parse_args() Queue = MasterQue() config = GlobalConfiguration(options.ConfigFile, options.Password) ssbot = SubspaceBot(config.Host, config.Port, config.MasterName, config.MasterPassword, config.MasterArena, False, BM_MASTER, Queue, logging.getLogger("ML.Master.Core")) ssbot.setBotInfo("Master", "MasterBot Manages the starting/stopping of bots", None) BotList = [] #this adds dir's to pythonpath so we can run the dev code out of seperate dirs for p in config.paths: sys.path.append(p) #get the module object for the current file... module = sys.modules[globals()['__name__']] #loads atleast the masterbot md = ModuleData("Master", module, "None", config.ConfigurationFile, "", logging.getLogger("ML.Master")) master = Bot(ssbot, md, config, Queue) master.setReactor(reactor) BotList.append(master) #load any bots that are specified in the config bot = None for m in config.Modules: bot = LoadBot(ssbot, m[0], m[1], config.ConfigurationFile, "", logging.getLogger("ML.Master." + m[0])) if bot: BotList.append(bot) bot = None ssbot.setBotList(BotList) lp = reactor.listenUDP(0, ssbot) ssbot.setReactorData( reactor, lp ) # so clients can disconnect themselves when they get disconnect packet or master kills them reactor.run() except (KeyboardInterrupt, SystemExit): logger.critical("CTRL-c or System.exit() detected") except: logger.critical("Unhandled Exception") LogException(logger) finally: # if 'master' in locals(): # master.StopAllBots() if reactor.running: reactor.stop() for b in BotList: b.Cleanup() logger.critical("Master Bot behaviors cleansed") filehandler.close() os._exit(1)
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot sets timers') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" timer_command_id = bot.registerCommand('!timer', 'Set a timer') while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_COMMAND: if event.command.id == timer_command_id: if len(event.arguments) == 1: bot.setTimer(int(event.arguments[0]), event.player.name) bot.sendPrivateMessage(event.player.name, "Ok") else: bot.sendPrivateMessage(event.player.name, "Usage: !timer <seconds>") elif event.type == EVENT_TIMER: bot.sendPrivateMessage(event.user_data, "Timer expired") print "Bot disconnected"
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot announces an arena message periodically') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" last_arena_ticks = GetTickCountHs() interval = 5 * 60 * 100 # 5 minutes * 60 -> seconds, seconds * 100 -> hundreths of seconds while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_TICK: if (GetTickCountHs() - last_arena_ticks) & 0xFFFFFFFF >= interval: bot.sendArenaMessage('5 minutes have passed since the last message') last_arena_ticks = GetTickCountHs() print "Bot disconnected"
#!/usr/bin/env python # import python's random library for the random.randrange() function import random # import our credentials from file. this prevents us from embedding our # username/password in our bot files from Credentials import botowner, botname, botpassword # import the SubspaceBot class. this is what has all the features we need from SubspaceBot import * if __name__ == '__main__': # initialize the bot, setting its owner and description, then connecting to the server bot = SubspaceBot(botowner, 'This bot rolls a random number between 1 and 100') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" # register two commands, !roll and !about roll_command_id = bot.registerCommand('!roll', 'Roll a number between 1 and 100') # keep looping as long as the bot is connected. at each loop, pull out the next # even that is waiting for us to process while bot.isConnected(): event = bot.waitForEvent() # based on the event type, if event.type == EVENT_COMMAND: # based on what type of command this is, handle it accordingly
#!/usr/bin/env python import random from Credentials import botowner, botname, botpassword from SubspaceBot import * if __name__ == '__main__': bot = SubspaceBot(botowner, 'This bot announces an arena message periodically') bot.connectToServer('66.235.184.102', 7900, botname, botpassword, '#python') print "Bot connected to server" last_arena_ticks = GetTickCountHs() interval = 5 * 60 * 100 # 5 minutes * 60 -> seconds, seconds * 100 -> hundreths of seconds while bot.isConnected(): event = bot.waitForEvent() if event.type == EVENT_TICK: if (GetTickCountHs() - last_arena_ticks) & 0xFFFFFFFF >= interval: bot.sendArenaMessage( '5 minutes have passed since the last message') last_arena_ticks = GetTickCountHs() print "Bot disconnected"