def main(args=None): """ Used by the pywatch script to handle command-line args. """ if not args: args = sys.argv[1:] usage = 'usage: %prog [options] "command" file1 file2 ...' parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="Output timestamp when commands are run.") parser.add_option("--version", action="store_true", dest="version", default=False, help="Output verion number and exit.") parser.add_option("--jsonconf", dest="jsonconf", help="Use advance JSON configuration file to run commands" ) options, args = parser.parse_args(args) if options.version: print "pywatch %s" % VERSION sys.exit(0) confile = None if options.jsonconf is not None: # Uses the JSON file to configure the main dir and actions to take if not os.path.isfile( options.jsonconf ): print( "Not valid jsonconf file name" ); else: confile = options.jsonconf elif os.path.isfile( ".tasksconfig.json" ): confile = ".tasksconfig.json" if confile is not None: cf = open( confile ) try: jconf = json.load( cf ) except ValueError: print "Invalid JSON" cf.close() exit() cf.close() tc = TasksConfig( jconf ) tc.run() elif len(args) >= 2: # "Classic" operation mode cmds = [args[0], ] files = args[1:] w = Watcher(cmds=cmds, files=files, verbose=options.verbose) w.run_monitor() sys.exit(0) else: print parser.error("You must provide a shell command and at least one file.")
def do_run_jtr_wordlist_mode(pJTR: JohnTheRipper, pWordlist: str, pRule: str) -> None: lCrackingMode = "Wordlist {}".format(os.path.basename(pWordlist)) if pRule: lCrackingMode += " with rule {}".format(pRule) lWatcher = Watcher(pCrackingMode=lCrackingMode, pJTR=pJTR) lWatcher.start_timer() lWatcher.print_mode_start_message() pJTR.run_wordlist_mode(pWordlist=pWordlist, pRule=pRule) lWatcher.stop_timer() lWatcher.print_mode_finsihed_message() gReporter.appendRecord( pMode=lCrackingMode, pMask="", pWordlist=pWordlist, pRule=pRule, pNumberPasswordsCracked=lWatcher.number_passwords_cracked_by_this_mode, pNumberPasswordsCrackedPerSecond=lWatcher. number_passwords_cracked_by_this_mode_per_second, pPercentPasswordsCracked=lWatcher. percent_passwords_cracked_by_this_mode)
def __init__(self, args): self.config = { 'ircdir': args[1], 'server': args[2], 'nick': args[3], 'channels': args[4].lower().split(' '), 'workdir': os.path.dirname(os.path.abspath(__file__)), } self.database = None self._modulesPath = None self._modulesList = [] self._triggers = [] self._replies = [] self._timers = [] try: print "[*] Starting core" self._initDatabase() self._initModules() self._controller = Controller(self) self._watcher = Watcher(self.config['ircdir'], self._callback, ['out']) except: e = sys.exc_info() print "[!] Uncaught exception: %s - %s" % (e[0], e[1]) sys.exit(1)
def setUp(self): self.w = Watcher( '', os.path.dirname(os.path.realpath(__file__)) + '/test/') self.w.savefile = '/test/test_watched.json' self.w.watched = [] self.w.save()
def run(self): handler = Watcher() handler.signals.update.connect(self.signals.update) handler.signals.update_map.connect(self.signals.update_map) handler.signals.update_cur.connect(self.signals.update_cur) handler.signals.update_dest.connect(self.signals.update_dest) handler.signals.update_done.connect(self.signals.update_done) handler.signals.update_radar.connect(self.signals.update_radar) recvSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) recvSocket.bind((self.host, self.port)) recvSocket.setblocking(False) while self.isalive(): try: data = recvSocket.recv(4096) except socket.timeout as e: err = e.args[0] if err == 'timed out': continue else: # a "real" error occurred print(e) sys.exit(1) except socket.error as e: err = e.args[0] if err == errno.EAGAIN or err == errno.EWOULDBLOCK: continue else: # a "real" error occurred print(e) sys.exit(1) else: message = pickle.loads( data ) print(message) handler.start_parse(message)
def do_run_jtr_prince_mode(pJTR: JohnTheRipper) -> None: lCrackingMode = "John the Ripper (JTR) Prince Mode" lWatcher = Watcher(pCrackingMode=lCrackingMode, pJTR=pJTR) lWatcher.start_timer() lWatcher.print_mode_start_message() pJTR.prince_element_count_min = 2 pJTR.prince_element_count_max = 3 pJTR.path_to_wordlist = "dictionaries" pJTR.wordlist = "prince.txt" pJTR.run_prince_mode() pJTR.prince_element_count_min = 2 pJTR.prince_element_count_max = 2 pJTR.wordlist = "short-list.txt" pJTR.run_prince_mode() pJTR.wordlist = "top-10000-english-words.txt" pJTR.run_prince_mode() lWatcher.stop_timer() lWatcher.print_mode_finsihed_message() gReporter.appendRecord( pMode=lCrackingMode, pMask="", pWordlist="", pRule="", pNumberPasswordsCracked=lWatcher.number_passwords_cracked_by_this_mode, pNumberPasswordsCrackedPerSecond=lWatcher. number_passwords_cracked_by_this_mode_per_second, pPercentPasswordsCracked=lWatcher. percent_passwords_cracked_by_this_mode)
def __init__(self,server,port,log): self.last_updated = 0 self.__init_ocurrences() self.graphite = Graphite(server, port) w = Watcher(log, self.count) w.watching(self.INTERVAL)
def do(task): watcher = Watcher() try: return watcher.watch(task) except: traceback.print_exc(file=sys.stderr) logging.critical('Failed while cleaning for task %s' % (task['ID'])) return False
def main(): print(getpass.getuser()) read_config() testclient = Client("192.168.0.1", 1234, getpass.getuser(), None) # testclient.get_public_key() testclient.dirname = input("Enter directory to monitor: ") w = Watcher(testclient.dirname) w.run()
def __init__(self, name, API_ID, API_HASH): super().__init__(name, API_ID, API_HASH) self.watcher = Watcher() for username, answerCount in api.get_all_data(): self.watcher.add_quora( username, stateInitializer=stateCustomizer(answerCount), update_interval=60, ) self.dispatcher = self.watcher.dispatcher
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(parent=None, title='Fuzzy Eve Notifier', size=(850, 400), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX) self.init_ui() self.Centre() self.Show(True) self.Bind(wx.EVT_CLOSE, self.on_exit) self.watcher = Watcher(self.show_popup) self.watcher.run_monitor()
def main(): parser = argparse.ArgumentParser() parser.add_argument('--address', default=krpc.DEFAULT_ADDRESS) parser.add_argument('--rpc-port', type=int, default=krpc.DEFAULT_RPC_PORT) parser.add_argument('--stream-port', type=int, default=krpc.DEFAULT_STREAM_PORT) parser.add_argument('--client-name', default='Program') parser.add_argument('--debug', action='store_true') parser.add_argument('--quicksave', action='store_true') parser.add_argument('--quickload', action='store_true') parser.add_argument('--no-autodecouple', action='store_true') parser.add_argument('program') args = parser.parse_args() if args.debug: log_level = logging.DEBUG else: log_level = logging.INFO logging.basicConfig(level=log_level) conn = krpc.connect(name=args.client_name, address=args.address, rpc_port=args.rpc_port, stream_port=args.stream_port) log.info('Connected to %s', args.address) if args.quickload: log.info('Loading quicksave as requested') conn.space_center.quickload() vessel = conn.space_center.active_vessel watcher_thread = Watcher(conn, vessel) watcher_thread.start() program = eval('[{}]'.format(args.program), {}, ProgramLocals(conn, vessel, watcher_thread)) program = [init_stage(stage) for stage in program] log.info('Program: %s', program) for stage in program: log.info('Executing stage %s', stage) watcher_thread.autodecouple = stage.autodecouple and not args.no_autodecouple stage() if args.quicksave: log.info('Quicksaving as requested') conn.space_center.quicksave() log.info('Program complete')
def main(): config = args.parse() say_hello() print('cli arguments as understood:\n') pprint(config, indent=2) print('\n\n') # dry run if config['dry'] is True: dry_run(config['dry_opts']) # real run elif len(config['watchers']): YOUTUBE_FILENAME_PATTERN = "(.*\\/)?([a-zA-Z0-9\\_\\-]{10,})\\.(mp3|m4a)$" watcher = Watcher() for watcher_config in config['watchers']: rc_json = get_configuration_from_file(watcher_config['rc_filename']) on_event = ConditionalFileEventHandler( both(is_moved_event, partial(filename_matches, YOUTUBE_FILENAME_PATTERN)), partial(on_youtube_music_file, rc_json=rc_json, watcher_config=watcher_config) ) watcher.schedule(on_event, watcher_config['watch'], recursive=config['recursive']) watcher.start() try: while True: time.sleep(1) except KeyboardInterrupt: if watcher is not None: watcher.stop() # inconsistent state else: raise ValueError('ValueError: Program should be run with either the --dry flag or with some --watch and --out values')
class Server(SmartServer): watcher = roproperty("_watcher") web_server = roproperty("_web_server") def prepare(self): self._watcher = Watcher() self._watcher.start() self._web_server = WebServer() self._web_server.start() def work(self): profiler.autosave()
def run_watcher(): try: get_libc() watcher = Watcher() watcher.run() except CodedError as err: send_error(err.code, err.message) except OSError as err: logging.warning(err) send_error(process_error(err.errno), err.strerror) except BaseException as err: logging.warning(err) if hasattr(err, '__traceback__'): logging.warning(''.join(traceback.format_tb(err.__traceback__))) send_error(Error.EINVAL, str(err) + '\n' + traceback.format_exc())
def __init__(self, path): self.path = path self.queue = Queue.PriorityQueue() self.watcher = Watcher(path, self.queue) self.walker = Walker(path, self.queue, Settings.is_rescan_forced()) self.reader = Reader(self.queue) self.validator = Validator(self.queue)
def __init__(self): self.sciezka = os.path.expanduser('~') + '\szyfrBox' self.drzewo = DrzewoPlikow(self.sciezka) self.funkcjeWeb = {} self.straznik = Watcher(self.sciezka, self.AktualizujDrzewo) threading.Thread(target=self.straznik.start).start( ) # wątek obserwujacy katalog lokalny
def inserirDadosBD(): try: conexao = sqlite3.connect("emailUsuario.sqlite3") consulta = conexao.cursor() sql = "CREATE TABLE IF NOT EXISTS email(emRemetente VARCHAR(50) NOT NULL, emDestinatario VARCHAR(50) NOT NULL)" limpatela() print(nome) emRemetente = input("\n [+] Seu e-mail: ").lower() verif = validarEmail(emRemetente) emRemetente = bs64(verif) emDestinatario = input(" [+] E-mail destinatário: ").lower() verif = validarEmail(emDestinatario) emDestinatario = bs64(verif) if consulta.execute(sql): pass argumentos = (emRemetente, emDestinatario) sql = """INSERT INTO email(emRemetente, emDestinatario)VALUES (?, ?)""" if consulta.execute(sql, argumentos): conexao.commit() print("\n [!] Dados inseridos com sucesso!") time.sleep(2) consulta.close() conexao.close() except Exception as erro: print("\n [x] Um erro ocorreu, consulte o log.") Watcher.LOG(" inserirDadosBD ", erro) time.sleep(2) return False
def __init__(self, parent, rdonly): self._parent = parent self._rdonly = rdonly self._watcher = None if not self._rdonly: from watcher import Watcher self._watcher = Watcher()
def __init__(self): super().__init__() self.__windowTitle = "Firepost VA" self.__defaultSize = QtCore.QSize(1080, 720) self.thumbnailDisplay = ThumbnailDisplay() self.detailDisplay = DetailDisplay() self.controlPanel = ControlPanel() self.handler = Handler() self.watcher = Watcher(["./stream_0"], self.handler) # connect handler to thumbnail display self.handler.tx_sendpathtime.connect(self.watcher.SendImage) self.watcher.sendImage.connect(self.thumbnailDisplay.rx_put_thumbnail) self.setup_mainWidget() # connect handler to detail display self.handler.tx_sendpathtime.connect( self.detailDisplay.rx_write_details) # connect controlPanel button to watcher self.controlPanel.toggle_monitor_button.clicked.connect( self.watcher.rxToggleObserver) # this should be the last step self.setup_dashboard()
def __init__( self, frame, iconf ) : super().__init__() self.args = Args.args self.POLL_INTERVAL = 2000 # in msec self.frame = frame self.watcher = Watcher( self.args.last_replay ) # # now wx stuff # self.set_icon( iconf ) self.add_username = None # pointer to add_username check menu, for ease of access. self.add_faction = None # pointer to add_faction check menu, for ease of access. self.add_vs_info = None # pointer to add_vs_info check menu, for ease of access. # timer for polling for replay change self.timer = wx.Timer( self ) self.timer.Start( self.POLL_INTERVAL ) # event bindings self.Bind( wx.adv.EVT_TASKBAR_LEFT_DCLICK, self.on_left_dclick ) # might show replay manager in the future, but not now. self.Bind( wx.EVT_TIMER, self.on_timer, self.timer )
def create_watcher(): web3 = Web3( HTTPProvider(endpoint_uri=config.ETH_RPC_URL, request_kwargs={"timeout": config.ETH_RPC_TIMEOUT})) web3.middleware_onion.inject(geth_poa_middleware, layer=0) Session = sessionmaker(bind=db_engine) session = Session() mining_round = session.query(MiningRound).filter( MiningRound.round == MINING_ROUND).one() session.rollback() share_token_tracer = ERC20Tracer(config.XIA_SHARE_TOKEN_ADDRESS, web3, mining_round.end_block_number) position_tracer = PositionTracer(config.ETH_PERPETUAL_ADDRESS, config.ETH_PERPETUAL_INVERSE, config.ETH_PERPETUAL_POSITION_TOPIC, web3, mining_round.end_block_number) miner = ShareMining(mining_round.begin_block_number, mining_round.end_block_number, mining_round.release_per_block, MINING_ROUND) mature_checker = MatureChecker(config.MATURE_CONFIRM, config.MATURE_CHECKPOINT_INTERVAL, MINING_ROUND) syncers = [share_token_tracer, position_tracer, miner, mature_checker] return Watcher(mining_round.watcher_id, syncers, web3, db_engine, mining_round.end_block_number)
def multi_watch(args): gens = [] config = configparser.ConfigParser() watch_path = os.environ.get('WATCHPIG') if watch_path is None: print("WATCHPIG未提供") return config.read(watch_path) paint(u"程序启动::FOREGROUND::celeste|| ::EMOJI::pig|| start...") for name in config.sections(): paint( u'项目名称::FOREGROUND::celeste|| %s::FOREGROUND::yellow|| watching ...' % name) watch_dict = {} for key, value in config[name].items(): watch_dict[key] = value excludes = watch_dict['excludes'].split('|') if watch_dict.get( 'excludes') else None gen = Watcher(watch_dict['path'], excludes=excludes, project=name).auto_reload(watch_dict['action']) gens.append(gen) while True: for g in gens: next(g) time.sleep(1)
def __init__(self, args): self.config = { 'ircdir': args[1], 'server': args[2], 'nick': args[3], 'channels': args[4].split(' '), 'workdir': os.path.dirname(os.path.abspath(__file__)), } self.database = None self._modulesPath = None self._modulesList = [] self._triggers = [] self._replies = [] try: print "[*] Starting core" self._initDatabase() self._initModules() self._controller = Controller(self) self._watcher = Watcher(self.config['ircdir'], self._callback, ['out']) except: e = sys.exc_info() print "[!] Uncaught exception: %s - %s" % (e[0], e[1]) sys.exit(1)
def main(args): from sys import stderr from sys import exit # print(args) try: if args['--remote']: with Watcher() as w: w.watch(remote=True) else: with Watcher() as w: w.watch(remote=False) except Exception as e: print(e, file=stderr) exit(1)
def __init__(self, bot): self.bot = bot self.erepublik = ErAPI() self.watcher = Watcher() # Requires bot for automatic messages self.events = Events(bot) self.serversocket = ServerSocket(bot)
def on_set_last_replay( self, event ) : self.args.set_last_replay() # invoke open dialog self.timer.Stop() self.watcher.last_replay = self.args.last_replay # and pass the information to watcher. self.watcher = Watcher( self.args.last_replay ) # re-init watcher to prevent bug. # If you switch games or change last repaly, the watcher thinks the # replay has changed! In a sense, it is correct but it's not the time to sample the replay. self.timer.Start()
def __init__(self, serial, name): self._serial = serial self.name = name if self._serial != None and self._serial != '': self._device = Device(self._serial) self._watcher = Watcher(self._device) else: self._device = None self._watcher = None
def start(self): print(f'Loading {self.get_latest_log()}') print('Your presence is working!') def change(): self.parse_all() self.update_state() watcher = Watcher(self.get_latest_log(), change) while True: if (self.shutdown): self.presence.close() print('Waiting for game to be played..') break watcher.look() sleep(1)
def main(): try: # Get pods ip address ipaddr = socket.gethostbyname(socket.gethostname()) print('main: POD IP {}'.format(ipaddr)) config.load_incluster_config() kube = KubeHandler() mongo = MongoHandler(kube) members = Members(mongo.db) mongo.setMembers(members) watcher = Watcher(kube, mongo, members, ipaddr) watcher.Start() except KeyboardInterrupt: pass except Exception as error: print('main: ERROR - {}'.format(error)) finally: print("main: SHUTDOWN") sys.exit(0)
def __init__(self, args: list, **kwargs): logging.config.dictConfig(config.LOG_CONFIG) self.keeper_account = None self.keeper_account_key = "" self.web3 = Web3(HTTPProvider(endpoint_uri=config.ETH_RPC_URL)) self.web3.middleware_onion.inject(geth_poa_middleware, layer=0) self.gas_price = self.web3.toWei(10, "gwei") # contract self.perp = Perpetual(web3=self.web3, address=Address(config.PERP_ADDRESS)) self.token = ERC20Token(web3=self.web3, address=Address(config.COLLATERAL_TOKEN)) self.AMM = AMM(web3=self.web3, address=Address(config.AMM_ADDRESS)) self.fund = Fund(web3=self.web3, address=Address(config.FUND_ADDRESS)) # mcdex for orderbook self.mcdex = Mcdex(config.MCDEX_URL, config.MARKET_ID) # watcher self.watcher = Watcher(self.web3)
def main(): # Setup Logging logger = logging.getLogger('twitterbox') hdlr = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s %(module)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) queue = Queue.PriorityQueue() watcher = None loops = 0 while True: try: loops = loops + 1 logger.debug("Main Loop " + str(loops)) # Make sure our twitter thread is alive and happy if not watcher or not watcher.is_alive(): logger.info("Starting watcher thread") watcher = Watcher(queue, logger) watcher.setDaemon(True) watcher.start() # Dump the queue for m in range(queue.qsize()): msg = queue.get() priority = msg[0] line1 = msg[1] line2 = msg[2] alert = msg[3] logger.info(line1 + " " + line2) queue.task_done() except Exception as e: logger.error("Exception in main thread: " + str(e)) traceback.print_tb(sys.exc_info()[2]) time.sleep(15) logger.warn("Exiting main thread")
def createNew(self, fileName, scriptName, importDirs, author, lic, copyRight, description, creationDate, version, email): " Creates a new project " # Try to create the user project directory projectUuid = str(uuid.uuid1()) userProjectDir = settingsDir + projectUuid + sep if not os.path.exists(userProjectDir): try: os.mkdir(userProjectDir) except: logging.error("Cannot create user project directory: " + self.userProjectDir + ". Please check the " "available disk space and re-create the " "project.") raise else: logging.warning("The user project directory existed! " "The content will be overwritten.") self.__removeProjectFiles(userProjectDir) # Basic pre-requisites are met. We can reset the current project self.__resetValues() self.fileName = str(fileName) self.importDirs = importDirs self.scriptName = scriptName self.creationDate = creationDate self.author = author self.license = lic self.copyright = copyRight self.version = version self.email = email self.description = description self.uuid = projectUuid self.userProjectDir = userProjectDir self.__createProjectFile() # ~/.codimension/uuidNN/project self.__generateFilesList() self.saveProject() # Update the watcher self.__dirWatcher = Watcher(Settings().projectFilesFilters, self.getProjectDir()) self.__dirWatcher.fsChanged.connect(self.onFSChanged) self.__createRopeProject() self.projectChanged.emit(self.CompleteProject) return
def do_run_jtr_single_mode(pJTR: JohnTheRipper) -> None: lCrackingMode = "John the Ripper (JTR) Single Crack" lWatcher = Watcher(pCrackingMode=lCrackingMode, pJTR=pJTR) lWatcher.start_timer() lWatcher.print_mode_start_message() pJTR.run_single_crack() lWatcher.stop_timer() lWatcher.print_mode_finsihed_message() gReporter.appendRecord( pMode=lCrackingMode, pMask="", pWordlist="", pRule="", pNumberPasswordsCracked=lWatcher.number_passwords_cracked_by_this_mode, pNumberPasswordsCrackedPerSecond=lWatcher. number_passwords_cracked_by_this_mode_per_second, pPercentPasswordsCracked=lWatcher. percent_passwords_cracked_by_this_mode)
def sync_extradata(extra_data: str, end_block_number: int, watcher_id: int, share_tokens: List[str]): logger = logging.getLogger() logger.info( f'start sync extra_data:{extra_data}, end_block_number:{end_block_number}, watcher_id:{watcher_id}, share_token:{",".join(share_tokens)}' ) web3 = Web3( HTTPProvider(endpoint_uri=config.ETH_RPC_URL, request_kwargs={"timeout": config.ETH_RPC_TIMEOUT})) web3.middleware_onion.inject(geth_poa_middleware, layer=0) syncers = [] for share_token in share_tokens: share_token_tracer = ERC20Tracer(share_token, web3, end_block_number) syncers.append(share_token_tracer) watcher = Watcher(watcher_id, syncers, web3, db_engine, end_block_number) while True: synced = watcher.sync() if synced < 0: time.sleep(config.WATCHER_CHECK_INTERVAL) elif synced == 0: return
def _start_watchers(self, live_streamers_list): for live_streamer in live_streamers_list: if live_streamer not in self.watched_streamers: live_streamer_dict = self.streamers.pop(live_streamer) curr_watcher = Watcher(live_streamer_dict, self.download_folder) self.watched_streamers.update({ live_streamer: { 'watcher': curr_watcher, 'streamer_dict': live_streamer_dict } }) if not self.kill: t = self.pool.submit(curr_watcher.watch) t.add_done_callback(self._watcher_callback)
def check_format( self ) : fmt = self.text_ctrl_format.GetValue() t = datetime.datetime.now() try : txt = t.strftime( fmt ) except ValueError : wx.MessageBox( "Invalid date time format!", "Error", style=wx.ICON_ERROR ) return None if txt != Watcher.sanitize_name( txt ) : msg = "File name must not contain the following:\n" msg += "<>:\"/\\|?*" wx.MessageBox( msg, "Error", style=wx.ICON_ERROR ) return None return txt
def main(): args = arguments() numeric_level = getattr(logging, args.log_level.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % args.log_level) # Get commands logger.setLevel(numeric_level) if args.log_file != "": fh = logging.FileHandler(args.log_file) fh.setLevel(numeric_level) fh.setFormatter(formatter) logger.addHandler(fh) jobid = args.jobid job = None if args.submit: try: jobin = jobid jobid = check_output(args.qsub_cmd + [jobid]) jobid = jobid.strip().split(".")[0] logger.info("Submitted %s, got id %s" % (jobin, jobid)) except Exception: logger.error("Failed to submit %s" % jobin) logger.error("Bailing out.") raise pb_token = args.pb_token sleep_time = args.poll_interval events = args.notify_on lowmem = args.kill_threshold try: # Create the job object job = Watcher(jobid, args.qstat_cmd, args.qdel_cmd, args.showstart_cmd, events, lowmem=lowmem) # Set a notifier for it if pb_token: job.set_notifier(pb_token, args.listener_name) while not job.finished: job.update() if not job.finished: logger.debug("Sleeping for %ds" % sleep_time) sleep(sleep_time) else: logger.debug("Job finished. Exiting.") break except Exception: raise finally: if job: job.remove_notifier()
def main(): prs = argparse.ArgumentParser(description='Generate the website anew.') prs.add_argument('-c', '--conf', type=str, default="example_configuration.yml", dest='conf_path', help='Path to the configuration file.') args = prs.parse_args() conf = yaml.load(open(args.conf_path, 'r').read()) task_manager = pst.Tasker(conf) watcher = Watcher(task_manager) watcher.start() try: while True: time.sleep(1) except KeyboardInterrupt: watcher.stop() watcher.join()
def main(): parser = ArgumentParser() parser.add_argument('--type', help='Start me as etcd watcher or commiter', choices=['watcher', 'commiter', 'mrproper'], required=True) parser.add_argument('--test', help='Select the test', choices=['ab-incrementor'], required=True) parser.add_argument('--host', help='IP address of machine with the etcd', default='127.0.0.1') parser.add_argument('--port', type=int, help='Peer port to connect to etcd', default=2379) args = parser.parse_args() etcd_client = etcd3.client(host=args.host, port=args.port) if args.type == 'watcher': watch_client = Watcher( etcd_client, create_test(etcd_client, ClientType.WATCHER, args.test)) watch_client.start_watcher() watch_client.run() elif args.type == 'commiter': data_provider = create_test(etcd_client, ClientType.COMMITER, args.test) data_provider.run() else: etcd_client.delete_prefix('/') print('done')
class Scanner: def __init__(self, path): self.path = path self.queue = Queue.PriorityQueue() self.watcher = Watcher(path, self.queue) self.walker = Walker(path, self.queue, Settings.is_rescan_forced()) self.reader = Reader(self.queue) self.validator = Validator(self.queue) def start(self): self.validator.start() self.watcher.start() self.walker.start() self.reader.start() def stop(self): self.watcher.stop() self.reader.stop() self.validator.join() self.walker.join() self.watcher.join() self.reader.join()
class TestWatcher(unittest.TestCase): def setUp(self): self.w = Watcher('', os.path.dirname( os.path.realpath(__file__)) + '/test/') self.w.savefile = '/test/test_watched.json' self.w.watched = [] self.w.save() def tearDown(self): try: os.remove(os.path.dirname( os.path.realpath(__file__)) + self.w.savefile) except FileNotFoundError: pass def test_find(self): w = self.w w.matches = w.find('') self.assertEqual(w.matches[0], 'test.jpg') def test_clear(self): self.w.watched.append('test.jpg') self.w.watched.append('keep.jpg') self.w.clear('te') assert 'keep.jpg' in self.w.watched assert 'test.jpg' not in self.w.watched self.w.watched.append('test2.jpg') self.w.clear('.') self.assertFalse(self.w.watched) def test_nosave(self): self.w.nosave = True self.w.watched.append('test') self.w.save() assert not self.w.load() def test_remove(self): shutil.copy(self.w.folder + '/test.jpg', self.w.folder + '/remove') self.w.watched.append('remove') self.w.watched.append('testdir/') self.w.remove() assert not os.path.isfile(self.w.folder + '/remove') def test_ignore(self): self.w.watched.append('test.jpg') assert self.w.find('', include_watched=True)
def main(): # Setup Logging logger = logging.getLogger('twitterbox') hdlr = logging.FileHandler(settings.LOG) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) hdlr = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) if settings.DEBUG: logger.setLevel(logging.DEBUG) logger.info("DEBUG level logging") else: logger.setLevel(logging.INFO) logger.info("INFO level logging") logger.info("Starting up...") if PI: # Not interested #GPIO.setwarnings(False) # Setup the LCD display GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers # Setup the alert light if settings.LIGHT_PIN_1: GPIO.setup(settings.LIGHT_PIN_1, GPIO.OUT) GPIO.output(settings.LIGHT_PIN_1, GPIO.LOW) if settings.LIGHT_PIN_2: GPIO.setup(settings.LIGHT_PIN_2, GPIO.OUT) GPIO.output(settings.LIGHT_PIN_2, GPIO.LOW) # The queue is where messages go to be displayed queue = Queue.PriorityQueue() watcher = None printer = None server = None loops = 0 while True: try: loops = loops + 1 logger.debug("Main Loop " + str(loops)) # Make sure our twitter thread is alive and happy if not watcher or not watcher.is_alive(): logger.info("Starting watcher thread") watcher = Watcher(queue, logger) watcher.setDaemon(True) watcher.start() # Make sure our printing thread is alive and happy if not printer or not printer.is_alive(): logger.info("Starting printer thread") printer = Printer(queue, logger, PI) printer.setDaemon(True) printer.start() if settings.HTTP_SERVER: if not server or not server.is_alive(): logger.info("Starting HTTP server") server = Server(queue, logger) server.setDaemon(True) server.start() # Throw some info in the queue if it's getting low if queue.qsize() < 1: messages = open(settings.MSG_FILE, 'r') for msg in messages: queue.put((settings.PRIORITY_LOW, msg, "", False)) messages.close() if settings.SLIDE_DIR: for filename in os.listdir(settings.SLIDE_DIR): queue.put((settings.PRIORITY_LOW, os.path.join(settings.SLIDE_DIR, filename), SLIDE, False)) except Exception as e: logger.exception("Exception in main thread: " + str(e)) time.sleep(15) logger.warn("Exiting main thread")
def setUp(self): self.w = Watcher('', os.path.dirname( os.path.realpath(__file__)) + '/test/') self.w.savefile = '/test/test_watched.json' self.w.watched = [] self.w.save()
def main(): # Setup Logging logger = logging.getLogger('twitterbox') hdlr = logging.FileHandler(settings.LOG) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) hdlr = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) if settings.DEBUG: logger.setLevel(logging.DEBUG) logger.info("DEBUG level logging") else: logger.setLevel(logging.INFO) logger.info("INFO level logging") logger.info("Starting up...") if PI: # Not interested GPIO.setwarnings(False) # Setup the LCD display GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers # Setup the alert light GPIO.setup(settings.LIGHT_PIN, GPIO.OUT) GPIO.output(settings.LIGHT_PIN, GPIO.LOW) # The queue is where messages go to be displayed queue = Queue.PriorityQueue() watcher = None printer = None loops = 0 while True: try: loops = loops + 1 logger.debug("Main Loop " + str(loops)) # Make sure our twitter thread is alive and happy if not watcher or not watcher.is_alive(): logger.info("Starting watcher thread") watcher = Watcher(queue, logger) watcher.setDaemon(True) watcher.start() # Make sure our printing thread is alive and happy if not printer or not printer.is_alive(): logger.info("Starting printer thread") printer = Printer(queue, logger, PI) printer.setDaemon(True) printer.start() # Throw some info in the queue if it's getting low if queue.qsize() == 0: messages = open(settings.MSG_FILE, 'r') for msg in messages: queue.put((settings.PRIORITY_LOW, msg, "", False)) messages.close() # Switching to using the message file instead of this generated msg #for w in settings.TRACK: # queue.put((settings.PRIORITY_LOW, "Watching for:", w, False)) # We are not tracking the number of followers for this event # This frees up an extra twitter connection to avoid rate limiting --JLS # user_data = watcher.getUserData() # if user_data != None: # for k,v in user_data.iteritems(): # queue.put((PRIORITY_LOW, k, v, False)) except Exception as e: logger.error("Exception in main thread: " + str(e)) traceback.print_tb(sys.exc_info()[2]) time.sleep(15) logger.warn("Exiting main thread")
def prepare(self): self._watcher = Watcher() self._watcher.start() self._web_server = WebServer() self._web_server.start()
class ClientDaemon: def __init__(self): self.init_home_dir() self.api = "https://andrefreitas.pt/budibox/api/" self.login = LoginBox() self.watcher = Watcher(self.budibox_home) def init_home_dir(self): # Searchs for user home folder and creates budibox folder self.budibox_home = expanduser("~") + "/budibox" self.home = expanduser("~") self.budibox_home = self.budibox_home.decode(system_enconding) # Creates budibox folder if not os.path.exists(self.budibox_home): os.makedirs(self.budibox_home) def client_start(self): self.login.start() self.computerId = self.get_computer_id() watcher_thread = Thread(target=self.listen_watcher, args=()) requests_thread = Thread(target=self.listen_requests, args=()) keep_alive = Thread(target=self.keep_alive, args=()) sync = Thread(target=self.sync, args=()) # Start threads watcher_thread.start() requests_thread.start() keep_alive.start() sync.start() # Join threads watcher_thread.join() requests_thread.join() keep_alive.join() sync.join() def get_computer_id(self): url = self.api + "computers/getComputerId.php" values = {"apikey": "12", "user": login_box.client.get_email(), "computer": get_computer_name()} response = json_request(url, values) print_message("Getting the computer ID") if response["result"] == "ok": return response["computerId"] def sync(self): while True: url = self.api + "files/getUserFiles.php" values = {"apikey": "12", "user": login_box.client.get_email()} response = json_request(url, values) if response["result"] != "ok": print_message("Error trying to get user files of " + login_box.client.get_email()) else: print_message("Total files: " + str(len(response["files"]))) self.restore_file(response["files"]) time.sleep(sync_files_interval) def restore_file(self, files): list_dir = os.listdir(self.budibox_home) global restore_requests for file in files: file_path = file["path"] if os.path.isfile(self.budibox_home + file_path): if file["status"] == "deleted": os.remove(self.budibox_home + file_path) break timestamp = int(file["date_modified"]["sec"]) datetime_request = datetime.fromtimestamp(timestamp) datetime_local_file = datetime.fromtimestamp(os.path.getmtime(self.budibox_home + file_path)) difference_times = ( time.mktime(datetime_request.timetuple()) - time.mktime(datetime_local_file.timetuple()) - 3600 ) if difference_times > 0: if not (file_path in restore_requests): print_message("More recent " + file_path) url = self.api + "files/restoreFile.php" values = {"apikey": "12", "computerId": self.computerId, "modification": file["modification"]} response = json_request(url, values) if response["result"] == "ok": print_message("Sent request of restore file of " + file_path) restore_requests[file_path] = False else: print_message("Error sending request of restore file of " + file_path) else: print "older or equal" else: if not (file_path in restore_requests) and file["status"] != "deleted": url = self.api + "files/restoreFile.php" values = {"apikey": "12", "computerId": self.computerId, "modification": file["modification"]} response = json_request(url, values) restore_requests[file_path] = False if response["result"] == "ok": print_message("Sent request of restore file of " + file_path) else: print_message("Error sending request of restore file of " + file_path) def keep_alive(self): while True: url = self.api + "computers/keepAlive.php" values = {"apikey": "12", "computerId": self.computerId} response = json_request(url, values) if response["result"] != "ok": print_message("Error sending message of keepAlive of computerId " + self.computerId) time.sleep(10) def listen_watcher(self): self.watcher.start(login_box.client, self.computerId) def listen_requests(self): while True: url = self.api + "requests/getComputerRequests.php" values = {"apikey": "12", "computerId": self.computerId} response = json_request(url, values) if response["result"] == "ok": total_requests = len(response["requests"]) print_message("Requests: " + str(total_requests)) if total_requests > 0: self.handle_request(response["requests"]) time.sleep(listen_requests_interval) def handle_request(self, requests): for request in requests: if request["action"] == "storeChunk": self.store_chunk(request["chunkNumber"], request["modification"], request["fileId"]) if request["action"] == "deleteFile": self.delete_chunks(request["modification"]) if request["action"] == "giveChunk": if os.path.exists( self.budibox_home + "/chunks/" + request["modification"] + "_" + str(request["chunkNumber"]) + ".chunk" ): self.send_chunk_to_restore(request["modification"], request["chunkNumber"], request["owner"]) if request["action"] == "recoverChunk": self.store_temp_chunk(request["modification"], request["number"], request["path"]) def store_temp_chunk(self, modification, number, path): temp_dir = self.home + "/chunks_restore/temp/" if not os.path.exists(temp_dir): os.makedirs(temp_dir) # Creates chunk temp_dir = temp_dir.decode(system_enconding) chunk = open(temp_dir + modification + "_" + str(number) + ".chunk", "w") # Gets chunk body url = self.api + "chunks/getRecover.php" values = {"apikey": "12", "owner": self.computerId, "number": str(number), "modification": modification} response = json_request(url, values) if response["result"] == "ok": chunk_body = response["chunk"] chunk.write(chunk_body) chunk.close() print_message("Chunk of " + modification + " and number " + str(number) + " writed!") else: chunk.close() print_message("Error getting chunk of " + modification + " and number " + str(number) + " writed!") # Delete chunk recover url = self.api + "chunks/deleteChunkRecover.php" values = {"apikey": "12", "owner": self.computerId, "modification": modification, "number": str(number)} response = json_request(url, values) if response["result"] == "ok": print_message("Deleted chunk recover !") else: print_message("Error deleting chunk recover!") return # Confirm chunk recover url = self.api + "requests/confirmRecoverChunk.php" values = { "apikey": "12", "computerId": self.computerId, "modification": modification, "chunkNumber": str(number), } response = json_request(url, values) if response["result"] == "ok": print_message("Confirmed chunk recover !") else: print_message("Error confirming chunk recover!") return # Checks if received all chunks url = self.api + "files/restoreFileIsDone.php" values = {"apikey": "12", "computerId": self.computerId, "modification": modification} response = json_request(url, values) if response["result"] == "ok": if response["isDone"] == True: print_message("Restore file " + path + " is done!") f = File(self.budibox_home + path, login_box.client, modification) f.restore_file(temp_dir, self.budibox_home + path) global restore_requests del restore_requests[path] print "Feito" def send_chunk_to_restore(self, modification, number, owner): path = self.budibox_home + "/chunks/" + modification + "_" + str(number) + ".chunk" chunk = open(path, "rb") chunk_body = chunk.read() url = self.api + "chunks/giveForRestore.php" values = { "apikey": "12", "modification": modification, "number": str(number), "body": chunk_body, "owner": owner["$id"], } response = json_post_request(url, values) if response["result"] == "ok": print_message("Sent chunk for restore of " + path) else: print_message("Error sending chunk for restore of " + path) def delete_chunks(self, modification): list_dir = os.listdir(self.budibox_home + "/chunks/") for file in list_dir: if file.startswith(modification): f = open(self.budibox_home + "/chunks/" + file, "rb") file_size = len(f.read()) f.close() os.remove(self.budibox_home + "/chunks/" + file) url = self.api + "users/incOfferUsage.php" values = {"apikey": "12", "user": login_box.client.get_email(), "value": str(-file_size)} response = json_request(url, values) if response["result"] == "ok": print_message("Decremented offer_usage in " + str(file_size)) else: print_message("Error decrementing offer_usage in " + str(file_size)) url = self.api + "requests/confirmFileDelete.php" values = {"apikey": "12", "computerId": self.computerId, "modification": modification} response = json_request(url, values) if response["result"] == "ok": print_message("Sent confirm delete message of modification: " + modification) else: print_message("Error confirm delete message of modification: " + modification) def store_chunk(self, chunkNumber, modification, fileId): # Gets Information about chunk to Store url = self.api + "chunks/get.php" values = {"apikey": "12", "fileId": fileId["$id"], "modification": modification, "number": str(chunkNumber)} response = json_request(url, values) if response["result"] == "ok": chunk_body = response["chunk"] else: print_message( "Error trying to get chunk body of fileID " + fileId["$id"] + "and chunkNumber " + str(chunkNumber) ) return False print_message( "Processing request, getting chunk body of " + fileId["$id"] + " and chunkNumber " + str(chunkNumber) ) if not os.path.exists(self.budibox_home + "/chunks/"): os.makedirs(self.budibox_home + "/chunks/") chunk_file = open(self.budibox_home + "/chunks/" + modification + "_" + str(chunkNumber) + ".chunk", "wb") chunk_file.write(chunk_body) chunk_file.close() # Sends confirmStorage message url = self.api + "chunks/confirmStorage.php" values = { "apikey": "12", "fileId": fileId["$id"], "computerId": self.computerId, "number": str(chunkNumber), "modification": modification, } response = json_request(url, values) if response["result"] == "ok": print_message( "Sent confirmation message: fileId " + fileId["$id"] + " and chunkNumber " + str(chunkNumber) + " and computerId " + self.computerId ) # Adds space of the offer_used url = self.api + "users/incOfferUsage.php" values = {"apikey": "12", "user": login_box.client.get_email(), "value": str(len(chunk_body))} response_space = json_request(url, values) if response_space["result"] == "ok": print_message("Increment offer usage successfully with " + str(len(chunk_body))) return True else: print_message("Error in incrementing offer usage with " + str(len(chunk_body))) return False else: print_message( "Error trying to send confirm message: fileId " + fileId["$id"] + " and chunkNumber " + str(chunkNumber) + " and computerId " + self.computerId ) return False
class Temp(object): def __init__(self, parent, rdonly): self._parent = parent self._rdonly = rdonly self._watcher = None if not self._rdonly: from watcher import Watcher self._watcher = Watcher() def _get_name(self, name): ret = '' length = len(name) for i in range(length): if name[i] == '/': ret += '_' else: ret += name[i] return ret def _get_dir(self, uid, field): path = get_var_path(uid) return os.path.join(path, TEMP, FIELDS[field]) def _check_dir(self, uid, field): path = self._get_dir(uid, field) if not os.path.exists(path): os.makedirs(path, DIR_MODE) return path def _check_path(self, uid, name): name = self._get_name(name) dirname = self._check_dir(uid, self._parent.field) return self._get_path(dirname, name) def _get_path(self, dirname, name, suffix=''): path = os.path.join(dirname, name) if suffix: path += '.' + suffix return path def get_path(self, uid, name, suffix=''): name = self._get_name(name) dirname = self._get_dir(uid, self._parent.field) return self._get_path(dirname, name, suffix) def mtime(self, uid, name): path = self.get_path(uid, name, 'mtime') try: with open(path, 'r') as f: t = long(f.read().strip()) return t except: return 0 def set_mtime(self, uid, name, t): path = self.get_path(uid, name, 'mtime') with open(path, 'w') as f: f.write(str(t)) def create(self, uid, name): path = self._check_path(uid, name) ret = os.open(path, os.O_RDWR | os.O_CREAT, FILE_MODE) if ret >= 0 and self._watcher: self._watcher.push(path) return ret def truncate(self, uid, name, length): path = self.get_path(uid, name) with open(path, 'r+') as f: f.truncate(length) def open(self, uid, name, flags): dest = self._check_path(uid, name) src = self._parent.get_path(uid, name) t = self._parent.get_mtime(uid, src) if not t or t != self.mtime(uid, name): self._parent.load(uid, src, dest) if t: self.set_mtime(uid, name, t) flg = os.O_RDWR if flags & os.O_TRUNC: flg |= os.O_TRUNC ret = os.open(dest, flg, FILE_MODE) if ret >= 0 and self._watcher: self._watcher.register(dest) return ret def release(self, uid, name, fh): dirty = False os.close(fh) if not self._rdonly: path = self.get_path(uid, name) if self._watcher and self._watcher.pop(path): dirty = True return dirty def commit(self, uid, name): src = self.get_path(uid, name) if os.path.exists(src): dest = self._parent.get_path(uid, name) self._parent.save(uid, src, dest) def discard(self, uid, name): path = self.get_path(uid, name) if os.path.exists(path): os.remove(path)
from __future__ import with_statement import daemon.pidlockfile from watcher import Watcher import time import logging import sys if __name__ == "__main__": logger = logging.getLogger("watcherd") formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") logger.setLevel(logging.INFO) handler = logging.FileHandler("watcherd.log") handler.setFormatter(formatter) logger.addHandler(handler) hdlrConsole = logging.StreamHandler(sys.stdout) hdlrConsole.setFormatter(formatter) logger.addHandler(hdlrConsole) logger.info("watcherd started") watcher = Watcher(logger) _count = 0 pid = daemon.pidlockfile.TimeoutPIDLockFile("/tmp/watcherd.pid", 10) daemon_context = daemon.DaemonContext(pidfile=pid, files_preserve=[handler.stream]) with daemon_context: while 1: _count+=1 if _count%40 == 0: logger.info(_count) watcher.watch() time.sleep(15)
def stop(self): self.gui = None Watcher.stop(self)
def start(self): self.gui = WatcherGUI(self) Watcher.start(self)
import time from yaml_loader import Loader from ds_client import Client from watcher import Watcher l_conf = Loader('./dsip.yml').conf() app_key, app_secret = l_conf.app_key, l_conf.app_secret camera_url = l_conf.camera_url client = Client(app_key=app_key, app_secret=app_secret) watcher = Watcher(client=client) # TODO: Threading... watcher.watch(camera_url=camera_url, destination='/')
class Bot(object): # def __init__(self, args): self.config = { 'ircdir': args[1], 'server': args[2], 'nick': args[3], 'channels': args[4].split(' '), 'workdir': os.path.dirname(os.path.abspath(__file__)), } self.database = None self._modulesPath = None self._modulesList = [] self._triggers = [] self._replies = [] try: print "[*] Starting core" self._initDatabase() self._initModules() self._controller = Controller(self) self._watcher = Watcher(self.config['ircdir'], self._callback, ['out']) except: e = sys.exc_info() print "[!] Uncaught exception: %s - %s" % (e[0], e[1]) sys.exit(1) # def _initDatabase(self): print "[*] Initializing database.." self.database = Database("%s/%s.db" % (self.config['ircdir'], self.config['server'])) # def _initModules(self): print "[*] Initializing modules.." self._triggers = [] self._modulesPath = "%s/modules" % self.config['workdir'] self._modulesList = pkgutil.iter_modules(path=[self._modulesPath]) for loader, modName, ispkg in self._modulesList: self._loadModule(modName) # def _loadModule(self, modName): if modName not in sys.modules: modTitle = modName.title() print "[*] Loading module %s [%s/%s]" % (modTitle, self._modulesPath, modName) # Import module mod = __import__("modules.%s" % modName, fromlist=[modTitle]) # Get class cls = getattr(mod, modTitle) # Create object obj = cls(self) if not hasattr(obj, 'meta'): print "[!] No meta section in module %s, skipping" % modTitle return if 'triggers' not in obj.meta: print "[!] No triggers in module %s, skipping" % modTitle return if 'usage' not in obj.meta: print "[?] No usage section in module %s, module won't be listed in help" % modTitle for trigger, callback in obj.meta['triggers'].iteritems(): valid = True try: re.compile(trigger) except re.error: valid = False if not valid: print "[!] Trigger %s is not valid regex, skipping" % trigger continue if callable(getattr(obj, callback, None)): print "[*] Callback %s.%s registered trigger %s" % (modTitle, callback, trigger) t = { 'module': modTitle, 'trigger': trigger, 'object': obj, 'callback': callback } self._triggers.append(t) else: print "[!] Callback %s.%s is not callable, skipping" % (modTitle, callback) # def _callback(self, filename, lines): for line in lines: message = Message("%s: %s" % (filename, line.strip())) if message.nick == self.config['nick']: continue self._controller.processMessage(self, message) if message.isValid(): print "[*] Processing message c:%s n:%s m:%s" % (message.channel, message.nick, message.message) for trigger in self._triggers: if re.search(trigger['trigger'], message.message): print "[*] Processing callback %s.%s" % (trigger['module'], trigger['callback']) try: getattr(trigger['object'], trigger['callback'])(self, message) except: e = sys.exc_info() print "[!] Uncaught exception: %s - %s" % (e[0], e[1]) # def addReply(self, channel, message): reply = { 'channel': channel, 'message': message } self._replies.insert(0, reply) # def sendReply(self, reply): outputFile = "%s/%s/%s/in" % (self.config['ircdir'], self.config['server'], reply['channel']) if os.path.exists(outputFile): print "[*] Sending reply %s to %s" % (reply['message'], reply['channel']) with open("%s" % outputFile, "a") as f: f.write("%s\n" % reply['message']) else: print "[!] Output file does not exist: %s" % outputFile # def run(self): print "[*] Starting main loop.." while True: self._watcher.loop(blocking=False) if len(self._replies) > 0: reply = self._replies.pop() self.sendReply(reply) time.sleep(0.1)
def __init__(self): self.init_home_dir() self.api = "https://andrefreitas.pt/budibox/api/" self.login = LoginBox() self.watcher = Watcher(self.budibox_home)
if __name__ == '__main__': camera_id = 0 width = 640 height = 480 try: opts, args = getopt.getopt(sys.argv,"hx:y:o:c:",["width=","height=", "output="]) except getopt.GetoptError: print HELP_MSG sys.exit(2) # Get the specified command line arguments for opt, arg in opts: if opt == '-h': print HELP_MSG sys.exit() elif opt in ('-x', '--width'): width = arg elif opt in ('-y', '--height'): height = arg elif opt in ('-c'): camera_id = arg elif opt in ('-o', '--output'): output_fname = arg # Finally let's start watcher = Watcher(camera_id, show_display=True, width=int(width), height=int(height)) watcher.main_loop() # Main loop. Stops when 'q' is pressed.
import argparse from watcher import Watcher parser = argparse.ArgumentParser(description="Process valid .py file") parser.add_argument('pyfile', metavar='FILE', type=str, help="Path to valid .py file") parser.add_argument("-e", "--exec", type=str, help="Executable", metavar='EXEC') parser.add_argument("-i", "--ignore", nargs='*', type=str, help="Ignored folders and files", metavar='') if __name__ == '__main__': args = parser.parse_args() if args: try: watcher = Watcher(args.pyfile, args.exec, args.ignore) except KeyboardInterrupt: print("Exiting on interrupt") pass
class AutoSaverAppIcon( wx.adv.TaskBarIcon ) : def __init__( self, frame, iconf ) : super().__init__() self.args = Args.args self.POLL_INTERVAL = 2000 # in msec self.frame = frame self.watcher = Watcher( self.args.last_replay ) # # now wx stuff # self.set_icon( iconf ) self.add_username = None # pointer to add_username check menu, for ease of access. self.add_faction = None # pointer to add_faction check menu, for ease of access. self.add_vs_info = None # pointer to add_vs_info check menu, for ease of access. # timer for polling for replay change self.timer = wx.Timer( self ) self.timer.Start( self.POLL_INTERVAL ) # event bindings self.Bind( wx.adv.EVT_TASKBAR_LEFT_DCLICK, self.on_left_dclick ) # might show replay manager in the future, but not now. self.Bind( wx.EVT_TIMER, self.on_timer, self.timer ) def on_timer( self, event ) : if self.watcher.poll() : newf = self.watcher.do_renaming( self.watcher.last_replay, add_username=self.args.add_username, add_faction=self.args.add_faction, add_vs_info=self.args.add_vs_info, custom_date_format=self.args.custom_date_format ) print( "Copied to", newf ) # shown on console! def create_menu_item( self, menu, label, func ) : item = wx.MenuItem(menu, -1, label) menu.Bind(wx.EVT_MENU, func, id=item.GetId()) menu.Append(item) return item def on_add_username( self, event ) : # toggle configuration status # has hidden cfg inside, must use the set function. self.args.set_var( 'add_username', not self.args.add_username ) def on_add_faction( self, event ) : # toggle configuration status # has hidden cfg inside, must use the set function. self.args.set_var( 'add_faction', not self.args.add_faction ) def on_add_vs_info( self, event ) : # toggle configuration status # has hidden cfg inside, must use the set function. self.args.set_var( 'add_vs_info', not self.args.add_vs_info ) # Overridden function def CreatePopupMenu( self ) : menu = wx.Menu() # checkable thingy self.add_username = menu.AppendCheckItem( wx.ID_ANY, 'Add user name', 'Append player names to the replay name' ) self.add_faction = menu.AppendCheckItem( wx.ID_ANY, 'Add factions', 'Append faction information to each player' ) self.add_vs_info = menu.AppendCheckItem( wx.ID_ANY, 'Add [1v1], [2v2] [FFA]', 'Append game type information.' ) # check status should follow the config. # context menu check items DO NOT have internal state!! # we must set checkedness here self.add_username.Check( self.args.add_username ) self.add_faction.Check( self.args.add_faction ) self.add_vs_info.Check( self.args.add_vs_info ) # event binding menu.Bind( wx.EVT_MENU, self.on_add_username, id=self.add_username.GetId() ) menu.Bind( wx.EVT_MENU, self.on_add_faction, id=self.add_faction.GetId() ) menu.Bind( wx.EVT_MENU, self.on_add_vs_info, id=self.add_vs_info.GetId() ) # custom date format self.create_menu_item( menu, 'Customize date time format', self.on_customize_date_format ) # change last replay file self.create_menu_item( menu, 'Change last replay file', self.on_set_last_replay ) # Replay Manager thingy self.create_menu_item( menu, 'Open replay manager', self.on_left_dclick ) # ----------------- menu.AppendSeparator() # exit self.create_menu_item( menu, 'Exit', self.on_exit ) return menu def set_icon( self, iconf ) : #icon = wx.IconFromBitmap( wx.Bitmap( iconf ) ) icon = wx.Icon( iconf, wx.BITMAP_TYPE_ICO ) self.SetIcon( icon, "Kane's Wrath replay auto saver" ) def on_customize_date_format( self, event ) : # parent pointer looks wonky but it works! dfc = DateFormatCustomizer( wx.GetApp().TopWindow, self.args ) result = dfc.ShowModal() if result == wx.ID_OK : fmt = dfc.text_ctrl_format.GetValue() self.args.set_var( 'custom_date_format', fmt ) dfc.Destroy() def open_replay_viewer( self ) : # parent pointer looks wonky but it works! replay_viewer = ReplayViewer( wx.GetApp().TopWindow ) replay_viewer.Show( True ) replay_viewer.Raise() def on_left_dclick( self, event ) : self.open_replay_viewer() def on_set_last_replay( self, event ) : self.args.set_last_replay() # invoke open dialog self.timer.Stop() self.watcher.last_replay = self.args.last_replay # and pass the information to watcher. self.watcher = Watcher( self.args.last_replay ) # re-init watcher to prevent bug. # If you switch games or change last repaly, the watcher thinks the # replay has changed! In a sense, it is correct but it's not the time to sample the replay. self.timer.Start() def on_exit(self, event): try : self.args.save() except : wx.MessageBox( "Failed to save settings to disk.\nPlease check if config.ini can be created/written in the folder where the replay viewer is!", "Warning", wx.OK|wx.ICON_ERROR ) self.Destroy() # self kill self.frame.Destroy() # parent kill
class MainWindow(wx.Frame): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(parent=None, title='Fuzzy Eve Notifier', size=(850, 400), style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX) self.init_ui() self.Centre() self.Show(True) self.Bind(wx.EVT_CLOSE, self.on_exit) self.watcher = Watcher(self.show_popup) self.watcher.run_monitor() def show_popup(self, message): # ShowBalloon is for windows only. If support for other platforms # needed, uncomment popup lines and comment out ShowBalloon line. # popup = wx.adv.NotificationMessage('Feven Intel', message) # popup.Show(timeout=5) self.tb_icon.ShowBalloon('Feven Interl', message, 5000) if self.play_sound_chk.IsChecked(): self.sound.Play(wx.adv.SOUND_ASYNC) def init_ui(self): self.sound = wx.adv.Sound('sound.wav') icon = wx.Icon() icon.CopyFromBitmap(wx.Bitmap("feven.ico", wx.BITMAP_TYPE_ANY)) self.SetIcon(icon) self.tb_icon = wx.adv.TaskBarIcon() self.tb_icon.SetIcon(wx.Icon(wx.Bitmap("feven.ico")), 'Fuzzy Eve Notifier') self.tb_icon.Bind(wx.adv.EVT_TASKBAR_LEFT_DOWN, self.on_left_down) menubar = wx.MenuBar() file_menu = wx.Menu() file_menu_quit = file_menu.Append(wx.ID_EXIT, 'Quit', 'Quit application') # options_menu = wx.Menu() # options_load_preset = options_menu.Append( # 1, 'Load Preset', 'Load Preset') # options_save_preset = options_menu.Append( # 2, 'Save Preset', 'Save Preset') # options_edit_preset = options_menu.Append( # 3, 'Edit Preset', 'Edit Preset') help_menu = wx.Menu() help_about = help_menu.Append(wx.ID_ABOUT, 'About', 'About') menubar.Append(file_menu, '&File') # menubar.Append(options_menu, '&Options') menubar.Append(help_menu, '&Help') self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.on_quit, file_menu_quit) self.Bind(wx.EVT_MENU, self.on_about, help_about) # self.Bind(wx.EVT_MENU, self.on_load_preset, options_load_preset) # self.Bind(wx.EVT_MENU, self.on_save_preset, options_save_preset) # self.Bind(wx.EVT_MENU, self.on_edit_preset, options_edit_preset) panel = wx.Panel(self) hbox = wx.BoxSizer(wx.HORIZONTAL) # Row based layout. # 3 rows with 4 columns, 5xp border horizontally and vertially. # buttons buttons button checkbox # caption caption caption caption # input input input input fgs = wx.FlexGridSizer(3, 4, 5, 5) font12 = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL) # First row. # Create text captions for columns and assign font. directory_caption = wx.StaticText(panel, label="Directory") filename_caption = wx.StaticText(panel, label="Filename") message_caption = wx.StaticText(panel, label="Keyword") ignore_caption = wx.StaticText(panel, label="Ignore Keyword") directory_caption.SetFont(font12) filename_caption.SetFont(font12) message_caption.SetFont(font12) ignore_caption.SetFont(font12) # Second row. # First column. panel_row0_col0 = wx.Panel(panel) sizer_row0_col0 = wx.BoxSizer(wx.HORIZONTAL) self.start_btn = wx.Button(panel_row0_col0, label="Start", size=(90, 28)) # Watcher has been started in __init__, so just disable start button. self.start_btn.Disable() self.stop_btn = wx.Button(panel_row0_col0, label="Stop", size=(90, 28)) self.start_btn.Bind(wx.EVT_BUTTON, self.on_start) self.stop_btn.Bind(wx.EVT_BUTTON, self.on_stop) self.start_btn.SetFont(font12) self.stop_btn.SetFont(font12) sizer_row0_col0.Add(self.start_btn, 0, wx.ALL, 3) sizer_row0_col0.Add(self.stop_btn, 0, wx.ALL, 3) panel_row0_col0.SetSizer(sizer_row0_col0) # Third column. panel_row0_col1 = wx.Panel(panel) sizer_row0_col1 = wx.BoxSizer(wx.HORIZONTAL) apply_btn = wx.Button(panel_row0_col1, label="Apply Changes", size=(130, 28)) apply_btn.Bind(wx.EVT_BUTTON, self.on_apply) apply_btn.SetFont(font12) sizer_row0_col1.Add(apply_btn, 1, wx.ALL, 3) panel_row0_col1.SetSizer(sizer_row0_col1) # Second column. panel_row0_col2 = wx.Panel(panel) sizer_row0_col2 = wx.BoxSizer(wx.HORIZONTAL) load_btn = wx.Button(panel_row0_col2, label="Load", size=(90, 28)) save_btn = wx.Button(panel_row0_col2, label="Save", size=(90, 28)) load_btn.Bind(wx.EVT_BUTTON, self.on_load) save_btn.Bind(wx.EVT_BUTTON, self.on_save) load_btn.SetFont(font12) save_btn.SetFont(font12) sizer_row0_col2.Add(load_btn, 1, wx.ALL, 3) sizer_row0_col2.Add(save_btn, 1, wx.ALL, 3) panel_row0_col2.SetSizer(sizer_row0_col2) # Fourth column. panel_row0_col3 = wx.Panel(panel) sizer_row0_col3 = wx.BoxSizer(wx.HORIZONTAL) self.play_sound_chk = wx.CheckBox(panel_row0_col3, label='Sound', size=(65, 28)) # delay_spin = wx.SpinCtrl(panel_row0_col3, value="5", size=(20, 28)) # delay_label = wx.StaticText(panel_row0_col3, label='Time', # size=(20, 28)) self.play_sound_chk.Bind(wx.EVT_CHECKBOX, self.on_sound_chk) self.play_sound_chk.SetValue(True) # delay_spin.Bind(wx.EVT_SPINCTRL, self.on_spin) self.play_sound_chk.SetFont(font12) # delay_spin.SetFont(font12) # delay_label.SetFont(font12) sizer_row0_col3.Add(self.play_sound_chk, 1, wx.ALL, 3) # sizer_row0_col3.Add(delay_spin, 1, wx.ALL, 3) # sizer_row0_col3.Add(delay_label, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 3) panel_row0_col3.SetSizer(sizer_row0_col3) # Third row. # Create text inputs and assign font. self.directory_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) self.filename_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) self.message_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) self.ignore_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE) self.directory_text.SetFont(font12) self.filename_text.SetFont(font12) self.message_text.SetFont(font12) self.ignore_text.SetFont(font12) # Add captions, buttons, text inputs into grid. fgs.AddMany([ panel_row0_col0, panel_row0_col2, panel_row0_col1, panel_row0_col3, directory_caption, filename_caption, message_caption, ignore_caption, (self.directory_text, 1, wx.EXPAND), (self.filename_text, 1, wx.EXPAND), (self.message_text, 1, wx.EXPAND), (self.ignore_text, 1, wx.EXPAND) ]) # Last row and all columns are growable to fill empty space. fgs.AddGrowableRow(2, 1) # fgs.AddGrowableCol(0, 1) # fgs.AddGrowableCol(1, 1) fgs.AddGrowableCol(2, 1) fgs.AddGrowableCol(3, 1) hbox.Add(fgs, proportion=1, flag=wx.ALL | wx.EXPAND, border=5) panel.SetSizer(hbox) def on_exit(self, e): self.tb_icon.RemoveIcon() self.watcher.stop_monitor() # For unknown reasons MainThread does not stop and process does not # finish. Use explicit exit. sys.exit(0) def on_quit(self, e): self.Close() def on_left_down(self, e): self.Show(True) self.SetFocus() self.Raise() def on_about(self, e): pass def on_load(self, e): openFileDialog = wx.FileDialog(self, "Open Feven file", ".\\presets", "", "Feven files|*.fen", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return with open(openFileDialog.GetPath(), 'r') as file: data = json.load(file) self.directory_text.SetValue(data.get('directories', '')) self.filename_text.SetValue(data.get('files', '')) self.message_text.SetValue(data.get('keywords', '')) self.ignore_text.SetValue(data.get('ignore', '')) self.on_apply(None) def on_save(self, e): saveFileDialog = wx.FileDialog(self, "Save XYZ file", ".\\presets", "", "Feven files|*.fen", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if saveFileDialog.ShowModal() == wx.ID_CANCEL: return with open(saveFileDialog.GetPath(), 'w+') as file: data = { 'directories': self.directory_text.GetValue(), 'files': self.filename_text.GetValue(), 'keywords': self.message_text.GetValue(), 'ignore': self.ignore_text.GetValue() } json.dump(data, file) def on_apply(self, e): paths = self.directory_text.GetValue().strip().split('\n') if not paths: return filenames = self.filename_text.GetValue().strip().split('\n') if not filenames: return keywords = self.message_text.GetValue().strip().split('\n') ignore = self.ignore_text.GetValue().strip().split('\n') self.watcher.update(paths, filenames, keywords, ignore) def on_start(self, e): self.watcher.run_monitor() self.start_btn.Disable() self.stop_btn.Enable() def on_stop(self, e): self.watcher.stop_monitor() self.stop_btn.Disable() self.start_btn.Enable() def on_sound_chk(self, e): pass def on_spin(self, e): pass
class FEAHandler: # Metodo constructor, seteos basicos necesarios de configuracion, instancia objetos utiles def __init__(self, bot): self.bot = bot self.erepublik = ErAPI() self.watcher = Watcher() # Requires bot for automatic messages self.events = Events(bot) self.serversocket = ServerSocket(bot) # Manejador inutil, existe solo para probar paralelismo y control de errores de nivel superior al objeto def HANDLE_SARASA(self, sender, params, is_pm): # Error intensional para demostrar que ante un error imprevisto esta todo manejado y que # soporta multiples comandos al mismo tiempo (ejecutar varios .sarasa para probar) time.sleep(10) raise Exception('sarasa') if(is_pm): self.bot.queue_append(*['PRIVMSG %s :%s' % (sender, 'Mensajes de a bloques 1.'), 'PRIVMSG %s :%s\n' % (sender, 'Mensaje de a bloques 2.')]) else: channel = params[0] self.bot.queue_append('PRIVMSG %s :%s' % (channel, 'Hola.')) # Manejador del MASS CALL, ilumina todos los nicks y envia mensaje def HANDLE_CHE(self, sender, params, is_pm): self.HANDLE_KUAK(sender, params, is_pm) # Manejador del MASS CALL, ilumina todos los nicks y envia mensaje def HANDLE_KUAK(self, sender, params, is_pm): if(is_pm == False): channel = params[0].lower() if(self.bot.has_level(channel, sender, '%') or self.bot.has_permission(sender, '%')): users = [self.bot.data[channel]['users'][i:i+35] for i in range(0, len(self.bot.data[channel]['users']), 35)] for sublist in users: self.bot.queue_append('PRIVMSG %s :%s' % (channel, ' '.join(sublist))) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,4\02¡ATENCION!\02\x03\x031,0\02 %s\x03' % params[1])) else: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador de sorteo, sortea lo que se envie por parametro al azar entre los miembros del canal, incluso el bot puede ganar ^.^ def HANDLE_SORTEAR(self, sender, params, is_pm): if(is_pm == False): channel = params[0].lower() self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,4\02¡ATENCION!\02\x03\x031,7\02 Comienza el sorteo de: %s\02\x03' % params[1])) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x031,7\02Chan chan chan\02\x03')) time.sleep(1) winner = random.choice(self.bot.data[channel]['users']) if(winner == self.bot.nick): self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,3\02Muajaja, gane yo, denme el premio!\02\x03')) else: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,3\02Felicidades %s, ganaste: %s\02\x03' % (winner, params[1]))) # Manejador del SYNC, actualiza ordenes def HANDLE_SYNC(self, sender, params, is_pm): if(is_pm): if(self.bot.has_permission(sender, '%')): self.bot.refresh_orders() self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Ordenes actualizadas.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: channel = params[0] if(self.bot.has_permission(sender, '%')): self.bot.refresh_orders() self.bot.queue_append('PRIVMSG %s :%s' % (channel, '%s: Ordenes actualizados.' % sender)) else: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del ANUNCIOKUAK, hace un KUAK y luego muestra el ANUNCIO en todos los canales donde esta el bot def HANDLE_ANUNCIOKUAK(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): self.serversocket.send('¡ANUNCIO! %s dice: %s' % (sender, params[1])) for channel in self.bot.data: users = [self.bot.data[channel]['users'][i:i+35] for i in range(0, len(self.bot.data[channel]['users']), 35)] for sublist in users: self.bot.queue_append('PRIVMSG %s :%s' % (channel, ' '.join(sublist))) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,4\02¡ANUNCIO!\02\x03\x030,5 %s dice:\x03\x031,0\02 %s\02\x03' % ('%s\'%s' % (sender[:-1], sender[-1:]), params[1]))) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del ANUNCIO, muestra un mensaje en todos los canales donde esta el bot def HANDLE_ANUNCIO(self, sender, params, is_pm): if(self.bot.has_permission(sender, '@')): self.serversocket.send('¡ANUNCIO! %s dice: %s' % (sender, params[1])) for channel in self.bot.data: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,4\02¡ANUNCIO!\02\x03\x030,5 %s dice:\x03\x031,0\02 %s\02\x03' % ('%s\'%s' % (sender[:-1], sender[-1:]), params[1]))) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del DONAR, muestra los links de donacion del perfil de eR asociado al nick, o si se especifica, de otro nick def HANDLE_DONAR(self, sender, params, is_pm): channel = sender if is_pm == True else params[0] try: if(len(params) > 1): if(bool(params[1].strip())): sender = params[1].strip(' \r\n') id = str(self.erepublik.get_id(sender)) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x03\02%s\02 - \02Donar items:\02\x03 http://www.erepublik.com/es/economy/donate-items/%s\x03 - \02Donar dinero:\02 \x03http://www.erepublik.com/es/economy/donate-money/%s' % (sender, id, id))) except: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x031,4\02Error:\02\x03 Nick \02"%s"\02 no esta registrado.' % sender)) # Manejador del FC, muestra estadisticas del perfil de eR asociado al nick, o si se especifica, de otro nick def HANDLE_FC(self, sender, params, is_pm): channel = sender if is_pm == True else params[0] try: if(len(params) > 1): if(bool(params[1].strip())): sender = params[1].strip(' \r\n') id = self.erepublik.get_id(sender) level = self.erepublik.get_level(sender) strength = self.erepublik.get_strength(sender) rank_points = self.erepublik.get_rank_points(sender) citizenship = self.erepublik.get_citizenship(sender) nick = self.erepublik.get_nick(sender) rank_name = self.erepublik.calculate_rank_name(rank_points) q0 = self.erepublik.calculate_damage(rank_points, strength, 0, level, 1) q1 = self.erepublik.calculate_damage(rank_points, strength, 20, level, 1) q2 = self.erepublik.calculate_damage(rank_points, strength, 40, level, 1) q3 = self.erepublik.calculate_damage(rank_points, strength, 60, level, 1) q4 = self.erepublik.calculate_damage(rank_points, strength, 80, level, 1) q5 = self.erepublik.calculate_damage(rank_points, strength, 100, level, 1) q6 = self.erepublik.calculate_damage(rank_points, strength, 120, level, 1) q7 = self.erepublik.calculate_damage(rank_points, strength, 200, level, 1) #self.bot.queue_append('PRIVMSG %s :%s' % (channel, 'Nick: %s | ID: %d | Nivel: %d | Fuerza: %.2f | Rango: %s | Puntos de rango: %d | Ciudadania: %s ' % (nick, id, level, strength, rank_name, rank_points, citizenship))) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x03\02%s\02\x03 (%s, %.2f de fuerza): \x0314[Q0: \02%d\02]\x03 \x033[Q1: \02%d\02]\x03 \x0312[Q2: \02%d\02]\x03 \x032[Q3: \02%d\02]\x03 \x037[Q4: \02%d\02]\x03 \x034[Q5: \02%d\02]\x03 \x035[Q6: \02%d\02]\x03 \x036[Q7: \02%d\02]\x03 \x030,3[Q7 + NE: \02%d\02]\x03 \x030,3[Q7 + 50%%: \02%d\02]\x03 \x030,3[Q7 + NE + 50%%: \02%d\02]\x03' % (nick, rank_name, strength, q0, q1, q2, q3, q4, q5, q6, q7, q7 * 1.1, q7 * 1.5, q7 * 1.65))) except: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x031,4\02Error:\02\x03 Nick \02"%s"\02 no esta registrado.' % sender)) # Manejador del LP, muestra estadisticas del perfil de eR asociado al nick, o si se especifica, de otro nick def HANDLE_LP(self, sender, params, is_pm): channel = sender if is_pm == True else params[0] try: if(len(params) > 1): if(bool(params[1].strip())): sender = params[1].strip(' \r\n') id = self.erepublik.get_id(sender) level = self.erepublik.get_level(sender) strength = self.erepublik.get_strength(sender) rank_points = self.erepublik.get_rank_points(sender) citizenship = self.erepublik.get_citizenship(sender) nick = self.erepublik.get_nick(sender) rank_name = self.erepublik.calculate_rank_name(rank_points) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x03\02%s\02 [%d] | \02Nivel:\02 %d | \02Fuerza:\02 %.2f | \02Rango:\02 %s (%d) | \02Ciudadania:\02 %s\x03' % (nick, id, level, strength, rank_name, rank_points, citizenship))) except: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x031,4\02Error:\02\x03 Nick \02"%s"\02 no esta registrado.' % sender)) # Manejador del LINK, muestra el link del perfil de eR asociado al nick, o si se especifica, de otro nick def HANDLE_LINK(self, sender, params, is_pm): channel = sender if is_pm == True else params[0] try: if(len(params) > 1): if(bool(params[1].strip())): sender = params[1].strip(' \r\n') id = self.erepublik.get_id(sender) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x03El link al perfil de \02%s\02 es:\x03 http://www.erepublik.com/es/citizen/profile/%d' % (sender, id))) except: self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x031,4\02Error:\02\x03 Nick \02"%s"\02 no esta registrado.' % sender)) # Manejador del REGID, registra el ID asociado al nick que envia el comando def HANDLE_REGID(self, sender, params, is_pm): channel = sender if is_pm == True else params[0] try: self.erepublik.reg_nick_write(sender, params[1]) self.bot.queue_append('PRIVMSG %s :%s' % (channel, 'Usuario registrado.')) except: self.bot.queue_append('PRIVMSG %s :%s' % (channel, 'Error al registrar usuario.')) # Manejador del ORDENES, muestra las ordenes en lista segun prioridad def HANDLE_ORDENES(self, sender, params, is_pm): channel = params[0] if(is_pm): channel = sender for zone in self.bot.orders: for div in ['d1', 'd2', 'd3', 'd4']: if self.bot.orders[zone][div] == 'NO PEGAR': self.bot.orders[zone][div] = '\x030,1\02 NO PEGAR \02\x03' elif self.bot.orders[zone][div] == 'BAJA': self.bot.orders[zone][div] = '\x030,9\02 BAJA \02\x03' elif self.bot.orders[zone][div] == 'MEDIA': self.bot.orders[zone][div] = '\x030,8\02 MEDIA \02\x03' elif self.bot.orders[zone][div] == 'ALTA': self.bot.orders[zone][div] = '\x030,7\02 ALTA \02\x03' elif self.bot.orders[zone][div] == 'MAXIMA': self.bot.orders[zone][div] = '\x030,4\02 MAXIMA \02\x03' data = (zone, self.bot.orders[zone]['id'], self.bot.orders[zone]['d1'], self.bot.orders[zone]['d2'], self.bot.orders[zone]['d3'], self.bot.orders[zone]['d4'], self.bot.orders[zone]['side']) self.bot.queue_append('PRIVMSG %s :%s' % (channel, '\x030,4\02Zona:\02\x03 %s || \02Link: http://erpk.org/b/%d\02 || \02Div 1:\02 %s || \02Div 2:\02 %s || \02Div 3:\02 %s || \02Div 4:\02 %s || \02Side:\02 \x030,3%s\x03' % data)) # Manejador del RW, muestra datos del estado de la rebelion de el/la region/pais indicad@ def HANDLE_RW(self, sender, params, is_pm): channel = sender if is_pm == True else params[0] if(params[1][0] == '-'): type = params[1][1:params[1].find(' ')].lower() what = params[1][params[1].find(' ') + 1:].strip('\r\n ').lower() if(len(what) > 0 and what[0] != '-'): if(type == 'p' or type == 'a'): if(type == 'a'): what = self.watcher.get_country_name(what) if(what != False): self.bot.queue_append('PRIVMSG %s :Regiones cargadas en: %s' % (channel, what)) rws = self.watcher.get_by_country_name(what) if(rws != False): enabled = False for rw in rws: if(rw['enabled'] == True): enabled = True self.bot.queue_append('PRIVMSG %s :%s [%s] | Supporters: %d/10' % (channel, rw['region_name'], rw['region_initial'], len(rw['supporters']))) if(enabled == False): self.bot.queue_append('PRIVMSG %s :El pais no tiene rebeliones activas.' % (channel)) else: self.bot.queue_append('PRIVMSG %s :\x031,4\02Error:\02\x03 Pais erroneo o no cargado en el sistema.' % channel) else: self.bot.queue_append('PRIVMSG %s :\x031,4\02Error:\02\x03 Abreviacion de pais erronea o inexistente.' % channel) elif(type == 's'): rw = self.watcher.get_by_region_initial(what) if(rw != False): if(rw['enabled'] == True): self.bot.queue_append('PRIVMSG %s :%s [%s] | Pais: %s [%s] | Supporters: %d/10' % (channel, rw['region_name'], rw['region_initial'], rw['country_name'], rw['country_initial'],len(rw['supporters']))) else: self.bot.queue_append('PRIVMSG %s :La region %s no tiene una rebelion activa.' % (channel, rw['region_name'])) else: self.bot.queue_append('PRIVMSG %s :\x031,4\02Error:\02\x03 Region incorrecta o no cargada en el sistema.' % channel) else: self.bot.queue_append('PRIVMSG %s :\x031,4\02Error:\02\x03 tipo de parametro incorrecto.' % channel) else: self.bot.queue_append('PRIVMSG %s :\x031,4\02Error:\02\x03 No se especifico valor del parametro.' % channel) else: self.bot.queue_append('PRIVMSG %s :\x031,4\02Error:\02\x03 No se especifico tipo de parametro.' % channel) # Manejador del HELP, muestra link al HTML de ayuda del bot def HANDLE_HELP(self, sender, params, is_pm): if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Hoja de ayuda: %s' % self.bot.help_html)) else: channel = params[0] self.bot.queue_append('PRIVMSG %s :%s' % (channel, 'Hoja de ayuda: %s' % self.bot.help_html)) # Manejador del JOIN, une el bot a un canal, parametro opcional de contraseña def HANDLE_JOIN(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): self.bot.queue_append('JOIN %s\n' % params[1].strip('\r\n')) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del PART, hace salir al bot de un canal y borra dicho canal de la lista temporal de canales def HANDLE_PART(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): self.bot.queue_append('PART %s\n' % params[1].strip('\r\n')) self.bot.del_channel(params[1].strip('\r\n')) self.bot.del_channel_event(params[1].strip('\r\n')) self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Canal eliminado de la lista de canales temporales y de canales de evento. No olvides hacerlo efectivo con ".update".')) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del STAY, añade el canal especificado a la lista temporal de canales, parametro opcional la contraseña del canal def HANDLE_STAY(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): parts = params[1].strip('\r\n').split(' ', 1) if len(parts) > 1: self.bot.add_channel(parts[0], parts[1]) else: self.bot.add_channel(parts[0], '') if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Canal agregado para autoinicio. No olvides hacerlo efectivo con ".update".')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Canal agregado para autoinicio. No olvides hacerlo efectivo con ".update".' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del DEL, elimina el nick ESPECIFICADO de la lista temporal del permiso ESPECIFICADO def HANDLE_DEL(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): parts = params[1].strip('\r\n').split(' ', 1) if len(parts) > 1: if((parts[1] != '~' and parts[1] != '&') or self.bot.has_permission(sender, '~')): self.bot.del_permission(parts[0], parts[1]) if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Permiso eliminado correctamente. No olvides hacerlo efectivo con ".update".')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Permiso eliminado correctamente. No olvides hacerlo efectivo con ".update".' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No puedes eliminar permisos iguales o superiores al tuyo.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No puedes eliminar permisos iguales o superiores al tuyo.' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'El formato del comando es erroneo.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: El formato del comando es erroneo.' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del ADD, agrega el nick ESPECIFICADO en la lista temporal del permiso ESPECIFICADO def HANDLE_ADD(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): parts = params[1].strip('\r\n').split(' ', 1) if len(parts) > 1: if((parts[1] != '~' and parts[1] != '&') or self.bot.has_permission(sender, '~')): self.bot.add_permission(parts[0], parts[1]) if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Permiso asignado correctamente. No olvides hacerlo efectivo con ".update".')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Permiso asignado correctamente. No olvides hacerlo efectivo con ".update".' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Solo puedes asignar permisos inferiores al tuyo.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Solo puedes asignar permisos inferiores al tuyo.' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'El formato del comando es erroneo.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: El formato del comando es erroneo.' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del UPDATE, actualiza hojas de datos de permisos y canales con los datos actuales del bot def HANDLE_UPDATE(self, sender, params, is_pm): if(self.bot.has_permission(sender, '&')): self.bot.update_permission() self.bot.update_channels() self.bot.update_channels_events() if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Base de datos de permisos y canales actualizadas.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Base de datos de permisos y canales actualizadas.' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del SAY, hace hablar al bot en el canal especificado diciendo el mensaje del parametro def HANDLE_SAY(self, sender, params, is_pm): if(self.bot.has_permission(sender, '~')): parts = params[1].split(' ', 1) if(parts[0].lower() != self.bot.nick.lower()): if(parts[1][0] != '.'): self.bot.queue_append('PRIVMSG %s :%s' % (parts[0], parts[1])) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del ACT, hace actuar al bot en el canal especificado diciendo el mensaje del parametro def HANDLE_ACT(self, sender, params, is_pm): if(self.bot.has_permission(sender, '~')): parts = params[1].split(' ', 1) if(parts[0].lower() != self.bot.nick.lower()): if(parts[1][0] != '.'): self.bot.queue_append('PRIVMSG %s :\01ACTION %s\01' % (parts[0], parts[1].strip('\r\n'))) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del REBOOT, reinicia el bot, por consecuencia se actualizan listas de canales y permisos desde las hojas de calculo def HANDLE_REBOOT(self, sender, params, is_pm): if(self.bot.has_permission(sender, '~')): self.bot.running = False else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del SHUTDOWN, desconecta el bot de forma remota evitando su reinicio. Finaliza todos los threads def HANDLE_SHUTDOWN(self, sender, params, is_pm): if(self.bot.has_permission(sender, '~')): self.bot.dont_reconnect = True self.bot.queue_append('QUIT :%s' % 'Debo irme, mi planeta me necesita.') else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del MATAR, "mata" al nick indicado def HANDLE_MATAR(self, sender, params, is_pm): if(is_pm == False): target = params[1][:params[1].find(' ')] if('xxciro' in target.lower()): if('xxciro' in sender.lower()): self.bot.queue_append(*['PRIVMSG %s :No podria vivir sin usted, no me oblige, nooooooooooo!' % params[0], 'PRIVMSG %s :\01ACTION mata a %s y se suicida.\01' % (params[0], target)]) else: self.bot.queue_append(*['PRIVMSG %s :¿Osas intentar matar a mi creador?' % params[0], 'PRIVMSG %s :\01ACTION captura a %s y lo encierra en una jaula. El creador decidira que hacer contigo.\01' % (params[0], sender)]) elif(self.bot.nick.lower() in target.lower()): if('xxciro' in sender.lower()): self.bot.queue_append(*['PRIVMSG %s :Si mi amo!' % params[0], 'PRIVMSG %s :\01ACTION se suicida.\01' % params[0]]) else: self.bot.queue_append(*['PRIVMSG %s :¿Me tomas por idiota?' % params[0], 'PRIVMSG %s :\01ACTION mata a %s y juega con sus tripas :3\01' % (params[0], sender)]) else: self.bot.queue_append('PRIVMSG %s :\01ACTION mata a %s y juega con sus tripas :3\01' % (params[0], target)) # Manejador del ABRAZAR, "abraza" al nick indicado mediante un ACT def HANDLE_ABRAZAR(self, sender, params, is_pm): if(is_pm == False): target = params[1][:params[1].find(' ')] if('xxciro' in target.lower()): self.bot.queue_append('PRIVMSG %s :\01ACTION abraza a su creador :3\01' % params[0]) elif(self.bot.nick.lower() in target.lower()): self.bot.queue_append('PRIVMSG %s :\01ACTION se autoabraza.\01' % params[0]) else: self.bot.queue_append('PRIVMSG %s :\01ACTION abraza a %s :3\01' % (params[0], target)) # Manejador del EJECT, kickbanea al nick indicado durante x segundos def HANDLE_EJECT(self, sender, params, is_pm): if(is_pm == False): if(self.bot.has_level(params[0].lower(), self.bot.nick, '%')): if(self.bot.has_level(params[0].lower(), sender, '%')): target = params[1][:params[1].find(' ')] ban_time = random.randrange(10) if('xxciro' in target.lower()): if('xxciro' in sender.lower()): self.bot.queue_append('PRIVMSG %s :No podria vivir sin usted, no me oblige, nooooooooooo!' % params[0]) self.bot.queue_append('PRIVMSG %s :El creador ha sido ejecutado durante %d segundos' % (params[0], ban_time)) self.bot.queue_append('MODE %s +b %s' % (params[0], target)) self.bot.queue_append('KICK %s %s :A VOOOLLLLAAARRR!!!!!!! Regresa dentro de %d segundos!!!' % (params[0], target, ban_time)) time.sleep(ban_time) self.bot.queue_append('MODE %s -b %s' % (params[0], target)) else: self.bot.queue_append('PRIVMSG %s :¿Osas intentar matar a mi creador?' % params[0]) self.bot.queue_append('PRIVMSG %s :%s ha sido ejecutado por %s durante %d segundos' % (params[0], sender, self.bot.nick, ban_time)) self.bot.queue_append('MODE %s +b %s' % (params[0], sender)) self.bot.queue_append('KICK %s %s :A VOOOLLLLAAARRR!!!!!!! Regresa dentro de %d segundos!!!' % (params[0], sender, ban_time)) time.sleep(ban_time) self.bot.queue_append('MODE %s -b %s' % (params[0], sender)) elif(self.bot.nick.lower() in target.lower()): self.bot.queue_append('PRIVMSG %s :¿Me tomas por idiota?' % params[0]) self.bot.queue_append('PRIVMSG %s :%s ha sido ejecutado por %s durante %d segundos' % (params[0], sender, self.bot.nick, ban_time)) self.bot.queue_append('MODE %s +b %s' % (params[0], sender)) self.bot.queue_append('KICK %s %s :A VOOOLLLLAAARRR!!!!!!! Regresa dentro de %d segundos!!!' % (params[0], sender, ban_time)) time.sleep(ban_time) self.bot.queue_append('MODE %s -b %s' % (params[0], sender)) else: self.bot.queue_append('PRIVMSG %s :%s ha sido ejecutado por %s durante %d segundos' % (params[0], target, sender, ban_time)) self.bot.queue_append('MODE %s +b %s' % (params[0], target)) self.bot.queue_append('KICK %s %s :A VOOOLLLLAAARRR!!!!!!! Regresa dentro de %d segundos!!!' % (params[0], target, ban_time)) time.sleep(ban_time) self.bot.queue_append('MODE %s -b %s' % (params[0], target)) else: self.bot.queue_append('PRIVMSG %s :%s: No tienes accesos suficientes como para ejecutar este comando.' % (params[0], sender)) else: self.bot.queue_append('PRIVMSG %s :%s: No tengo accesos suficientes como para ejecutar este comando, necesito HOP.' % (params[0], sender)) # Manejador del FUSILAR, kickbanea al nick indicado durante x segundos def HANDLE_FUSILAR(self, sender, params, is_pm): if(is_pm == False): if(self.bot.has_level(params[0].lower(), self.bot.nick, '%')): if(self.bot.has_level(params[0].lower(), sender, '%')): target = params[1][:params[1].find(' ')] if('xxciro' in target.lower()): if('xxciro' in sender.lower()): self.bot.queue_append('PRIVMSG %s :No podria vivir sin usted, no me oblige, nooooooooooo!' % params[0]) self.bot.queue_append(*['PRIVMSG %s :\01ACTION le pone un cigarro a %s y lo prende\01' % (params[0], target), 'PRIVMSG %s :\01ACTION deja que %s diga sus ultimas palabras\01' % (params[0], target), 'PRIVMSG %s :\01ACTION Apunta!!!\01' % (params[0]), 'MODE %s +b %s' % (params[0], target), 'KICK %s %s :PUUUUMMMMMMM!!!!!! You\'re DEAD!' % (params[0], target), 'MODE %s -b %s' % (params[0], target)]) else: self.bot.queue_append('PRIVMSG %s :¿Osas intentar matar a mi creador?' % params[0]) self.bot.queue_append(*['PRIVMSG %s :\01ACTION le pone un cigarro a %s y lo prende\01' % (params[0], sender), 'PRIVMSG %s :\01ACTION deja que %s diga sus ultimas palabras\01' % (params[0], sender), 'PRIVMSG %s :\01ACTION Apunta!!!\01' % (params[0]), 'MODE %s +b %s' % (params[0], sender), 'KICK %s %s :PUUUUMMMMMMM!!!!!! You\'re DEAD!' % (params[0], sender), 'MODE %s -b %s' % (params[0], sender)]) elif(self.bot.nick.lower() in target.lower()): self.bot.queue_append('PRIVMSG %s :¿Me tomas por idiota?' % params[0]) self.bot.queue_append(*['PRIVMSG %s :\01ACTION le pone un cigarro a %s y lo prende\01' % (params[0], sender), 'PRIVMSG %s :\01ACTION deja que %s diga sus ultimas palabras\01' % (params[0], sender), 'PRIVMSG %s :\01ACTION Apunta!!!\01' % (params[0]), 'MODE %s +b %s' % (params[0], sender), 'KICK %s %s :PUUUUMMMMMMM!!!!!! You\'re DEAD!' % (params[0], sender), 'MODE %s -b %s' % (params[0], sender)]) else: self.bot.queue_append(*['PRIVMSG %s :\01ACTION le pone un cigarro a %s y lo prende\01' % (params[0], target), 'PRIVMSG %s :\01ACTION deja que %s diga sus ultimas palabras\01' % (params[0], target), 'PRIVMSG %s :\01ACTION Apunta!!!\01' % (params[0]), 'MODE %s +b %s' % (params[0], target), 'KICK %s %s :PUUUUMMMMMMM!!!!!! You\'re DEAD!' % (params[0], target), 'MODE %s -b %s' % (params[0], target)]) else: self.bot.queue_append('PRIVMSG %s :%s: No tienes accesos suficientes como para ejecutar este comando.' % (params[0], sender)) else: self.bot.queue_append('PRIVMSG %s :%s: No tengo accesos suficientes como para ejecutar este comando, necesito HOP.' % (params[0], sender)) # Manejador del EVENTO, añade el canal especificado a la lista temporal de canales, parametro opcional la contraseña del canal def HANDLE_EVENTO(self, sender, params, is_pm): parts = params[1].strip(' \r\n').split(' ', 1) if(self.bot.has_level(params[0].lower(), sender, '&') or self.bot.has_permission(sender, '~')): if len(parts) == 2 and (parts[1].lower() == 'enable' or parts[1].lower() == 'disable'): if parts[1].lower() == 'enable': self.bot.add_channel_event(parts[0]) if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Canal agregado temporalmente para evento. No olvides hacerlo efectivo con ".update".')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Canal agregado temporalmente para evento. No olvides hacerlo efectivo con ".update".' % sender)) else: self.bot.del_channel_event(parts[0]) if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Canal eliminado temporalmente para evento. No olvides hacerlo efectivo con ".update".')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Canal eliminado temporalmente para evento. No olvides hacerlo efectivo con ".update".' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'Formato del comando invalido.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: Formato del comando invalido.' % sender)) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender)) # Manejador del ADMIN, permite visualizar valores de variables def HANDLE_ADMIN(self, sender, params, is_pm): if self.bot.has_permission(sender, '~'): parts = params[1].strip(' \r\n').split(' ', 1) str_exit = 'Formato de comando invalido' if len(parts) >= 1: if parts[0].lower() == 'evento': str_exit = ', '.join(self.bot.channels_events) elif parts[0].lower() == 'channels': channels_list = [] for channel in self.bot.data: channels_list.append(channel) str_exit = ', '.join(channels_list) elif parts[0].lower() == 'data': str_exit = str(self.bot.data) else: str_exit = 'Valor de busqueda invalido' if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, str_exit)) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: %s' % (sender, str_exit))) else: if(is_pm): self.bot.queue_append('PRIVMSG %s :%s' % (sender, 'No tienes permiso para utilizar ese comando.')) else: self.bot.queue_append('PRIVMSG %s :%s' % (params[0], '%s: No tienes permiso para utilizar ese comando.' % sender))