def reobfuscate(conffile, reobf_all, keep_lvt, keep_generics, only_client, only_server, srg_names, force_rg): try: commands = Commands(conffile, verify=True) if keep_generics: keep_lvt = True # client or server process_client = True process_server = True if only_client and not only_server: process_server = False if only_server and not only_client: process_client = False commands.logger.info('> Creating Retroguard config files') commands.creatergcfg(reobf=True, keep_lvt=keep_lvt, keep_generics=keep_generics, srg_names=srg_names) if process_client: reobfuscate_side(commands, CLIENT, reobf_all=reobf_all, srg_names=srg_names, force_rg=force_rg) if process_server: reobfuscate_side(commands, SERVER, reobf_all=reobf_all, srg_names=srg_names, force_rg=force_rg) except Exception: # pylint: disable-msg=W0703 logging.exception('FATAL ERROR') sys.exit(1)
def updatemd5(conffile, force): try: commands = Commands(conffile) if (commands.checkmd5s(CLIENT) or commands.checkmd5s(SERVER)) and not force: print 'WARNING:' print 'The updatemd5 script is unsupported and should only be run in special' print 'cases, such as if there were compile errors in the last decompile which' print 'have now been corrected. It will reset the changed status of all classes' print 'for reobfuscation, and only classes modified afterwards will end up in' print 'the reobf directory.' print 'Only use this script if you absolutely know what you are doing, or when a' print 'MCP team member asks you to do so.' answer = raw_input('If you really want to update all classes, enter "Yes" ') if answer.lower() not in ['yes']: print 'You have not entered "Yes", aborting the update process' sys.exit(1) try: updatemd5_side(commands, CLIENT) except CalledProcessError: commands.logger.error('Client recompile failed, correct source then rerun updatemd5') try: updatemd5_side(commands, SERVER) except CalledProcessError: commands.logger.error('Server recompile failed, correct source then rerun updatemd5') except Exception: # pylint: disable-msg=W0703 logging.exception('FATAL ERROR') sys.exit(1)
def parse_cmd(inp, key): """ This function validates the data we received from the API and delegates the appropriate responses to that data. """ # First check if inp can be parsed as an integer try: int(inp) print(inp) except: print('Input was not an integer :)') return commands = Commands() if inp == '1': print('input 1') message = communication.getdata(cfg.P_BASE, cfg.P_COMMAND, key) commands.system_cmd(message) elif inp == '2': url_to_open = communication.getdata(cfg.P_BASE, cfg.P_COMMAND, key) commands.open_webbrowser(url_to_open) elif inp == '3': url_to_open = communication.getdata(cfg.P_BASE, cfg.P_COMMAND, key) screenshot = Screenshot() screenshot.snap()
def status(self, env): from params import status_params env.set_params(status_params) commands = Commands(status_params) if not commands.topologies_running(): raise ComponentIsNotRunning()
def install(self, env): import params env.set_params(params) commands = Commands(params) commands.setup_repo() Logger.info('Install RPM packages') self.install_packages(env)
def status(self, env): import status_params env.set_params(status_params) commands = Commands(status_params) if not commands.is_topology_active(): raise ComponentIsNotRunning()
def on_publicmsg(self, connection, event): if connection != self.connection: self.log.info("IRC: Incorrect connection in on_publicmsg") return incoming_message = event.arguments()[0].lstrip() if len(incoming_message) < 1: return cmd = incoming_message.partition(" ")[0][1:] args = incoming_message.partition(" ")[2] src = event.source() if incoming_message[0] == "!": self.log.info("Command: \"%s\" Args: \"%s\" From: \"%s\"" % (cmd, args, src)) command = Commands(event.target(), self.command_info, self.command_callback) command.parse(cmd, args, src) else: inc_msg = incoming_message.strip(" \t\n\r").lower() origin = src.partition("!")[0] if (not inc_msg.find("morning") == -1) and (not inc_msg.find(self.config.nick) == -1): self.command_callback("Morning %s" % origin, event.target()) elif (not inc_msg.find("afternoon") == -1) and (not inc_msg.find(self.config.nick) == -1): self.command_callback("Afternoon %s" % origin, event.target()) elif (not inc_msg.find("evening") == -1) and (not inc_msg.find(self.config.nick) == -1): self.command_callback("Evening %s" % origin, event.target()) elif (not inc_msg.find("night") == -1) and (not inc_msg.find(self.config.nick) == -1): self.command_callback("Good night %s" % origin, event.target())
def cleanup(conffile, force, distclean): try: commands = Commands(conffile, shortstart=True) if not force: print 'WARNING:' print 'The cleanup script will delete all folders created by MCP, including the' print 'src folder which may contain changes you made to the code, along with any' print 'saved worlds from the client or server.' answer = raw_input('If you really want to clean up, enter "Yes" ') if answer.lower() not in ['yes']: print 'You have not entered "Yes", aborting the clean up process' sys.exit(1) commands.checkupdates() try: commands.logger.info('> Cleaning temp') reallyrmtree(commands.dirtemp) commands.logger.info('> Cleaning src') reallyrmtree(commands.dirsrc) commands.logger.info('> Cleaning bin') reallyrmtree(commands.dirbin) commands.logger.info('> Cleaning reobf') reallyrmtree(commands.dirreobf) if distclean: commands.logger.info('> Cleaning lib') reallyrmtree(commands.dirlib) commands.logger.info('> Cleaning jars') reallyrmtree(os.path.join(commands.dirjars, 'stats')) reallyrmtree(os.path.join(commands.dirjars, 'texturepacks')) reallyrmtree(os.path.join(commands.dirjars, 'texturepacks-mp-cache')) if distclean: reallyrmtree(os.path.join(commands.dirjars, 'saves')) reallyrmtree(os.path.join(commands.dirjars, 'mcpworld')) reallyrmtree(os.path.join(commands.dirjars, 'versions')) reallyrmtree(os.path.join(commands.dirjars, 'assets')) reallyrmtree(os.path.join(commands.dirjars, 'libraries')) if os.path.exists(os.path.join(commands.dirjars, 'server.log')): os.remove(os.path.join(commands.dirjars, 'server.log')) for txt_file in glob.glob(os.path.join(commands.dirjars, '*.txt')): os.remove(txt_file) commands.logger.info('> Cleaning logs') logging.shutdown() reallyrmtree(commands.dirlogs) except OSError as ex: print >> sys.stderr, 'Cleanup FAILED' if hasattr(ex, 'filename'): print >> sys.stderr, 'Failed to remove ' + ex.filename sys.exit(1) except Exception: # pylint: disable-msg=W0703 logging.exception('FATAL ERROR') sys.exit(1)
def startserver(conffile=None): commands = Commands(conffile) try: commands.startserver() except Exception: # pylint: disable-msg=W0703 commands.logger.exception('FATAL ERROR') sys.exit(1)
def test_run_retcodes(self): p = Commands(CommandsBase("opengrok-master", [["/bin/echo"], ["/bin/true"], ["/bin/false"]])) p.run() # print(p.retcodes) self.assertEqual({'/bin/echo opengrok-master': 0, '/bin/true opengrok-master': 0, '/bin/false opengrok-master': 1}, p.retcodes)
def cleanup(conffile=None, force=False): if not force: print "WARNING:" print "The cleanup script will delete all folders created by MCP, including the" print "src folder which may contain changes you made to the code." answer = raw_input('If you really want to clean up, enter "Yes" ') if answer.lower() not in ["yes"]: print 'You have not entered "Yes", aborting the clean up process' sys.exit(1) commands = Commands(conffile) commands.checkupdates() commands.logger.info("> Cleaning temp") try: reallyrmtree(commands.dirtemp) except OSError: commands.logger.error("failed cleaning temp") commands.logger.info("> Cleaning src") try: reallyrmtree(commands.dirsrc) except OSError: commands.logger.error("failed cleaning src") commands.logger.info("> Cleaning bin") try: reallyrmtree(commands.dirbin) except OSError: commands.logger.error("failed cleaning bin") commands.logger.info("> Cleaning reobf") try: reallyrmtree(commands.dirreobf) except OSError: commands.logger.error("failed cleaning reobf") commands.logger.info("> Cleaning jars") try: reallyrmtree(os.path.join(commands.dirjars, "saves")) except OSError: commands.logger.error("failed cleaning saves") try: reallyrmtree(os.path.join(commands.dirjars, "texturepacks")) except OSError: commands.logger.error("failed cleaning texturepacks") try: reallyrmtree(os.path.join(commands.dirjars, "world")) except OSError: commands.logger.error("failed cleaning world") if os.path.exists(os.path.join(commands.dirjars, "server.log")): os.remove(os.path.join(commands.dirjars, "server.log")) for txt_file in glob.glob(os.path.join(commands.dirjars, "*.txt")): os.remove(txt_file) commands.logger.info("> Cleaning logs") logging.shutdown() reallyrmtree(commands.dirlogs)
def main(conffile=None): commands = Commands(conffile) commands.logger.info ('> Recompiling') recompile.main(conffile) commands.logger.info ('> Generating the md5 (client)') commands.gathermd5s(0) commands.logger.info ('> Generating the md5 (server)') commands.gathermd5s(1)
def service_check(self, env): from params import params env.set_params(params) commands = Commands(params) all_found = commands.topologies_running() if all_found: exit(0) else: exit(1)
def service_check(self, env): import params env.set_params(params) commands = Commands(params) if commands.is_topology_active(): exit(0) else: exit(1)
def updatemcp(conffile=None, force=False): commands = Commands(conffile) try: commands.logger.info('== Updating MCP ==') commands.downloadupdates(force) except Exception: # pylint: disable-msg=W0703 commands.logger.exception('FATAL ERROR') sys.exit(1)
class Bot(irc.IRCClient): """Core Bot events, subclassed from Twisted's IRCClient Respond to privmsgs in channels and wrap self.msg to delegate replies based on the context (query versus public channel). This also maintains the Redis and last.fm connections while creating contacts as users talk. """ def __init__(self, nickname, chans, fact): """initialize the Bot info, Redis client, and last.fm connection""" self.nickname = nickname self.chans = chans self.factory = fact self.db = Contacts() self.youtube = Youtube(secrets.YOUTUBE_API_KEY) self.commands = Commands(self) self.last = pylast.LastFMNetwork(api_key=secrets.LAST_API_KEY, api_secret=secrets.LAST_API_SECRET, username=secrets.LAST_USER, password_hash=secrets.LAST_PASS_HASH) def _isPrivate(self, nick, channel): """sets the private context based on channel or user""" return (channel == self.nickname and nick != self.nickname) def signedOn(self): for chan in self.chans: self.join(chan) def msg(self, contact, message): """wraps self.msg to delegate the reply""" channel = contact.nick if contact.private else contact.channel irc.IRCClient.msg(self, channel, message) def privmsg(self, user, channel, message): """manages contacts based on message and dispatches it to Commands Interface with Redis for getting, or creating, the Contact and setting its context, then passing it off to be parsed. """ contact = self.db.get(user) # update private context for replies to existing contact if contact: private = self._isPrivate(contact.nick, channel) contact.channel = channel contact.private = private # if new contact, create and set private context else: contact = Contact(user, channel) contact.private = self._isPrivate(contact.nick, channel) self.db.set(contact.user, contact) # only respond if it's properly said if contact.private or message.startswith("!"): self.commands.parse(contact, message)
def main(): parser = build_parser() args = validate(parser) commands = Commands() commands.authenticate() try: getattr(commands, args.command_name)(args) except AttributeError: print('[{}] command does not exist.'.format(args.command_name))
class ComodITConsole(object): def __init__(self, debug = False): self._cmds = None self._debug = debug def interact(self): if self._cmds == None: raise Exception("Console must be connected") readline.parse_and_bind('tab: complete') readline.set_completer_delims(readline.get_completer_delims().replace('-', '')) while True: try: readline.set_completer(self._cmds.get_completer()) line = raw_input(self._cmds.prompt() + "> ") self.execute_line(line) except EOFError: print break except KeyboardInterrupt: print # skip a line continue def execute_file(self, path): with open(path, 'r') as f: for line in f: self.execute_line(line) def connect(self, api_url, username, password, insecure = False): self._cmds = Commands(Client(api_url, username, password, insecure)) self._cmds.set_debug(self._debug) def execute_line(self, line): # Strip comments out index = line.find('#') if index >= 0: line = line[0:index] line = line.strip() # If line is empty, do nothing if line != '': args = merge_escaped(line.split()) self._execute(args) def _execute(self, args): if len(args) == 0: # Nothing to do return try: self._cmds.call(args) except Exception as e: sys.stderr.write(str(e) + "\n") if self._debug: sys.exit(1)
def startserver(conffile): try: commands = Commands(conffile) if not commands.checkbins(SERVER): commands.logger.warning('!! Can not find server bins !!') sys.exit(1) commands.startserver() except Exception: # pylint: disable-msg=W0703 logging.exception('FATAL ERROR') sys.exit(1)
def startclient(conffile): try: commands = Commands(conffile) if not commands.checkbins(CLIENT): commands.logger.warning("!! Can not find client bins !!") sys.exit(1) commands.startclient() except Exception: # pylint: disable-msg=W0703 logging.exception("FATAL ERROR") sys.exit(1)
def worker(base): """ Process one project by calling set of commands. """ x = Commands(base) logger.debug(str(os.getpid()) + " " + str(x)) x.run() base.fill(x.retcodes, x.outputs, x.failed) return base
def updatemd5(conffile=None): commands = Commands(conffile) try: commands.logger.info('> Recompiling') recompile(conffile) commands.logger.info('> Generating the md5 (client)') commands.gathermd5s(CLIENT) commands.logger.info('> Generating the md5 (server)') commands.gathermd5s(SERVER) except Exception: # pylint: disable-msg=W0703 commands.logger.exception('FATAL ERROR') sys.exit(1)
class GDBMICmd(cmd.Cmd): """Simple extension of Cmd for controlling GDB.""" prompt = "" intro = "" def __init__(self): """Initialize Cmd and load the commands.""" cmd.Cmd.__init__(self) self.use_rawinput = 1 self.completekey = "tab" self.commands = Commands() def do_EOF(self, line): """Terminate.""" return True def dispatch_gdbmi_command_string(self, string): """Dispatch a GDBMI command from a string.""" command = self.resolve_gdbmi_command(string) if command: self.dispatch_gdbmi_command(cmd) def dispatch_gdbmi_command(self, command): """Execute a GDBMI command. Should be over-ridden by children.""" print("Would invoke {0} with arguments {1} and options {2}".format( command.command, command.args, command.opts)) def check_gdbmi_command(self, string): """Check whether a string is a valid command.""" if self.commands.complete(string): return True return False def run(self): """Main run loop. Should be over-ridden by children if needed.""" self.cmdloop() def resolve_gdbmi_command(self, line, err=True): """Parse a line into a GDBMI command.""" command = self.commands.generate_command(line) if not command and err: print("Bad command: " + line) return command def default(self, line): """Catch and handle all GDBMI commands.""" command = self.resolve_gdbmi_command(line) if command: self.dispatch_gdbmi_command(command)
def reobfuscate(conffile, reobf_all, keep_lvt, keep_generics): try: commands = Commands(conffile, verify=True) if keep_generics: keep_lvt = True commands.logger.info('> Creating Retroguard config files') commands.creatergcfg(reobf=True, keep_lvt=keep_lvt, keep_generics=keep_generics) reobfuscate_side(commands, CLIENT, reobf_all=reobf_all) reobfuscate_side(commands, SERVER, reobf_all=reobf_all) except Exception: # pylint: disable-msg=W0703 logging.exception('FATAL ERROR') sys.exit(1)
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('-f', '--force', action='store_true', dest='force', help='force cleanup', default=False) parser.add_option('-c', '--config', dest='config', help='additional configuration file') parser.add_option('-d', '--distclean', action='store_true', dest='distclean', help='Remove worlds, libraries and jars', default=False) options, _ = parser.parse_args() cleanup(options.config, options.force, options.distclean)
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('--client', dest='only_client', action='store_true', help='only process client', default=False) parser.add_option('--server', dest='only_server', action='store_true', help='only process server', default=False) parser.add_option('-j', '--jad', dest='force_jad', action='store_true', help='force use of JAD even if Fernflower available', default=False) parser.add_option('-s', '--csv', dest='force_csv', action='store_true', help='force use of CSVs even if SRGs available', default=False) parser.add_option('-r', '--norecompile', dest='no_recompile', action='store_true', help='disable recompile after decompile', default=False) parser.add_option('-d', '--nocomments', dest='no_comments', action='store_true', help='disable javadoc', default=False) parser.add_option('-a', '--noreformat', dest='no_reformat', action='store_true', help='disable source reformatting', default=False) parser.add_option('-n', '--norenamer', dest='no_renamer', action='store_true', help='disable field and method renaming', default=False) parser.add_option('-l', '--lvt', dest='keep_lvt', action='store_true', help='preserve local variable table', default=False) parser.add_option('-g', '--generics', dest='keep_generics', action='store_true', help='preserve generics as well as local variables', default=False) parser.add_option('-o', '--onlypatch', dest='only_patch', action='store_true', help='only patch source', default=False) parser.add_option('-p', dest='no_patch', action='store_true', help='Undocumented magic', default=False) parser.add_option('-c', '--config', dest='config', help='additional configuration file') options, _ = parser.parse_args() decompile(options.config, options.force_jad, options.force_csv, options.no_recompile, options.no_comments, options.no_reformat, options.no_renamer, options.no_patch, options.only_patch, options.keep_lvt, options.keep_generics, options.only_client, options.only_server)
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('--client', dest='only_client', action='store_true', help='only process client', default=False) parser.add_option('--server', dest='only_server', action='store_true', help='only process server', default=False) parser.add_option('-c', '--config', dest='config', help='additional configuration file') options, _ = parser.parse_args() recompile(options.config, options.only_client, options.only_server)
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('-c', '--config', dest='config', help='additional configuration file') parser.add_option('-m', '--main', dest='mainclass', help='Main class to start', default='net.minecraft.server.MinecraftServer') parser.add_option('-j', '--json', dest='json',action='store_true', help='Use the json file to setup parameters', default=False) options, _ = parser.parse_args() startserver(options.config, options.mainclass, options.json)
def main(): parser = OptionParser(version="MCP %s" % Commands.fullversion()) parser.add_option("--client", dest="only_client", action="store_true", help="only process client", default=False) parser.add_option("--server", dest="only_server", action="store_true", help="only process server", default=False) parser.add_option("-c", "--config", dest="config", help="additional configuration file") options, _ = parser.parse_args() recompile(options.config, options.only_client, options.only_server)
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('--client', dest='only_client', action='store_true', help='only process client', default=False) parser.add_option('--server', dest='only_server', action='store_true', help='only process server', default=False) parser.add_option('-j', '--jad', dest='force_jad', action='store_true', help='force use of JAD even if Fernflower available', default=False) parser.add_option('--rg', dest='force_rg', action='store_true', help='force use of RetroGuard even if SpecialSource available', default=False) parser.add_option('-s', '--csv', dest='force_csv', action='store_true', help='force use of CSVs even if SRGs available', default=False) parser.add_option('-r', '--norecompile', dest='no_recompile', action='store_true', help='disable recompile after decompile', default=False) parser.add_option('-d', '--nocomments', dest='no_comments', action='store_true', help='disable javadoc', default=False) parser.add_option('-a', '--noreformat', dest='no_reformat', action='store_true', help='disable source reformatting', default=False) parser.add_option('-n', '--norenamer', dest='no_renamer', action='store_true', help='disable field and method renaming', default=False) parser.add_option('-l', '--kill_lvt', dest='keep_lvt', action='store_false', help='erase local variable table', default=True) parser.add_option('-g', '--kill_generics', dest='keep_generics', action='store_false', help='Destroy generics', default=True) parser.add_option('-o', '--onlypatch', dest='only_patch', action='store_true', help='only patch source', default=False) parser.add_option('-p', dest='no_patch', action='store_true', help='Undocumented magic', default=False) parser.add_option('-c', '--config', dest='config', help='additional configuration file') parser.add_option('-w', '--workDir', dest='workdir', help='Change client lookup place (by default, ~/.minecraft)') parser.add_option('--json', dest='json', help='Location of the json file for none standard installs') parser.add_option('--nocopy', dest='nocopy', action='store_true', help='Do not try to copy assets from minecraft install', default=False) options, _ = parser.parse_args() decompile(options.config, options.force_jad, options.force_csv, options.no_recompile, options.no_comments, options.no_reformat, options.no_renamer, options.no_patch, options.only_patch, options.keep_lvt, options.keep_generics, options.only_client, options.only_server, options.force_rg, options.workdir, options.json, options.nocopy)
def create_commands(is_left=True, bonus=5, color=3, black=6): block_circles = BlockCirclesCoordinate(is_left, bonus, color, black) cross_circles = CrossCirclesCoordinate() return Commands(block_circles, cross_circles)
def main(conffile=None): commands = Commands(conffile) commands.startserver()
def __init__(self, dumper): """Initialize interface.""" super().__init__(None, wx.ID_ANY, 'Конструктор дампов базы данных') self.command = Commands(self, dumper) self.path = '' title_db = 'Выбор базы SQLITE:' wildcard_db = 'sqlite database file (*.db)|*.db|' \ 'All files (*.*)|*.*' self.path_sql = '' title_sql = 'Выбор файла дампа:' wildcard_sql = 'SQL dump file (*.sql)|*.sql|' \ 'All files (*.*)|*.*' panel = wx.Panel(self, wx.ID_ANY) sizer_panel = wx.BoxSizer(wx.HORIZONTAL) sizer_panel.Add(panel, 1, wx.EXPAND | wx.ALL) self.SetSizer(sizer_panel) box_db_browse = wx.StaticBox(panel, wx.ID_ANY, 'База Данных') self.db_ctrl = wx.FilePickerCtrl(box_db_browse, wx.ID_ANY, self.path, title_db, wildcard_db, style=wx.FLP_OPEN | wx.FLP_USE_TEXTCTRL) self.db_ctrl.GetPickerCtrl().SetLabel('Обзор...') self.but_connect = wx.ToggleButton(panel, wx.ID_ANY, 'Подключить') box_tables = wx.StaticBox(panel, wx.ID_ANY, 'Таблицы') self.but_add_table = wx.Button(box_tables, wx.ID_ANY, 'Добавить') self.tables = wx.Choice(box_tables, wx.ID_ANY, choices=[]) box_rows = wx.StaticBox(panel, wx.ID_ANY, 'Записи') self.but_insert = wx.Button(box_rows, wx.ID_ANY, 'Вставить') self.but_update = wx.Button(box_rows, wx.ID_ANY, 'Обновить') self.but_delete = wx.Button(box_rows, wx.ID_ANY, 'Удалить') box_fix = wx.StaticBox(panel, wx.ID_ANY, 'Корректировки') self.mysql = wx.CheckBox(box_fix, wx.ID_ANY, 'Служебные правки') self.drop_table = wx.CheckBox(box_fix, wx.ID_ANY, 'Добавить строку удаления таблицы') self.del_quotes = wx.CheckBox(box_fix, wx.ID_ANY, 'Удалить кавычки вокруг имени таблицы') self.use_db = wx.RadioButton(box_fix, wx.ID_ANY, 'Добавить использование БД', style=wx.RB_GROUP) self.add_db = wx.RadioButton(box_fix, wx.ID_ANY, 'Добавить имя БД перед именем таблицы') box_sql_browse = wx.StaticBox(panel, wx.ID_ANY, 'Файл дампа') self.sql_ctrl = wx.FilePickerCtrl(box_sql_browse, wx.ID_ANY, self.path_sql, title_sql, wildcard_sql, style=wx.FLP_SAVE | wx.FLP_USE_TEXTCTRL) self.sql_ctrl.GetPickerCtrl().SetLabel('Обзор...') self.but_save = wx.Button(panel, wx.ID_ANY, 'Сохранить') but_about = wx.Button(panel, wx.ID_ANY, 'О программе...') but_exit = wx.Button(panel, wx.ID_ANY, 'Выход') sizer = wx.BoxSizer(wx.VERTICAL) db_sizer = wx.BoxSizer(wx.HORIZONTAL) db_browse_sizer = wx.StaticBoxSizer(box_db_browse, wx.VERTICAL) db_browse_sizer.Add(self.db_ctrl, 0, wx.EXPAND | wx.ALL, 5) db_sizer.Add(db_browse_sizer, 1, wx.EXPAND | wx.ALL, 5) db_sizer.Add(self.but_connect, 0, wx.EXPAND | wx.ALL, 5) sizer.Add(db_sizer, 0, wx.EXPAND | wx.ALL) tables_sizer = wx.StaticBoxSizer(box_tables, wx.HORIZONTAL) tables_sizer.Add(self.but_add_table, 0, wx.EXPAND | wx.ALL, 5) tables_sizer.Add(self.tables, 1, wx.EXPAND | wx.ALL, 5) sizer.Add(tables_sizer, 0, wx.EXPAND | wx.ALL) rows_sizer = wx.StaticBoxSizer(box_rows, wx.HORIZONTAL) rows_sizer.Add(self.but_insert, 0, wx.EXPAND | wx.CENTER, 5) rows_sizer.Add(self.but_update, 0, wx.EXPAND | wx.CENTER, 5) rows_sizer.Add(self.but_delete, 0, wx.EXPAND | wx.CENTER, 5) sizer.Add(rows_sizer, 0, wx.EXPAND | wx.ALL) fix_sizer = wx.StaticBoxSizer(box_fix, wx.VERTICAL) fix_sizer.Add(self.mysql, 0, wx.EXPAND | wx.ALL, 5) fix_sizer.Add(self.drop_table, 0, wx.EXPAND | wx.ALL, 5) fix_sizer.Add(self.del_quotes, 0, wx.EXPAND | wx.ALL, 5) fix_sizer.Add(self.use_db, 0, wx.EXPAND | wx.ALL, 5) fix_sizer.Add(self.add_db, 0, wx.EXPAND | wx.ALL, 5) sizer.Add(fix_sizer, 1, wx.EXPAND | wx.ALL) sql_browse_sizer = wx.StaticBoxSizer(box_sql_browse, wx.HORIZONTAL) sql_browse_sizer.Add(self.sql_ctrl, 1, wx.EXPAND | wx.ALL, 5) sizer.Add(sql_browse_sizer, 0, wx.EXPAND | wx.ALL) buttons_sizer = wx.BoxSizer(wx.HORIZONTAL) buttons_sizer.Add(self.but_save, 0, wx.EXPAND | wx.CENTER, 5) buttons_sizer.Add(but_about, 0, wx.EXPAND | wx.CENTER, 5) buttons_sizer.Add(but_exit, 0, wx.EXPAND | wx.CENTER, 5) sizer.Add(buttons_sizer, 0, wx.EXPAND | wx.ALL) panel.SetSizer(sizer) self.Bind(wx.EVT_CLOSE, getattr(self.command, 'close_window')) self.Bind(wx.EVT_FILEPICKER_CHANGED, getattr(self.command, 'db_browse'), self.db_ctrl) self.Bind(wx.EVT_FILEPICKER_CHANGED, getattr(self.command, 'sql_browse'), self.sql_ctrl) self.Bind(wx.EVT_TOGGLEBUTTON, getattr(self.command, 'connect'), self.but_connect) self.Bind(wx.EVT_BUTTON, self.add_table, self.but_add_table) self.Bind(wx.EVT_BUTTON, self.insert, self.but_insert) self.Bind(wx.EVT_BUTTON, self.update, self.but_update) self.Bind(wx.EVT_BUTTON, self.delete, self.but_delete) self.Bind(wx.EVT_BUTTON, getattr(self.command, 'save'), self.but_save) self.Bind(wx.EVT_BUTTON, getattr(self.command, 'about'), but_about) self.Bind(wx.EVT_BUTTON, getattr(self.command, 'close'), but_exit) self.but_connect.SetValue(False) self.mysql.SetValue(True) self.drop_table.SetValue(True) self.del_quotes.SetValue(True) self.use_db.SetValue(True) self.but_add_table.Disable() self.but_insert.Disable() self.but_update.Disable() self.but_delete.Disable() self.but_save.Disable() self.Layout()
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('--client', dest='only_client', action='store_true', help='only process client', default=False) parser.add_option('--server', dest='only_server', action='store_true', help='only process server', default=False) parser.add_option('-j', '--jad', dest='force_jad', action='store_true', help='force use of JAD even if Fernflower available', default=False) parser.add_option( '--rg', dest='force_rg', action='store_true', help='force use of RetroGuard even if SpecialSource available', default=False) parser.add_option('-s', '--csv', dest='force_csv', action='store_true', help='force use of CSVs even if SRGs available', default=False) parser.add_option('-r', '--norecompile', dest='no_recompile', action='store_true', help='disable recompile after decompile', default=False) parser.add_option('-d', '--nocomments', dest='no_comments', action='store_true', help='disable javadoc', default=False) parser.add_option('-a', '--noreformat', dest='no_reformat', action='store_true', help='disable source reformatting', default=False) parser.add_option('-n', '--norenamer', dest='no_renamer', action='store_true', help='disable field and method renaming', default=False) parser.add_option('-l', '--lvt', dest='keep_lvt', action='store_true', help='preserve local variable table', default=False) parser.add_option('-g', '--generics', dest='keep_generics', action='store_true', help='preserve generics as well as local variables', default=False) parser.add_option('-o', '--onlypatch', dest='only_patch', action='store_true', help='only patch source', default=False) parser.add_option('-p', dest='no_patch', action='store_true', help='Undocumented magic', default=False) parser.add_option('-c', '--config', dest='config', help='additional configuration file') parser.add_option( '-w', '--workDir', dest='workdir', help='Change client lookup place (by default, ~/.minecraft)') parser.add_option( '--json', dest='json', help='Location of the json file for none standard installs') parser.add_option('--nocopy', dest='nocopy', action='store_true', help='Do not try to copy assets from minecraft install', default=False) options, _ = parser.parse_args() decompile(options.config, options.force_jad, options.force_csv, options.no_recompile, options.no_comments, options.no_reformat, options.no_renamer, options.no_patch, options.only_patch, options.keep_lvt, options.keep_generics, options.only_client, options.only_server, options.force_rg, options.workdir, options.json, options.nocopy)
class TestLighterer(unittest.TestCase): def setUp(self): cls = build_lighterer_mock() with patch('lighterer.Lighterer', cls): self.commands = Commands('fake', 0, None, None) def test_aliases(self): # null string alias pub = ('03aa434d9ff5d5470033aa654f201dbbd' 'ce79955c61e9e48a6674d203ae3b689f5') self.assertEqual(self.commands._alias(pub, pub), pub) self.assertNotEqual(self.commands._alias(pub), pub) # mani = ('03db61876a9a50e5724048170aeb14f00' # '96e503def38dc149d2a4ca71efd95a059') # self.assertEqual(self.commands._alias(mani), 'mani_al_cielo') false = ('020000000000000000000000000000000' '000000000000000000000000000000000') self.assertEqual(self.commands._alias(false, false), false) with open('cities.txt', 'rt') as fd: cities = [x.strip() for x in fd.readlines()] self.assertIn(self.commands._alias(false).split(maxsplit=1)[1], cities) CITYSCAPE = '\U0001f3d9' CITY_DUSK = '\U0001f306' # TODO: test both conditions if self.commands.aliases: self.assertEqual(self.commands._alias(false).split()[0], CITY_DUSK) else: self.assertEqual(self.commands._alias(false).split()[0], CITYSCAPE) def test_cities_file(self): """cities.txt must be ascii encoded""" with open('cities.txt', 'rt') as fd: data = fd.readlines() for city in data: try: city.encode('ascii') except UnicodeEncodeError: self.fail('{} is not ascii encoded'.format(city.strip())) def test_private_chs(self): self.assertNotIn(PRIVATE, ''.join( self.commands.channels())) self.assertNotIn(PRIVATE, self.commands.chs()) cls = build_lighterer_mock('private') with patch('lighterer.Lighterer', cls): private = Commands('fake', 0, None, None) self.assertIn(PRIVATE, ''.join( private.channels())) self.assertIn(PRIVATE, private.chs()) def test_active_flag(self): """chs and channels commands are involved""" # Case 0: all the channels are active output = '\n'.join(self.commands.channels()) occ_channels = output.count(ACTIVE) self.assertIn(ACTIVE, output) self.assertNotIn(NACTIVE, output) output = self.commands.chs() occ_chs = output.count(ACTIVE) self.assertIn(ACTIVE, output) self.assertNotIn(NACTIVE, output) self.assertEqual(occ_channels, occ_chs) # Case 1: 1 active ch and 1 not active ch # channels and chs call get: # - all channels # - active channels cls = build_lighterer_mock(None, 'active') with patch('lighterer.Lighterer', cls): active = Commands('fake', 0, None, None) output = '\n'.join(active.channels()) self.assertEqual(output.count(ACTIVE), 1) self.assertEqual(output.count(NACTIVE), 1) @patch('requests.get') def test_commands(self, mock_get): mock_get.return_value = FakeRequests() uri = self.commands._lit.getinfo().node_uri self.assertIn(uri, self.commands.info()) self.assertIn(uri, self.commands.uri()) self.commands.add() self.commands.add('123') self.commands.add('0.001') self.commands.add('7') self.commands.add('6.7€') self.commands.add('6.8e') self.commands.add('6.9E') self.commands.balance() self.assertIsInstance(self.commands.channels(pending=False), list) # Not implemented # self.assertIsInstance(self.commands.channels(pending=True), list) self.assertIsInstance(self.commands.pending(), list) self.commands.chs() self.commands.is_pay_req(PAY_REQ) assert re.match('^(bc|tb)1', self.commands.address()) self.commands.pay(PAY_REQ) self.commands.pay(PAY_REQ, '0.001') self.commands.pay(PAY_REQ, '7') self.commands.pay(PAY_REQ, '6.7€') self.commands.pay(PAY_REQ, '6.8e') self.commands.pay(PAY_REQ, '6.9E') self.commands.pay(PROTOCOL + PAY_REQ) self.assertEqual(len(self.commands.add('1.23')), 2) self.assertEqual(len(self.commands.channels(pending=False)), 2) # self.assertEqual(len(self.commands.channels(pending=True)), 7) # self.assertEqual(len(self.commands.pending()), 1) self.assertEqual(len(self.commands.channels('no-one', False)), 0) self.assertEqual(len(self.commands.channels('03db61876a9a50e5', False)), 1) self.assertEqual(len(self.commands.channels('03db61876a', False)), 1) def test_cmd_payment(self): PAID = '\U0001f44d' NOT_PAID = '\U0001f44e' NOT_FOUND = 'Invoice not found' # Random r hash. Mock does not check the hash value r_hash = '86' * 32 no_hash = '67' * 32 self.assertIn(PAID, self.commands.payment(r_hash)) self.assertIn(PAID, self.commands.payment()) cls = build_lighterer_mock('notfound') with patch('lighterer.Lighterer', cls): notfound = Commands('fake', 0, None, None) self.assertIn(NOT_FOUND, notfound.payment(no_hash)) # Load unpaid mock cls = build_lighterer_mock('unpaid') with patch('lighterer.Lighterer', cls): unpaid = Commands('fake', 0, None, None) self.assertIn(NOT_PAID, unpaid.payment(r_hash)) self.assertIn(NOT_PAID, unpaid.payment()) # TODO: check the order of invoices r_last = cls().listinvoices()[0].payment_hash self.assertIn(self.commands.payment().split()[0], (PAID, NOT_PAID)) self.assertIn(r_last, self.commands.payment()) # Expiration tests # TODO: next version of payment command # self.assertIn('Expired on', self.commands.payment()) # self.assertNotIn('Settled on', self.commands.payment()) # self.assertNotIn('Expires', self.commands.payment(r_hash)) # self.assertIn('Settled on', self.commands.payment(r_hash)) def test_decode(self): enc_payreq = self.commands.add('1.23')[0] dec_payreq = self.commands.decode(enc_payreq) # self.assertIn('To ', dec_payreq) -> Aliases are not supported yet self.assertIn('Pubkey ', dec_payreq) self.assertIn('Amount ', dec_payreq) self.assertIn('Description ', dec_payreq) self.assertIn('Created on ', dec_payreq) self.assertIn('Expires ', dec_payreq) # TODO: test expired # Optional outputs cls = build_lighterer_mock('nodescription') with patch('lighterer.Lighterer', cls): nodesc = Commands('fake', 0, None, None) dec_payreq = nodesc.decode(enc_payreq) self.assertNotIn('Description ', dec_payreq) # TODO: implement aliases # Test: invoice without alias # self.assertNotIn('To ', dec_payreq) def test_decode_error(self): cls = build_lighterer_mock('error') with patch('lighterer.Lighterer', cls): error = Commands('fake', 0, None, None) self.assertIn('This is not a payment request', error.decode('No'))
def setUp(self): cls = build_lighterer_mock() with patch('lighterer.Lighterer', cls): self.commands = Commands('fake', 0, None, None)
class PupyCmd(cmd.Cmd): def __init__(self, pupsrv): cmd.Cmd.__init__(self) self.pupsrv = pupsrv self.dnscnc = pupsrv.dnscnc self.pupsrv.register_handler(self) self.config = pupsrv.config self.input = sys.stdin self.output = sys.stdout self.commands = Commands() self.display_lock = Lock() self.init_readline() self._intro = [ Color(BANNER, 'green'), Indent(Color(UPSTREAM, 'cyan')), Indent(Color(DISCLAIMER, 'lightred')) ] self.raw_prompt = colorize('>> ', 'blue') self.prompt = colorize('>> ', 'blue', prompt=True) self.default_filter = None try: if not self.config.getboolean("cmdline", "display_banner"): self._intro = [] except Exception: pass self.aliases = {} for m, _ in self.pupsrv.get_aliased_modules(): self.aliases[m] = m try: for command, alias in self.config.items("aliases"): logger.debug("adding alias: %s => %s" % (command, alias)) self.aliases[command] = alias except: logger.warning("error while parsing aliases from pupy.conf ! %s", traceback.format_exc()) @property def intro(self): return '\n'.join(hint_to_text(x) for x in self._intro) def add_motd(self, motd={}): for ok in motd.get('ok', []): self._intro.append(ServiceInfo(ok + '\n')) for fail in motd.get('fail', []): self._intro.append( Error(fail + '\n') if not issubclass(type(fail), Text) else fail) def default(self, line): return self.execute(line) def inject(self, line, clients_filter, message=None): self.display_srvinfo(message or 'Inject: {}'.format(line)) self.execute(line, clients_filter) self.display_srvinfo('Action complete') def execute(self, line, clients_filter=None): if line.startswith('!'): os.system(line[1:]) return try: self.commands.execute(self.pupsrv, self, self.pupsrv.config, line, clients_filter) self.completion_matches = None except PupyModuleUsageError, e: prog, message, usage = e.args self.display(Line(Error(message, prog))) self.display(usage) except PupyModuleExit: pass
def connect(self, api_url, username, password, insecure=False): self._cmds = Commands(Client(api_url, username, password, insecure)) self._cmds.set_debug(self._debug)
def main(conffile): commands = Commands(conffile) commands.logger.info ('== Reobfuscating client ==') if commands.checkbins(0): commands.cleanreobfdir(0) commands.logger.info ('> Gathering md5 checksums') commands.gathermd5s(0,True) commands.logger.info ('> Compacting client bin directory') commands.packbin(0) commands.logger.info ('> Reobfuscating client jar') commands.reobfuscate(0) commands.logger.info ('> Extracting modified classes') commands.unpackreobfclasses(0) commands.logger.info ('== Reobfuscating server ==') if commands.checkbins(1): commands.cleanreobfdir(1) commands.logger.info ('> Gathering md5 checksums') commands.gathermd5s(1,True) commands.logger.info ('> Compacting server bin directory') commands.packbin(1) commands.logger.info ('> Reobfuscating server jar') commands.reobfuscate(1) commands.logger.info ('> Extracting modified classes') commands.unpackreobfclasses(1)
logger.error("cannot get list of projects") sys.exit(1) else: directory = args.directory for entry in os.listdir(directory): if path.isdir(path.join(directory, entry)): dirs_to_process.append(entry) logger.debug("to process: {}".format(dirs_to_process)) projects = [] for d in dirs_to_process: proj = CommandsBase(d, config.get("commands"), config.get("cleanup")) projects.append(proj) try: projects = pool.map(worker, projects, 1) except KeyboardInterrupt: # XXX lock.release() or return 1 ? sys.exit(1) else: for proj in projects: logger.debug("Checking results of project {}".format(proj)) cmds = Commands(proj) cmds.fill(proj.retcodes, proj.outputs, proj.failed) cmds.check(ignore_errors) except Timeout: logger.warning("Already running, exiting.") sys.exit(1)
def recompile(conffile=None): commands = Commands(conffile) try: commands.logger.info('> Recompiling client...') clienttime = time.time() if commands.checksources(CLIENT): commands.cleanbindirs(CLIENT) commands.recompile(CLIENT) commands.logger.info('> Done in %.2f seconds' % (time.time() - clienttime)) commands.logger.info('> Recompiling server...') servertime = time.time() if commands.checksources(SERVER): commands.cleanbindirs(SERVER) commands.recompile(SERVER) commands.logger.info('> Done in %.2f seconds' % (time.time() - servertime)) except Exception: # pylint: disable-msg=W0703 commands.logger.exception('FATAL ERROR') sys.exit(1)
class Agent: def __init__(self): # Load configuration with open('config/config.json') as f: config = json.load(f) self._config = config # Do logger self._setup_logger() logger.info('HardwareID={}'.format(get_cpu_id())) # GPIOs GPIO.setmode(GPIO.BCM) self._go = False self._temp_sensors = Max31850Sensors(self._config['temperature']) self._blower_fan = BlowerFan(self._config['fan']) # Our MQTT client self._client = mqtt_client.Client(client_id=get_cpu_id()) # Data logger self._data_logger = DataLogger(config['data_logger']['path'], get_cpu_id()) # IController self._controller = TempController(self._config, self._temp_sensors, self._blower_fan, self._client, self._data_logger) self._commands = Commands(self._config, self._client, self._data_logger) def _setup_logger(self): # Setup logger root = logging.getLogger() level = self._config['logger']['level'] root.setLevel(level) ch = logging.StreamHandler(sys.stdout) ch.setLevel(level) formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s') ch.setFormatter(formatter) root.addHandler(ch) def initialise(self): logger.info('Initialising.') # Connect to MQTT self._client.on_connect = self._on_connect self._client.connect_async(host=self._config["mqtt"]["broker_host"], port=self._config["mqtt"]["broker_port"]) self._client.loop_start() # Initialise controller self._controller.initialise() self._commands.init() def run(self): self._go = True self._control_loop() def terminate(self): # Causes the control loop to stop self._go = False self._controller.stop() self._client.loop_stop() # We are done with GPIOs. GPIO.cleanup() # Terminates communications. self._client.disconnect() logger.info('Control loop terminated.') def _control_loop(self): logger.info('Running control loop.') pacer = Pacer() self._controller.start() try: while self._go: now = time.time() # Tick controller self._controller.tick(now) # Pace control loop per desired interval try: pacer.pace( now, self._config['intervals']['control_loop_second']) except KeyboardInterrupt: self._go = False finally: self.terminate() def _on_connect(self, client, userdata, flags, rc): logger.info('MQTT Connected with result code ' + str(rc)) # Subscribe to our control topics now that we have a connection root_topic = self._config['mqtt']['root_topic'] + get_cpu_id() + "/#" client.subscribe(root_topic) def _on_disconnect(self, client, userdata, rc): logger.info('MQTT Disonnected with result code ' + str(rc))
def decompile(conffile=None, force_jad=False): commands = Commands(conffile) try: commands.checkupdates() cltdone = False srvdone = False use_ff = os.path.exists(commands.fernflower) and not force_jad commands.logger.info('> Creating Retroguard config files') commands.creatergcfg() srcdir = os.path.join(commands.srcclient, os.path.normpath(commands.ffsource)) if not os.path.exists(srcdir): commands.logger.info('== Decompiling Client ==') if commands.checkjars(CLIENT): clienttime = time.time() commands.logger.info('> Creating SRGS for client') commands.createsrgs(CLIENT) commands.logger.info('> Applying Retroguard to client') commands.applyrg(CLIENT) commands.logger.info('> Applying Exceptor to client') commands.applyexceptor(CLIENT) if use_ff: commands.logger.info('> Decompiling...') commands.applyff(CLIENT) commands.logger.info('> Unzipping the client sources') commands.extractsrc(CLIENT) commands.logger.info('> Unzipping the client jar') commands.extractjar(CLIENT) if not use_ff: commands.logger.info('> Applying jadretro') commands.applyjadretro(CLIENT) commands.logger.info('> Decompiling...') commands.applyjad(CLIENT) commands.logger.info('> Copying the client sources') commands.copysrc(CLIENT) commands.logger.info('> Applying patches') if commands.osname == 'osx' and not use_ff: commands.applypatches(CLIENT, False, True) commands.applypatches(CLIENT, use_ff) commands.logger.info('> Removing comments') commands.process_comments(CLIENT) commands.logger.info('> Renaming sources') commands.process_rename(CLIENT) commands.logger.info('> Reformating sources') commands.applyastyle(CLIENT) commands.logger.info('> Commenting OpenGL constants') commands.process_annotate(CLIENT) commands.logger.info('> Creating reobfuscation tables') commands.renamereobsrg(CLIENT) commands.logger.info('> Done in %.2f seconds' % (time.time() - clienttime)) else: commands.logger.warn( '!! Client already decompiled. Run cleanup before decompiling again !!' ) cltdone = True srcdir = os.path.join(commands.srcserver, os.path.normpath(commands.ffsource)) if not os.path.exists(srcdir): commands.logger.info('== Decompiling Server ==') if commands.checkjars(SERVER): servertime = time.time() commands.logger.info('> Creating SRGS for server') commands.createsrgs(SERVER) commands.logger.info('> Applying Retroguard to server') commands.applyrg(SERVER) commands.logger.info('> Applying Exceptor to server') commands.applyexceptor(SERVER) if use_ff: commands.logger.info('> Decompiling...') commands.applyff(SERVER) commands.logger.info('> Unzipping the server sources') commands.extractsrc(SERVER) commands.logger.info('> Unzipping the server jar') commands.extractjar(SERVER) if not use_ff: commands.logger.info('> Applying jadretro') commands.applyjadretro(SERVER) commands.logger.info('> Decompiling...') commands.applyjad(SERVER) commands.logger.info('> Copying the server sources') commands.copysrc(SERVER) commands.logger.info('> Applying patches') if commands.osname == 'osx' and not use_ff: commands.applypatches(SERVER, False, True) commands.applypatches(SERVER, use_ff) commands.logger.info('> Removing comments') commands.process_comments(SERVER) commands.logger.info('> Renaming sources') commands.process_rename(SERVER) commands.logger.info('> Reformating sources') commands.applyastyle(SERVER) commands.logger.info('> Creating reobfuscation tables') commands.renamereobsrg(SERVER) commands.logger.info('> Done in %.2f seconds' % (time.time() - servertime)) else: commands.logger.warn( '!! Server already decompiled. Run cleanup before decompiling again !!' ) srvdone = True commands.logger.info('== Post decompiling operations ==') if not cltdone or not srvdone: commands.logger.info('> Recompiling') recompile(conffile) if not cltdone: commands.logger.info('> Generating the md5 (client)') commands.gathermd5s(CLIENT) if not srvdone: commands.logger.info('> Generating the md5 (server)') commands.gathermd5s(SERVER) except Exception: # pylint: disable-msg=W0703 commands.logger.exception('FATAL ERROR') sys.exit(1)
def __initialize(self): """ Initialize - add to the window (root) all the labels, button and combo-boxes and bind them to their functions :return: """ # if debug mode is on, print that right now initializing the gui if self.__DEBUG: print >> sys.__stdout__, "Initializing The GUI" # change the root's background color self.__root.configure(background='black') self.__root.title("Command Center") # add the title title_label = Tk.Label(self.__root, justify=Tk.LEFT, font=FONT, text=""" _____ _____ _______ _______ _______ __ _ ______ ______ _______ __ _ _______ _______ ______ | | | | | | | | | |_____| | \ | | \ | |______ | \ | | |______ |_____/ |_____ |_____| | | | | | | | | | \_| |_____/ |_____ |______ | \_| | |______ | \_ """) title_label.configure(background='black', foreground='green') title_label.grid(row=0, column=0, columnspan=2) # add the style combostyle = ttk.Style() combostyle.theme_create('combostyle', parent='alt', settings={'TCombobox': { 'configure': {'selectbackground': 'black', 'fieldbackground': 'black', 'background': 'green', 'foreground': 'green'}}}) # ATTENTION: this applies the new style 'combostyle' to all ttk.Combobox combostyle.theme_use('combostyle') # add the peasant's ip (label and combo box) peasant_label = Tk.Label(self.__root, text="Peasant Address:", font=FONT) peasant_label.configure(background='black', foreground='green') peasant_label.grid(row=1, column=0) peasant_combobox = ttk.Combobox(self.__root, state="readonly", values=[], font=FONT) peasant_combobox.grid(row=1, column=1) peasant_combobox.configure(background='black', foreground='green') self.__comboboxes['peasant'] = peasant_combobox # add the command (label and combo box) command_label = Tk.Label(self.__root, text="Command:", font=FONT) command_label.configure(background='black', foreground='green') command_label.grid(row=2, column=0) command_combobox = ttk.Combobox(self.__root, state="readonly", values=Commands.get_commands_names(), font=FONT) command_combobox.configure(background='black', foreground='green') command_combobox.grid(row=2, column=1) self.__comboboxes['command'] = command_combobox # add the send button send_button = Tk.Button(self.__root, text="Send", font=FONT) send_button.configure(background='black', foreground='green') send_button.grid(row=10, column=0, columnspan=2) # add the output highlight-able text output = HighlightText(self.__root, state=Tk.DISABLED, font=FONT) output.config(state=Tk.DISABLED, font=FONT) output.configure(background='black', foreground='green', width=100) output.grid(row=11, column=0, columnspan=2) # add the red highlight tag output.tag_configure("red", foreground="red") # add the red highlight tag output.tag_configure("blue", foreground="blue") # print to the screen a welcome message output.config(state=Tk.NORMAL) output.insert(Tk.END, """_ _ _ ___ _ ___ ____ _ _ ___ _ _ ____ ____ ___ ___ ____ | | | |___ | | | | |\/| |___ |\/| |__| [__ | |___ |__/ |_|_| |___ |___ |___ |__| | | |___ | | | | ___] | |___ | \ \n""") output.config(state=Tk.DISABLED) # set the member output to be the output we just used self.__output = output # bind the command combo-box and the send button to their respective callback functions command_combobox.bind("<<ComboboxSelected>>", lambda event=None: self.__command_callback( root=self.__root, command=self.__comboboxes['command'].get(), entries=self.__entries, re_grid=[send_button, output])) send_button.bind("<Button-1>", lambda event=None: self.__send_enhance_callback([send_button, output])) # weight the grid for col in range(self.__root.grid_size()[0]): self.__root.grid_columnconfigure(col, weight=1) for row in range(self.__root.grid_size()[1]): self.__root.grid_rowconfigure(row, weight=1)
class Logbot(SingleServerIRCBot): def __init__(self, server, port, server_pass=None, channels=[], nick="pelux", nick_pass=None): SingleServerIRCBot.__init__(self, [(server, port, server_pass)], nick, nick) self.chans = [x.lower() for x in channels] self.set_ftp() self.nick_pass = nick_pass self.commands = Commands() print("Logbot %s" % __version__) print("Connecting to %s:%i..." % (server, port)) print("Press Ctrl-C to quit") def quit(self): self.connection.disconnect("Quitting...") def color(self, user): return "#%s" % md5(user.encode()).hexdigest()[:6] def set_ftp(self, ftp=None): self.ftp = ftp def write_event(self, event_name, event, params={}): target = event.target() if event_name == "nick": message = params["new"] target = params["chan"] elif event_name == "kick": message = "%s kicked %s from %s. Reason: %s" % (nm_to_n( params["kicker"]), params["user"], params["channel"], params["reason"]) elif event_name == "mode": message = "%s changed mode on %s: %s" % ( params["giver"], params["person"], params["modes"]) elif event_name == "quit": target = params["chan"] message = "%s has quit" % nm_to_n(event.source()) elif len(event.arguments()) > 0: message = event.arguments()[0] else: message = "" add_log_message(target, nm_to_n(event.source()), event_name, message) def check_for_prs(self, c): p = PullRequest() for line in p.check_all(): message = line["message"] channel = line["channel"] c.privmsg(channel, message) time.sleep(1) Timer(60 * 5, self.check_for_prs, [c]).start() ### These are the IRC events def on_all_raw_messages(self, c, e): """Display all IRC connections in terminal""" if DEBUG: print(e.arguments()[0]) def on_welcome(self, c, e): """Join channels after successful connection""" if self.nick_pass: c.privmsg("nickserv", "identify %s" % self.nick_pass) for chan in self.chans: c.join(chan) self.check_for_prs(c) def on_nicknameinuse(self, c, e): """Nickname in use""" c.nick(c.get_nickname() + "_") def on_invite(self, c, e): """Arbitrarily join any channel invited to""" c.join(e.arguments()[0]) #TODO: Save? Rewrite config file? ### Loggable events def on_action(self, c, e): """Someone says /me""" self.write_event("action", e) def on_join(self, c, e): self.write_event("join", e) def on_kick(self, c, e): self.write_event( "kick", e, { "kicker": e.source(), "channel": e.target(), "user": e.arguments()[0], "reason": e.arguments()[1], }) def on_mode(self, c, e): self.write_event( "mode", e, { "modes": e.arguments()[0], "person": e.arguments()[1] if len(e.arguments()) > 1 else e.target(), "giver": nm_to_n(e.source()), }) def on_nick(self, c, e): old_nick = nm_to_n(e.source()) # Only write the event on channels that actually had the user in the channel for chan in self.channels: if old_nick in [ x.lstrip('~%&@+') for x in self.channels[chan].users() ]: self.write_event("nick", e, { "old": old_nick, "new": e.target(), "chan": chan, }) def on_part(self, c, e): self.write_event("part", e) def on_pubmsg(self, c, e): # if e.arguments()[0].startswith(NICK): # c.privmsg(e.target(), self.format["help"]) self.commands.process(c, e) self.write_event("pubmsg", e) def on_pubnotice(self, c, e): self.write_event("pubnotice", e) def on_privmsg(self, c, e): # c.privmsg(nm_to_n(e.source()), self.format["help"]) pass def on_quit(self, c, e): nick = nm_to_n(e.source()) # Only write the event on channels that actually had the user in the channel for chan in self.channels: if nick in [ x.lstrip('~%&@+') for x in self.channels[chan].users() ]: self.write_event("quit", e, {"chan": chan}) def on_topic(self, c, e): self.write_event("topic", e)
session = vk_api.VkApi(app_id=config.app_id, token=config.token) session_group = vk_api.VkApi(token=config.bot_token) session.RPS_DELAY = 1 api = session.get_api() bot_api = session_group.get_api() bot = VkBotLongPoll(vk=session_group, group_id=config.group_id) print('Bot was started in', datetime.today()) config.log_to_file('out_sorry.log', 'Bot was started in') bot_api.messages.send(user_id=config.me, message=('Bot was started in ' + datetime.today().__str__()), random_id=randint(0, 999999999)) processing = Commands(api, auto_read, session, bot_api, bot, db) while True: try: for event in bot.listen(): if event.type == VkBotEventType.MESSAGE_NEW: db.add_user_to_db(event.object.peer_id) if len(event.object.attachments ) == 0 and event.object.text[0] == '/': processing.bot_api.messages.setActivity( user_id=event.object.peer_id, type='typing') processing.commands(event) if len(processing.people) < 25: processing.search_people() elif event.type == VkBotEventType.MESSAGE_ALLOW:
class Mission(): def __init__(self): rospy.init_node("test_mission", log_level=rospy.INFO) #initialize the pixhawk node print('node initialized') self.rate = rospy.Rate(10) self.subs = Subscribers() #initialize streaming of subscribers self.comp = Computations() self.commands = Commands() self.navigation = Navigation() self.arrow = Arrow() #object for arrow detection class self.road_follow = RoadFollow() #object for road detection class #initialize the publishers self.setpoint_publisher = rospy.Publisher( "/mavros/setpoint_position/local", PoseStamped, queue_size=10) self.setvel_publisher = rospy.Publisher( "/mavros/setpoint_velocity/cmd_vel", TwistStamped, queue_size=10) self.setaccel_publisher = rospy.Publisher( "/mavros/setpoint_accel/accel", Vector3Stamped, queue_size=10) print('Publishers initialized') def stillActive(self): return (self.subs.state.mode == 'OFFBOARD') def arrowDetection(self): #arrow detection ''' delta_orientation=1000 #initialize the change in orientation self.commands.set_mode('AUTO.LOITER') #change mode to hold mode rate.sleep() cv2.imwrite('Images123/image1.jpg', self.subs.cv_image ) while(delta_orientation ==1000): #loop to wait for drone to see the arrow print(self.subs.state.mode) #failsafe if(self.subs.state.mode != 'AUTO.LOITER' and self.subs.state.mode != 'OFFBOARD'): return delta_orientation=self.arrow.arrow_angle(self.subs.cv_image)#get change in orientation self.comp.send_arb_waypoints() self.commands.set_mode('OFFBOARD') #move to offboard mode print(delta_orientation) self.comp.change_orientation(delta_orientation) #rotate the drone to the desired arrow orientation rate.sleep() cv2.imwrite('Images123/image.jpg', self.subs.cv_image) #save image for scrutiny rate.sleep() #road following self.delta=1000 #initialize the next waypoint angle #self.commands.set_mode('AUTO.LOITER') #change later after making road following robust #rate.sleep() while(self.delta==1000): #loop to go through to check if image is received #failsafe if(self.subs.state.mode != 'AUTO.LOITER' and self.subs.state.mode != 'OFFBOARD'): return cv2.imwrite('Images123/image.jpg', self.subs.cv_image) #save image for scrutiny self.delta=self.road_follow.getRoadAngle(self.subs.cv_image)#get the change in the road's orientation print(self.delta) #self.comp.send_arb_waypoints() #self.commands.set_mode('OFFBOARD') #change later after making road following robust self.comp.road_next_waypoint(self.delta) #compute the next waypoint and the orientation if(True): self.commands.land() else: return ''' def choose_mission(self): print( 'Choose a mission:\n1. Drone take off and land\n2.Drone make a square\n3. Arrow detectiona and road follow' ) val = input('Enter a value:') self.way_mission(val) #main function for the drone mission def way_mission(self, val): self.comp.send_arb_waypoints( ) #send arbitary number of waypoints for changing to offboard mode self.commands.set_mode('OFFBOARD') #set mode to offboard if (self.stillActive()): print('going to waypoint') if val == 1: self.navigation.waypoint(self.subs.pose.pose.position.x, self.subs.pose.pose.position.y, self.subs.pose.pose.position.z + 3) print('Takeoff completed') if val == 2: self.navigation.waypoint(self.subs.pose.pose.position.x, self.subs.pose.pose.position.y, self.subs.pose.pose.position.z + 3) print('Takeoff completed') self.navigation.waypoint(self.subs.pose.pose.position.x + 10, self.subs.pose.pose.position.y, self.subs.pose.pose.position.z) self.navigation.waypoint(self.subs.pose.pose.position.x, self.subs.pose.pose.position.y + 10, self.subs.pose.pose.position.z) self.navigation.waypoint(self.subs.pose.pose.position.x - 10, self.subs.pose.pose.position.y, self.subs.pose.pose.position.z) self.navigation.waypoint(self.subs.pose.pose.position.x, self.subs.pose.pose.position.y - 10, self.subs.pose.pose.position.z) #if val == 3: # self.navigation.waypoint(self.subs.pose.pose.position.x,self.subs.pose.pose.position.y,self.subs.pose.pose.position.z+3) # print('Takeoff completed') # arrowDetection() else: print('exiting coz mode not changed') return ''' #arrow detection delta_orientation=1000 #initialize the change in orientation self.commands.set_mode('AUTO.LOITER') #change mode to hold mode rate.sleep() cv2.imwrite('Images123/image1.jpg', self.subs.cv_image ) while(delta_orientation ==1000): #loop to wait for drone to see the arrow print(self.subs.state.mode) #failsafe if(self.subs.state.mode != 'AUTO.LOITER' and self.subs.state.mode != 'OFFBOARD'): return delta_orientation=self.arrow.arrow_angle(self.subs.cv_image)#get change in orientation self.comp.send_arb_waypoints() self.commands.set_mode('OFFBOARD') #move to offboard mode print(delta_orientation) self.comp.change_orientation(delta_orientation) #rotate the drone to the desired arrow orientation rate.sleep() cv2.imwrite('Images123/image.jpg', self.subs.cv_image) #save image for scrutiny rate.sleep() #road following self.delta=1000 #initialize the next waypoint angle #self.commands.set_mode('AUTO.LOITER') #change later after making road following robust #rate.sleep() while(self.delta==1000): #loop to go through to check if image is received #failsafe if(self.subs.state.mode != 'AUTO.LOITER' and self.subs.state.mode != 'OFFBOARD'): return cv2.imwrite('Images123/image.jpg', self.subs.cv_image) #save image for scrutiny self.delta=self.road_follow.getRoadAngle(self.subs.cv_image)#get the change in the road's orientation print(self.delta) #self.comp.send_arb_waypoints() #self.commands.set_mode('OFFBOARD') #change later after making road following robust self.comp.road_next_waypoint(self.delta) #compute the next waypoint and the orientation if(True): self.commands.land() else: return ''' if (self.stillActive()): self.commands.land() else: return def main(self): #rate = rospy.Rate(10) while (self.subs.state.armed != True): #check if armed continue print("Armed") while (1): if (self.subs.state.mode == 'AUTO.LOITER' ): #failsafe(will enter only if position) self.choose_mission() #call the main mission break else: continue
def find_replies(): #We have to turn the obtained string into a json object to obtain #the data that is inside. message = json.loads(request.form['payload']) #BLOCK interaction and also check if verification token is correct. if message['type'] == 'block_actions' and message[ 'token'] == verification_token: print('message of block action:') print(message) #actions is a list so we also parse that. message_action = message['actions'][0] #declaration of the input json channel_id = message['container']['channel_id'] message_ts = message['container']['message_ts'] user_id = message['user']['id'] trigger_id = message['trigger_id'] print('message_action:') print(message_action) #Here we check what kind of message it is. This is from an option menu. #An example of this is the /helpme command. #info locals: https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists if message_action['action_id'] == 'action_helpme': #this is how we get the value out of it. message_value = message_action['selected_option']['value'] #here we check what value is inside of it and create interactivity if message_value == '!trello': #you can also return the user id so it send him a pm. commands = Commands(user_id) message = commands.get_message_trello() answer = slack_web_client.chat_postMessage( channel=user_id, text= "Here is some information of how i can be used with Trello:" ) return ("", 200) elif message_value == '!review': commands = Commands(user_id) message = commands.get_message_review() slack_web_client.chat_postMessage(**message) return ("", 200) elif message_value == '!meeting': commands = Commands(user_id) message = commands.get_meeting_planner() slack_web_client.views_open(trigger_id=trigger_id, view=message) return ("", 200) elif message_value == '!sentiment': commands = Commands(user_id) message = commands.get_sentiment_modal() slack_web_client.views_open(response_action="clear", trigger_id=trigger_id, view=message) return ("", 200) #if it is this action we know its a "approve block" elif message_action['action_id'] == 'approve_request_sentiment': #Show sentiment approval modal. commands = Commands(user_id) message = commands.get_approved_sentiment() slack_web_client.views_open(trigger_id=trigger_id, view=message) return ("", 200) elif message_action['action_id'] == 'deny_request_sentiment': #if they dont want to submit a form. commands = Commands(user_id) message = commands.get_feedback_block() slack_web_client.chat_postMessage(**message) return ("", 200) elif message_action['action_id'] == 'request_info_sentiment': commands = Commands(user_id) message = commands.get_info_sentiment() slack_web_client.views_open(trigger_id=trigger_id, view=message) return ("", 200) #when this gets called it means that the AI predicted #the sentiment correctly -> Positive feedback loop. elif message_action['action_id'] == 'last_prediction_positive': return ("", 200) #this means that the last prediction was negative (auto feedback) elif message_action['action_id'] == 'last_prediction_negative': return ("", 200) #check if it comes from a submitted modal & accept verification token elif message['type'] == 'view_submission' and message[ 'token'] == verification_token: print('message of view submission') #retrieve the title of the modal to know which one it is. submit_name = message['view']['title']['text'] test = message['view']['state']['values'].values() user_id = message['user']['id'] trigger_id = message['trigger_id'] print("trigger Id :") print(trigger_id) #if then name of the modal is sentiment then do this if statement. if submit_name == "Sentiment": #nadenken over wat we met die info willen doen #bericht sturen naar HR? Indien ja navragen aan persoon #of dat oké is ,.... """commands = Commands(user_id) messageZ = commands.get_specific_sentiment_info() slack_web_client.views_push( response_action = "push", trigger_id = trigger_id, view = messageZ )""" return ("", 200) elif submit_name == "Sentiment Info": return ("", 200) else: return ("", 200)
def main(conffile, force=False): commands = Commands(conffile) commands.logger.info('== Updating MCP ==') commands.downloadupdates(force)
def decompile(conffile, force_jad, force_csv, no_recompile, no_comments, no_reformat, no_renamer, no_patch, only_patch, keep_lvt, keep_generics, only_client, only_server, force_rg, workdir, json, nocopy): try: commands = Commands(conffile, verify=True, no_patch=no_patch, workdir=workdir, json=json) commands.checkupdates() if not commands.has_ss: force_rg = True use_ff = commands.has_ff and not force_jad use_srg = commands.has_srg and not force_csv if force_jad and not commands.has_jad: commands.logger.error('!! forcing jad when not available !!') sys.exit(1) if force_rg and not commands.has_rg: commands.logger.error( '!! forcing retroguard when not available !!') sys.exit(1) if force_csv and not commands.has_map_csv: commands.logger.error('!! forcing csvs when not available !!') sys.exit(1) # client or server process_client = True process_server = True if only_client and not only_server: process_server = False if only_server and not only_client: process_client = False # always strip comments by default, turn off in update mode if required strip_comments = True # update only options rg_update = False exc_update = False if no_patch: # no_patch is basically update mode, disables everything # and reuses a few different options to do update stuff if only_patch: # with only_patch then we actually do the patches, but not the comment stripping, for use when updating # the fernflower patches no_patch = False strip_comments = False if no_reformat: # reuse -a no_reformat to switch rg to fullmap=1 startindex=RGIndex rg_update = True if no_renamer: # reuse -n to switch mcinjector to outputing exc file, and adding new parameters exc_update = True no_comments = True no_reformat = True no_renamer = True no_recompile = True elif only_patch: # if only_patch then disable everything but patching and comment stripping no_comments = True no_reformat = True no_renamer = True no_recompile = True # if we have generics enabled we need the lvt as well if keep_generics: keep_lvt = True if force_rg: commands.logger.info('> Creating Retroguard config files') commands.creatergcfg(reobf=False, keep_lvt=keep_lvt, keep_generics=keep_generics, rg_update=rg_update) if not nocopy: clientCopy.copyClientAssets(commands, workdir) try: if process_client: cltdecomp = decompile_side(commands, CLIENT, use_ff=use_ff, use_srg=use_srg, no_comments=no_comments, no_reformat=no_reformat, no_renamer=no_renamer, no_patch=no_patch, strip_comments=strip_comments, exc_update=exc_update, keep_lvt=keep_lvt, keep_generics=keep_generics, force_rg=force_rg) else: cltdecomp = False if process_server: srvdecomp = decompile_side(commands, SERVER, use_ff=use_ff, use_srg=use_srg, no_comments=no_comments, no_reformat=no_reformat, no_renamer=no_renamer, no_patch=no_patch, strip_comments=strip_comments, exc_update=exc_update, keep_lvt=keep_lvt, keep_generics=keep_generics, force_rg=force_rg) else: srvdecomp = False except CalledProcessError: # retroguard or other called process error so bail commands.logger.error('Decompile failed') sys.exit(1) if not no_recompile: if cltdecomp: try: updatemd5_side(commands, CLIENT) except CalledProcessError: commands.logger.error( 'Initial client recompile failed, correct source then run updatemd5' ) if srvdecomp: try: updatemd5_side(commands, SERVER) except CalledProcessError: commands.logger.error( 'Initial server recompile failed, correct source then run updatemd5' ) else: commands.logger.info('!! recompile disabled !!') except Exception: # pylint: disable-msg=W0703 logging.exception('FATAL ERROR') sys.exit(1)
for line in cmd.getoutput(): dirs_to_process.append(line.strip()) else: logger.error("cannot get list of projects") sys.exit(1) else: directory = args.directory for entry in os.listdir(directory): if path.isdir(path.join(directory, entry)): dirs_to_process.append(entry) logger.debug("to process: {}".format(dirs_to_process)) projects = [] for d in dirs_to_process: proj = CommandsBase(d, config["commands"]) projects.append(proj) try: projects = pool.map(worker, projects, 1) except KeyboardInterrupt: # XXX lock.release() or return 1 ? sys.exit(1) else: for proj in projects: cmds = Commands(proj) cmds.check(ignore_errors) except Timeout: logger.warning("Already running, exiting.") sys.exit(1)
import threading from websocket import create_connection from commands import Commands from ssh_handler import ShellHandler log_levels = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } bc = bencodepy.Bencode(encoding='utf-8') commands = Commands() config = None calls = [] sock = None def load_config(conf): try: logging.info("Started!") parser = configparser.ConfigParser() if not parser.read(conf): raise Exception except Exception: logging.error("Cannot read or parse the configuration file.") return None logging.info("Configuration file loaded!")
class TestFiatRate(unittest.TestCase): CACHE = {'eur': (3000, time())} def setUp(self): cls = build_lighterer_mock() with patch('lighterer.Lighterer', cls): self.commands = Commands('fake', 0, None, None) def test_cached(self): fiat = Fiat() # Import cache fiat._cache = self.CACHE self.assertEqual(fiat.get_rate(), self.CACHE['eur'][0]) self.assertEqual(fiat.to_fiat(1), 0) self.assertEqual(fiat.to_fiat(0.001 * 1e8), 0.001 * self.CACHE['eur'][0]) self.assertEqual(fiat.to_satoshis(5), int(5 / self.CACHE['eur'][0] * 1e8)) self.assertRegex(fiat.to_fiat_str(1), '^\d*\.\d{2} €') self.assertRegex(fiat.to_fiat_str(7), '^\d*\.\d{2} €') self.assertRegex(fiat.to_fiat_str(1000), '^\d*\.\d{2} €') @patch('requests.get') def test_kraken_mock(self, mock_get): mock_get.return_value = FakeRequests() expected_price = float(FakeRequests.DATA['result']['XXBTZEUR']['c'][0]) fiat = Fiat() self.assertAlmostEqual(fiat.get_rate(), expected_price) @patch('requests.get') def test_kraken_mock_error(self, mock_get): mock_get.return_value = FakeRateError() fiat = Fiat() with self.assertRaises(RateError): fiat.get_rate() @patch('requests.get') def test_commands_with_rate(self, mock_get): mock_get.return_value = FakeRequests() self.assertIn('€', self.commands.info()) self.commands.uri() self.commands.add() self.commands.add('123') self.commands.add('0.001') self.commands.add('7') self.assertIsInstance(self.commands.add('6.7€'), tuple) self.assertIsInstance(self.commands.add('6.8e'), tuple) self.assertIsInstance(self.commands.add('6.9E'), tuple) self.assertIn('€', self.commands.balance()) self.assertIsInstance(self.commands.channels(pending=False), list) # self.assertIsInstance(self.commands.channels(pending=True), list) # self.assertIsInstance(self.commands.pending(), list) self.assertIn('€', self.commands.chs()) self.assertTrue(self.commands.is_pay_req(PAY_REQ)) self.assertTrue(re.match('^(bc|tb)1', self.commands.address())) @patch('requests.get') def test_commands_without_rate(self, mock_get): mock_get.return_value = FakeRateError() self.assertNotIn('€', self.commands.info()) self.assertEqual(mock_get.call_count, 1) mock_get.reset_mock() self.commands.uri() self.commands.add() self.commands.add('123') self.commands.add('0.001') self.commands.add('7') with self.assertRaises(RateError): self.commands.add('6.7€') self.assertEqual(mock_get.call_count, 1) mock_get.reset_mock() with self.assertRaises(RateError): self.commands.add('6.8e') self.assertEqual(mock_get.call_count, 1) mock_get.reset_mock() with self.assertRaises(RateError): self.commands.add('6.9E') self.assertEqual(mock_get.call_count, 1) mock_get.reset_mock() self.assertNotIn('€', self.commands.balance()) self.assertIsInstance(self.commands.channels(pending=False), list) # self.assertIsInstance(self.commands.channels(pending=True), list) # self.assertIsInstance(self.commands.pending(), list) self.assertNotIn('€', self.commands.chs()) self.assertTrue(self.commands.is_pay_req(PAY_REQ)) self.assertTrue(re.match('^(bc|tb)1', self.commands.address()))
def main(conffile=None): commands = Commands(conffile) commands.startclient()
async def on_command_error(ctx: commands.Context, error): if hasattr(ctx.command, 'on_error'): return if isinstance(error, discord.ext.commands.CommandNotFound): await ctx.channel.send( '```fix\n' 'Unknown command\n' f'Type {settings.PREFIX} help for possible commands```') @bot.event async def on_ready(): await bot.change_presence( status=discord.Status.online, activity=discord.Game(f"Listening on {settings.PREFIX}")) logging.info('Bot started') try: open('config.yaml', 'x') logging.info('Created new config file') except FileExistsError: pass logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s", level=logging.INFO) bot.add_cog(ScheduledTasks(bot)) bot.add_cog(Commands(bot)) bot.run(settings.BOT_TOKEN)
# import random from hero import Hero # from monster import Monster from commands import Commands from game_object import GameObject from bestiary import Bestiary from colors import bcolors # import sys # from item import Item from potion_heal import Potion_heal # initialize game command_obj = Commands() bestiary = Bestiary("monsters.txt") def getInput(): if (game_obj.HERO.hp / game_obj.HERO.hp_max) > 0.66: hp_color = bcolors.FG_BOLD_GREEN elif (game_obj.HERO.hp / game_obj.HERO.hp_max) > 0.33: hp_color = bcolors.FG_BOLD_YELLOW else: hp_color = bcolors.FG_BOLD_RED prompt = bcolors.BOLD + game_obj.HERO.name + bcolors.ENDC +\ " - lvl: [" + str(game_obj.HERO.level) + "]" +\ " - hp: " + hp_color + "[" + str(game_obj.HERO.hp) + "/" + str(game_obj.HERO.hp_max) + "]" + bcolors.ENDC +\ " .... " + \ bcolors.FG_MAGENTA + game_obj.MONSTER.name + bcolors.ENDC +\ " - hp: [" + str(game_obj.MONSTER.hp) + "]" +\
line) # support for comments, f**k yea! mnemon, op, argument_sizes = line.split(",") argument_sizes = argument_sizes.split("|") argument_sizes = [ int(argument_size) for argument_size in argument_sizes ] if len(argument_sizes) == 1 and argument_sizes[0] == 0: argument_sizes = [] opcode_map[op.rstrip(" ").lower()] = { 'mnemon': mnemon.rstrip(" "), 'argument_sizes': argument_sizes } return opcode_map if __name__ == "__main__": buffer = "" # insert image here? registers = Registers() memory = Memory() commands = Commands(registers, memory) rom = b"\xa9\x05" opcode_parser = OpCodeParser(rom, commands, memory, registers) print(registers) opcode_parser.step(fake=False) # opcode_parser.step(fake=False) # opcode_parser.step(fake=False) # opcode_parser.step(fake=False) # opcode_parser.step(fake=False) print(registers)
def main(conffile=None, force=False): commands = Commands(conffile) commands.logger.info('== Updating MCP ==') commands.updatemcp(force)
class Bot: @property def mods(self): if ((time.time() - self._mods_updated_at) / 3600 >= self._mods_refresh_rate): self._mods = self.subreddit.moderator() self._mods_updated_at = time.time() return self._mods def __init__(self, reddit, subreddit_name, **options): self.reddit = reddit self.subreddit = self.reddit.subreddit(subreddit_name) self.me = self.reddit.user.me() self.post_flair_template_id = None self.data = Data(save_rate=options.get('save_data_every', 10)) self.data.load() self.stream = PushshiftStream(reddit, subreddit_name, self.data._seen) self.commands = Commands(**options) self.comment_template = options.get('sticky_comment_template') self.user_flair_template = options.get('user_flair_text_template') self.post_flair_template = options.get('post_flair_text_template') self.pinned_check_duration = options.get('pinned_check_duration', 7) self.checks_per_day = options.get('checks_per_day', 1) self.chart_limit = options.get('chart_limit', 5) self.character_limit = options.get('character_limit', 1000) self.flair_ignore = options.get('flair_ignore') self._mods = self.subreddit.moderator() self._mods_updated_at = time.time() self._mods_refresh_rate = 6 def update_sticky(self, thread): now = time.time() sorted_users = thread.sorted_users() top_user = thread.top_user(sorted_users_list=sorted_users) if top_user is None: if thread.sticky_comment is not None: thread.sticky_comment.delete() for user in thread.pinned_users: pinned_time = now - user.pinned_at user_flair_info = self.data.flair_infos[user.name] user_flair_info.pinned_for[ thread.submission.id] += pinned_time user.pinned_at = None thread.sticky_comment = None thread.pasted = None thread.pinned_users = set() return None top_users = thread.top_users(sorted_users_list=sorted_users) view_comment = top_user.get_comment() body = thread.get_body(self.comment_template, self.character_limit, self.chart_limit, top_user=top_user, sorted_users_list=sorted_users) if thread.sticky_comment is None: try: submission = view_comment.submission except AttributeError: submission = view_comment thread.sticky_comment = submission.reply(body) thread.sticky_comment.mod.distinguish(how='yes', sticky=True) for user in top_users: user.pinned_at = now elif thread.sticky_comment.body != body: thread.sticky_comment.edit(body) for user in top_users - thread.pinned_users: user.pinned_at = now for user in thread.pinned_users - top_users: pinned_time = now - user.pinned_at user_flair_info = self.date.flair_infos[user.name] user_flair_info.pinned_for[thread.submission.id] += pinned_time user.pinned_at = None else: return None thread.pasted = view_comment thread.pinned_users = top_users def vote_handler(self, comment): thread = self.data.thread(comment.submission) if thread.disabled: return None voter_name = comment.author.name parent_name = thread.parent(comment.parent_id) voter = thread.user(voter_name) prev_total = thread.total_voters prev_casts = thread.casted_votes if parent_name == self.me: if thread.pasted is not None: parent_name = thread.pasted.author.name else: return None if (self.commands.is_valid('vote', comment.body) and self.commands.percentage(comment.body, voter.votes) is not None and parent_name != voter_name): percentage = self.commands.percentage(comment.body, voter.votes) if parent_name in voter.voted_for: thread.update_votes(voter_name, parent_name, unvote=True) thread.update_votes(voter_name, parent_name, value=percentage, fullname=comment.fullname) elif (self.commands.is_valid('unvote', comment.body) and parent_name in voter.voted_for): thread.update_votes(voter_name, parent_name, unvote=True) else: return None self.update_sticky(thread) if (prev_casts != thread.casted_votes or prev_total != thread.total_voters): self.update_post_flair(comment.submission, thread) def update_post_flair(self, submission, thread): if self.post_flair_template_id is None: choices = submission.flair.choices() try: self.post_flair_template_id = choices[0]['flair_template_id'] except IndexError: return None flair = self.post_flair_template.format(voters=thread.total_voters, votes_cast=thread.casted_votes) submission.flair.select(self.post_flair_template_id, text=flair) def comment_handler(self, comment): thread = self.data.thread(comment.submission) if thread.disabled: return None author_name = comment.author.name if self.commands.is_valid('view', comment.body): thread.user(author_name).add_comment(comment) else: thread.user(author_name).add_comment(comment, is_view=False) self.update_sticky(thread) def update_pinned_comments(self): fullnames = self.data.fullnames(self.pinned_check_duration, self.checks_per_day) if fullnames: to_update = [] for thing in self.reddit.info(fullnames): if isinstance(thing, Comment): submission = thing.submission body = thing.body else: submission = thing body = thing.selftext thread = self.data.thread(submission) if isinstance(thread.pasted, Comment): pasted_body = thread.pasted.body else: pasted_body = thread.pasted.selftext if pasted_body != body: username = thread.pasted.author.name user = thread.user(username) if isinstance(thread.pasted, Comment): user.remove_comment(thread.pasted) else: user.submission = None if not is_deleted(thing) and not thing.removed: if isinstance(thing, Comment): is_view = self.commands.is_valid('view', body) user.add_comment(thing, is_view=is_view) else: user.submission = thing to_update.append(thread) thread.last_checked = time.time() for thread in to_update: self.update_sticky(thread) def update_users_flair(self, usernames): mappings = [] for username in usernames: if username not in self.flair_ignore: h, v = self.data.user_flair_averages(username) flair = self.user_flair_template.format(hours_average=h, votes_average=v) mappings.append({'user': username, 'flair_text': flair}) if mappings: self.subreddit.flair.update(mappings) def main(self): to_flair = set() comments_stream = self.stream.comments() while True: for comment in comments_stream: if comment is not None: thread = self.data.thread(comment.submission) thread.ids_authors[comment.fullname] = comment.author.name else: break if comment.author == self.me: continue elif (self.commands.is_valid('vote', comment.body) or self.commands.is_valid('unvote', comment.body)): self.vote_handler(comment) elif (self.commands.is_valid('disablevote', comment.body) and comment.author in self.mods): thread = self.data.thread(comment.submission) thread.disabled = True else: self.comment_handler(comment) to_flair.add(comment.author.name) self.update_users_flair(to_flair) self.update_pinned_comments() self.data.clean() self.data.save(last_seen=self.stream._last_seen)
def main(): parser = OptionParser(version='MCP %s' % Commands.fullversion()) parser.add_option('-c', '--config', dest='config', help='additional configuration file') options, _ = parser.parse_args() startserver(options.config)