def fetch_todo(): def todo_plugin(name): todo = [] if plugins.is_installed(name): for dep in plugins.headers[name].DEPENDENCIES: if extensions.is_installed(dep): todo.append(dep) else: return [] return (todo, name) return [] extensions.load() plugins.load() ext_req = [] plugs = [] for name in plugins.headers.keys(): for i in todo_plugin(name): ext_req.append(i[0]) plugs.append(i[1]) todo = [(extensions.load_extension, ext[0]) for ext in ext_req] for plug in plugs: todo.append((plugins.load_plugin, plug)) return todo
def _on_connect(self, initial_data): """handle connection/reconnection""" logging.debug("connected") self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator self._user_list = yield from hangups.user.build_user_list(self._client, initial_data) self._conv_list = hangups.ConversationList(self._client, initial_data.conversation_states, self._user_list, initial_data.sync_timestamp) self.conversations = yield from permamem.initialise_permanent_memory(self) self.tags = tagging.tags(self) plugins.load(self, command) self._conv_list.on_event.add_observer(self._on_event) self._client.on_state_update.add_observer(self._on_status_changes) logging.info("bot initialised")
def fetch_todo(): def todo_plugin(name): todo=[] if plugins.is_installed(name): for dep in plugins.headers[name].DEPENDENCIES: if extensions.is_installed(dep): todo.append(dep) else: return [] return (todo,name) return [] extensions.load() plugins.load() ext_req=[] plugs=[] for name in plugins.headers.keys(): for i in todo_plugin(name): ext_req.append(i[0]) plugs.append(i[1]) todo=[(extensions.load_extension, ext[0]) for ext in ext_req] for plug in plugs: todo.append((plugins.load_plugin, plug)) return todo
def _on_connect(self, initial_data): """Handle connecting for the first time""" print(_('Connected!')) self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator try: # hangups-201504090500 self._user_list = yield from hangups.user.build_user_list( self._client, initial_data ) except AttributeError: # backward-compatibility: pre hangups-201504090500 self._user_list = hangups.UserList(self._client, initial_data.self_entity, initial_data.entities, initial_data.conversation_participants) self._conv_list = hangups.ConversationList(self._client, initial_data.conversation_states, self._user_list, initial_data.sync_timestamp) self._conv_list.on_event.add_observer(self._on_event) self.conversations = conversation_memory(self) plugins.load(self, command)
def _on_connect(self, initial_data): """handle connection/reconnection""" logging.debug("connected") self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator self._user_list = yield from hangups.user.build_user_list( self._client, initial_data) self._conv_list = hangups.ConversationList( self._client, initial_data.conversation_states, self._user_list, initial_data.sync_timestamp) self.conversations = yield from permamem.initialise_permanent_memory( self) self.tags = tagging.tags(self) plugins.load(self, command) self._conv_list.on_event.add_observer(self._on_event) self._client.on_state_update.add_observer(self._on_status_changes) logging.info("bot initialised")
async def load_command(msg, args): name = plugin_from_arg(args.next_arg()) if not name: return try: plugins.load(name) await msg.channel.send("\u2705") except: await reply_exception(msg)
def onStart(self): load(Parameters['HomeFolder']) if Parameters["Mode6"] == 'Debug': Domoticz.Debugging(2) else: Domoticz.Debugging(0) if platform.system() == "Windows": Domoticz.Error("Windows Platform is NOT YET SUPPORTED!") return self.install_ui() self.api_manager = APIManager(Devices)
def load_plugin(self): mode_infos = load(self.plugin_dir, 'name', 'urls') for model, name, urls in mode_infos.values(): self.init_mode(model, name, urls) self.__add_url()
def main(): '''Take command from 127.0.0.1:5000 and run it through various modules''' try: #Get command command = request.args.get("command", '') logs.write("Command is {0}".format(command),'working') logs.write("Analyzing content in command", 'trying') #Run command through contentextract.py contentextract.main(command) logs.write("Analyzed command content", 'success') logs.write("Trying to load plugin modules", 'trying') #Load plugins using plugins.py plugins=plugs.load() #If the plugins encounter an error if plugins==False: logs.write("Could not load plugins", 'error') return "error" #If plugins.py says that there are no plugins found. All functions are a plugin so no point in continuing elif plugins==[]: logs.write("No plugins found", 'error') return 'error' logs.write("Successfully loaded plugin modules", 'success') logs.write("Using the intent module to parse the command", 'trying') #Use intent.py to try to extract intent from command parsed=intent.parse(command, plugins) logs.write("Parsed the command", 'success') #If the intent parser says to execute the following plugin. Leaves room if I ever want to expand the capabilities of the intent module if parsed.keys()[0]=="execute": logs.write("Executing plugin {0}".format(parsed.values()[0].keys()[0]), 'trying') response=plugs.execute(parsed.values()[0], command) logs.write("Found answer {0}, returning it".format(response), 'success') return response except Exception as e: logs.write(e,'error') return str(e)
def pluginreload(bot, event, *args): if args: module_path = args[0] try: yield from plugins.unload(bot, module_path) plugins.load(bot, module_path) message = "<b><pre>{}</pre>: reloaded</b>".format(module_path) except (RuntimeError, KeyError) as e: message = "<b><pre>{}<pre>: <pre>{}</pre></b>".format(module_path, str(e)) else: message = "<b>module path required</b>" yield from bot.coro_send_message(event.conv_id, message)
def main(): try: command = request.args.get("command", '') logs.write("Command is {0}".format(command),'working') logs.write("Analyzing content in command", 'trying') contentextract.main(command) logs.write("Analyzed command content", 'success') logs.write("Trying to load plugin modules", 'trying') plugins=plugs.load() if plugins==False: logs.write("Could not load plugins", 'error') return "error" elif plugins==[]: logs.write("No plugins found", 'error') return 'error' logs.write("Successfully loaded plugin modules", 'success') logs.write("Using the intent module to parse the command", 'trying') parsed=intent.parse(command, plugins) logs.write("Parsed the command", 'success') if parsed.keys()[0]=="execute": logs.write("Executing plugin {0}".format(parsed.values()[0].keys()[0]), 'trying') response=plugs.execute(parsed.values()[0], command) logs.write("Found answer {0}, returning it".format(response), 'success') return response except Exception as e: logs.write(e,'error') return str(e)
def addplugin(bot, event, plugin, *args): """Adds a plugin to the bot, REQUIRES REBOOT /bot addplugin <pluginname>""" all_plugins = plugins.retrieve_all_plugins() loaded_plugins = plugins.get_configured_plugins(bot) if plugin not in loaded_plugins: if plugin in all_plugins: value = bot.config.get_by_path(["plugins"]) if isinstance(value, list): value.append(plugin) bot.config.set_by_path(["plugins"], value) bot.config.save() # attempt to load the plugin try: if plugins.load(bot, "plugins.{}".format(plugin)): message = "<b><pre>{}</pre>: loaded</b>".format( "plugins.{}".format(plugin)) else: message = "<b><pre>{}</pre>: failed</b>".format( "plugins.{}".format(plugin)) except RuntimeError as e: message = "<b><pre>{}</pre>: <pre>{}</pre></b>".format( module_path, str(e)) else: message = "Error: Do <b>/bot config set plugins []</b> first" else: message = "Not a valid plugin name" else: message = "Plugin already loaded" yield from bot.coro_send_message(event.conv_id, message)
def main(): try: command = request.args.get("command", '') logs.write("Command is {0}".format(command), 'working') logs.write("Analyzing content in command", 'trying') contentextract.main(command) logs.write("Analyzed command content", 'success') logs.write("Trying to load plugin modules", 'trying') plugins = plugs.load() if plugins == False: logs.write("Could not load plugins", 'error') return "error" elif plugins == []: logs.write("No plugins found", 'error') return 'error' logs.write("Successfully loaded plugin modules", 'success') logs.write("Using the intent module to parse the command", 'trying') parsed = intent.parse(command, plugins) logs.write("Parsed the command", 'success') if parsed.keys()[0] == "execute": logs.write( "Executing plugin {0}".format(parsed.values()[0].keys()[0]), 'trying') response = plugs.execute(parsed.values()[0], command) logs.write("Found answer {0}, returning it".format(response), 'success') return response except Exception as e: logs.write(e, 'error') return str(e)
def addplugin(bot, event, plugin, *args): """Adds a plugin to the bot, REQUIRES REBOOT /bot addplugin <pluginname>""" all_plugins = plugins.retrieve_all_plugins() loaded_plugins = plugins.get_configured_plugins(bot) if plugin not in loaded_plugins: if plugin in all_plugins: value = bot.config.get_by_path(["plugins"]) if isinstance(value, list): value.append(plugin) bot.config.set_by_path(["plugins"], value) bot.config.save() # attempt to load the plugin try: if plugins.load(bot, "plugins.{}".format(plugin)): message = "<b><pre>{}</pre>: loaded</b>".format("plugins.{}".format(plugin)) else: message = "<b><pre>{}</pre>: failed</b>".format("plugins.{}".format(plugin)) except RuntimeError as e: message = "<b><pre>{}</pre>: <pre>{}</pre></b>".format(module_path, str(e)) else: message = "Error: Do <b>/bot config set plugins []</b> first" else: message = "Not a valid plugin name" else: message = "Plugin already loaded" yield from bot.coro_send_message(event.conv_id, message)
def load_blueprint(self): if self.blueprints_dir is None: return bps_infos = load(self.blueprints_dir, 'app_bp') for name, bps in bps_infos.items(): bp = bps[1] self.app.register_blueprint(bp)
def run(): '''Open logs, check log settings, and start the flask server and slack thread''' log.info(''' \ / | | | \ / | | | \ / | | | \ /\ / | | | \ / \ / | | | \/ \/ | ------------ ------------ ''') if log.getEffectiveLevel() == logging.DEBUG: debugval = True else: debugval = False #Load the plugins plugins.load("plugins/") log.info("Debug value is {0}".format(debugval))
def main(): '''Take command from 127.0.0.1:5000 and run it through various modules''' try: # Get command command = request.args.get("command", '') log.debug("Command is {0}".format(command)) log.info("Analyzing content in command") # Run command through contentextract.py contentextract.main(command) log.info("Analyzed command content") log.info("Trying to load plugin modules") # Load plugins using plugins.py plugins = plugs.load() # If the plugins encounter an error if plugins is False: log.error("Could not load plugins") return "error" # If plugins.py says that there are no plugins found. All functions are # a plugin so no point in continuing elif plugins == []: log.error("No plugins found") return 'error' log.info("Successfully loaded plugin modules") log.info("Using the intent module to parse the command") # Use intent.py to try to extract intent from command parsed = intent.parse(command, plugins) log.info("Parsed the command") # If the intent parser says to execute the following plugin. Leaves # room if I ever want to expand the capabilities of the intent module if parsed.keys()[0] == "execute": log.info("Executing plugin {0}".format( parsed.values()[0].keys()[0])) response = plugs.execute(parsed.values()[0], command) log.info("Found answer {0}, returning it".format( response)) return response elif parsed.keys()[0]=="error": log.error("Parse function returned the error {0}".format(parsed.values()[0])) if parsed.values()[0]=="notfound": #This would have unhandled exceptions if the search plugin was gone, but I can't imagine why it would be log.error("The error means that the command was not recognized") log.info("Using the search plugin on the command phrase") log.info("Trying to find search plugin") for plugin in plugins: if plugin.keys()[0]=="search": searchplug=plugin break log.info("Found search plugin") response=plugs.execute(searchplug,command) log.info("Found answer {0}, returning it".format(response)) return response else: log.error("Unhandled error {0}. If you get this error message something is broken in the intent module. Please raise an issue on https://github.com/ironman5366/W.I.L.L".format(str(parsed.values()[0]))) except Exception as e: log.error(e, 'error') return str(e)
def start(): import namb.gui as gui global m m=gui.MainWindow() import extensions extensions.load() extensions.load_extension("vlc") import plugins plugins.load() plugins.install_plugin("radionpo") plugins.load_plugin("radionpo") #plugins.load_plugin("jazzradio_com") global g g=plugins.get_plugin("radionpo") g.init() g.display(m.p.frame) import namb.userinput namb.userinput.set_receiver(g.menu) g.menu.focus_receive() m.p.frame.after(1, lambda: m.bar.menu_vanish()) ui_loop()
def addplugin(bot, event, plugin, *args): """loads a plugin on the bot and adds it to the config, does not require plugins. prefix""" config_plugins = bot.config.get_by_path(["plugins"]) or False if not isinstance(config_plugins, list): yield from bot.coro_send_message( event.conv_id, "this command only works with manually-configured plugins key in config.json" ) return lines = [] loaded_plugins = plugins.get_configured_plugins(bot) or [] all_plugins = plugins.retrieve_all_plugins(allow_underscore=True) plugin = _strip_plugin_path(plugin) if not plugin: yield from bot.coro_send_message(event.conv_id, "invalid plugin name") return if plugin not in all_plugins: yield from bot.coro_send_message( event.conv_id, "plugin does not exist: {}".format(plugin.replace("_", "\\_"))) return lines.append("**add plugin: {}**".format(plugin.replace("_", "\\_"))) if plugin in loaded_plugins: lines.append('* already loaded on bot start') else: module_path = "plugins.{}".format(plugin) escaped_module_path = module_path.replace("_", "\\_") try: if plugins.load(bot, module_path): lines.append('* **loaded: {}**'.format(escaped_module_path)) else: lines.append( '* failed to load: {}'.format(escaped_module_path)) except RuntimeError as e: lines.append('* error loading {}: {}'.format( escaped_module_path, str(e))) if plugin in config_plugins: lines.append('* already in config.json') else: config_plugins.append(plugin) bot.config.set_by_path(["plugins"], config_plugins) bot.config.save() lines.append('* **added to config.json**') yield from bot.coro_send_message(event.conv_id, "\n".join(lines))
def addplugin(bot, event, plugin, *args): """loads a plugin on the bot and adds it to the config, does not require plugins. prefix""" config_plugins = bot.config.get_by_path(["plugins"]) or False if not isinstance(config_plugins, list): yield from bot.coro_send_message( event.conv_id, "this command only works with manually-configured plugins key in config.json" ) return lines = [] loaded_plugins = plugins.get_configured_plugins(bot) or [] all_plugins = plugins.retrieve_all_plugins(allow_underscore=True) plugin = _strip_plugin_path(plugin) if not plugin: yield from bot.coro_send_message( event.conv_id, "invalid plugin name") return if plugin not in all_plugins: yield from bot.coro_send_message( event.conv_id, "plugin does not exist: {}".format(plugin.replace("_", "\\_")) ) return lines.append("**add plugin: {}**".format(plugin.replace("_", "\\_"))) if plugin in loaded_plugins: lines.append('* already loaded on bot start') else: module_path = "plugins.{}".format(plugin) escaped_module_path = module_path.replace("_", "\\_") try: if plugins.load(bot, module_path): lines.append('* **loaded: {}**'.format(escaped_module_path)) else: lines.append('* failed to load: {}'.format(escaped_module_path)) except RuntimeError as e: lines.append('* error loading {}: {}'.format(escaped_module_path, str(e))) if plugin in config_plugins: lines.append('* already in config.json') else: config_plugins.append(plugin) bot.config.set_by_path(["plugins"], config_plugins) bot.config.save() lines.append('* **added to config.json**') yield from bot.coro_send_message(event.conv_id, "\n".join(lines))
def load_restful(app_api, restful_dir): mode_infos = load(restful_dir, "urls") for model, urls in mode_infos.values(): mode_name = model.__name__ names = mode_name.split("/")[-1:][0] for url, view in _groups(urls): view = _get_attr(model, view) if view is None: continue endpoint = "%s.%s"%(names, view.__name__) app_api.add_resource(view, url, endpoint=endpoint)
def __init__(self, config: Dict[str, Any]): self.stop_event = threading.Event() self.plugins = { name: plugins.load(name, self, config) for name in config["plugins"] } assert self.validate_plugins(config) self.smtp_credentials = Credentials("smtp", config) self.machines = [ Machine(config["adc_config"], **args) for args in config["machines"] ] self.users = [User(self, **args) for args in config["users"]]
def pluginload(bot, event, *args): if args: module_path = args[0] try: if plugins.load(bot, module_path): message = "<b><pre>{}</pre>: loaded</b>".format(module_path) else: message = "<b><pre>{}</pre>: failed</b>".format(module_path) except RuntimeError as e: message = "<b><pre>{}</pre>: <pre>{}</pre></b>".format(module_path, str(e)) else: message = "<b>module path required</b>" yield from bot.coro_send_message(event.conv_id, message)
def run_from_url(username, reponame): gh = login(token=os.environ['GITHUB_API_TOKEN']) repo = gh.repository(username, reponame) if repo is None: return "Error - Repo doesn't exist!" results = [] actives = plugins.load() results.extend(active.get_html(repo) for active in actives) passes = [] passes.extend(active.get_passes() for active in actives) print(actives) print(len(actives)) results = map(Markup, results) results = zip(results, passes) return render_template("results.html", name=repo.name, results=results)
def newfunc(*args, **kwargs): global _client global signals if not _client: _client = Client() signals = _client.signals if not _client.connected: try: # wait for next connect if _client.channel.status != kaa.rpc.CONNECTED: # this may raise an exception yield kaa.inprogress(_client.channel) if not _client.connected: yield kaa.inprogress(signals["connect"]) log.info("beacon connected") for name, interface in plugins.load(_client).items(): globals()[name] = interface except Exception, e: raise ConnectError(e)
def newfunc(*args, **kwargs): global _client global signals if not _client: _client = Client() signals = _client.signals if not _client.connected: try: # wait for next connect if _client.channel.status != kaa.rpc.CONNECTED: # this may raise an exception yield kaa.inprogress(_client.channel) if not _client.connected: yield kaa.inprogress(signals['connect']) log.info('beacon connected') for name, interface in plugins.load(_client).items(): globals()[name] = interface except Exception, e: raise ConnectError(e)
def pluginreload(bot, event, *args): """reloads a previously loaded plugin, requires plugins. prefix""" if args: module_path = args[0] try: yield from plugins.unload(bot, module_path) if plugins.load(bot, module_path): message = "<b><pre>{}</pre>: reloaded</b>".format(module_path) else: message = "<b><pre>{}</pre>: failed reload</b>".format(module_path) except (RuntimeError, KeyError) as e: message = "<b><pre>{}</pre>: <pre>{}</pre></b>".format(module_path, str(e)) else: message = "<b>module path required</b>" yield from bot.coro_send_message(event.conv_id, message)
def main(): '''Take command from 127.0.0.1:5000 and run it through various modules''' try: #Get command command = request.args.get("command", '') logs.write("Command is {0}".format(command), 'working') logs.write("Analyzing content in command", 'trying') #Run command through contentextract.py contentextract.main(command) logs.write("Analyzed command content", 'success') logs.write("Trying to load plugin modules", 'trying') #Load plugins using plugins.py plugins = plugs.load() #If the plugins encounter an error if plugins == False: logs.write("Could not load plugins", 'error') return "error" #If plugins.py says that there are no plugins found. All functions are a plugin so no point in continuing elif plugins == []: logs.write("No plugins found", 'error') return 'error' logs.write("Successfully loaded plugin modules", 'success') logs.write("Using the intent module to parse the command", 'trying') #Use intent.py to try to extract intent from command parsed = intent.parse(command, plugins) logs.write("Parsed the command", 'success') #If the intent parser says to execute the following plugin. Leaves room if I ever want to expand the capabilities of the intent module if parsed.keys()[0] == "execute": logs.write( "Executing plugin {0}".format(parsed.values()[0].keys()[0]), 'trying') response = plugs.execute(parsed.values()[0], command) logs.write("Found answer {0}, returning it".format(response), 'success') return response except Exception as e: logs.write(e, 'error') return str(e)
def _on_connect(self, initial_data): """handle connection/reconnection""" logger.debug("connected") plugins.tracking.set_bot(self) command.set_tracking(plugins.tracking) command.set_bot(self) self.tags = tagging.tags(self) self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator plugins.load(self, "monkeypatch.otr_support") self._user_list = yield from hangups.user.build_user_list(self._client, initial_data) self._conv_list = hangups.ConversationList(self._client, initial_data.conversation_states, self._user_list, initial_data.sync_timestamp) self.conversations = yield from permamem.initialise_permanent_memory(self) plugins.load(self, "commands.plugincontrol") plugins.load(self, "commands.basic") plugins.load(self, "commands.tagging") plugins.load(self, "commands.permamem") plugins.load(self, "commands.convid") plugins.load(self, "commands.loggertochat") plugins.load_user_plugins(self) self._conv_list.on_event.add_observer(self._on_event) self._client.on_state_update.add_observer(self._on_status_changes) logger.info("bot initialised") yield from self.coro_send_message(CONTROL, _("Bot is back up"))
def __init__(self): #print "DEBUG: constructor for handler initing" self.plugins = plugins_(self) if(not self.plugins): print "DEBUG: unable to make self.plugins!?!" self.newplugins = plugins.load()
def _on_connect(self): """handle connection/reconnection""" logger.debug("connected") plugins.tracking.set_bot(self) command.set_tracking(plugins.tracking) command.set_bot(self) self.tags = tagging.tags(self) self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator """ monkeypatch plugins go heere # plugins.load(self, "monkeypatch.something") use only in extreme circumstances e.g. adding new functionality into hangups library """ #self._user_list = yield from hangups.user.build_user_list(self._client) self._user_list, self._conv_list = ( yield from hangups.build_user_conversation_list(self._client) ) self.conversations = yield from permamem.initialise_permanent_memory(self) plugins.load(self, "commands.plugincontrol") plugins.load(self, "commands.basic") plugins.load(self, "commands.tagging") plugins.load(self, "commands.permamem") plugins.load(self, "commands.convid") plugins.load(self, "commands.loggertochat") plugins.load_user_plugins(self) self._conv_list.on_event.add_observer(self._on_event) self._client.on_state_update.add_observer(self._on_status_changes) logger.info("bot initialised")
def _on_connect(self, initial_data): """handle connection/reconnection""" logger.debug("connected") plugins.tracking.set_bot(self) command.set_tracking(plugins.tracking) command.set_bot(self) self.tags = tagging.tags(self) self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator plugins.load(self, "monkeypatch.otr_support") self._user_list = yield from hangups.user.build_user_list( self._client, initial_data) self._conv_list = hangups.ConversationList( self._client, initial_data.conversation_states, self._user_list, initial_data.sync_timestamp) self.conversations = yield from permamem.initialise_permanent_memory( self) plugins.load(self, "commands.plugincontrol") plugins.load(self, "commands.basic") plugins.load(self, "commands.tagging") plugins.load(self, "commands.permamem") plugins.load(self, "commands.convid") plugins.load(self, "commands.loggertochat") plugins.load_user_plugins(self) self._conv_list.on_event.add_observer(self._on_event) self._client.on_state_update.add_observer(self._on_status_changes) logger.info("bot initialised")
import logging logging.basicConfig(level=logging.DEBUG) import asyncio import util.restart import plugins import discord_client loop = asyncio.get_event_loop() loop.create_task(discord_client.main_task()) try: plugins.load("plugins.autoload") loop.run_forever() except: logging.getLogger(__name__).critical("Exception during main event loop", exc_info=True) finally: if not discord_client.client.is_closed(): loop.run_until_complete(discord_client.client.close()) loop.close()
time.sleep(10 / 1000000.0) lp_url = 'https://' + lp_info['server'] + '?act=a_check&key=' + lp_info['key'] + '&ts=' + \ str(lp_info['ts']) + '&wait=60&mode=2&version=3' result = json.loads(requests.get(lp_url).text) try: lp_info['ts'] = result['ts'] for update in result['updates']: updates_queue.put(update) except KeyError: lp_info = get_lp_server() if __name__ == '__main__': kbotlib.log_print('Подключение плагинов ...', 'info') import plugins plugins.load() kbotlib.log_print('Плагины подключены.', 'info') kbotlib.log_print('Запуск longpoll потока ...', 'info') thread_longpoll = threading.Thread(target=longpollserver) thread_longpoll.start() kbotlib.log_print('Longpoll поток запущен.', 'info') kbotlib.log_print('Инициализация завершена.', 'info') try: while True: time.sleep(10 / 1000000.0) if not updates_queue.empty(): update = updates_queue.get() if update[0] == 4:
class Server(object): """ Server for the virtual filesystem to handle write access to the db and scanning / monitoring of queries. """ def __init__(self, dbdir, scheduler=None): log.info('start beacon') try: self.ipc = kaa.rpc.Server('beacon') except IOError, e: kaa.beacon.thumbnail.thumbnail.disconnect() log.error('beacon: %s' % e) time.sleep(0.1) sys.exit(0) self.ipc.signals['client-connected'].connect(self.client_connect) self.ipc.register(self) self._dbdir = dbdir self._db = Database(dbdir) self._next_client = 0 self._db.register_inverted_index('keywords', min=2, max=30) self._db.register_object_type_attrs("dir", image_from_parser=(bool, ATTR_SIMPLE), last_crawl=(int, ATTR_SIMPLE), title=(unicode, ATTR_SIMPLE), series=(unicode, ATTR_SIMPLE), season=(int, ATTR_SIMPLE), artist=(unicode, ATTR_SIMPLE), album=(unicode, ATTR_SIMPLE), length=(float, ATTR_SIMPLE)) # files self.register_file_type_attrs( "video", title=(unicode, ATTR_SEARCHABLE | ATTR_IGNORE_CASE | ATTR_INVERTED_INDEX, 'keywords'), poster=(str, kaa.beacon.ATTR_SIMPLE), width=(int, ATTR_SIMPLE), height=(int, ATTR_SIMPLE), length=(float, ATTR_SIMPLE), scheme=(str, ATTR_SIMPLE), description=(unicode, ATTR_SIMPLE), series=(unicode, ATTR_SEARCHABLE), season=(int, ATTR_SEARCHABLE), episode=(int, ATTR_SEARCHABLE), hash=(str, ATTR_SIMPLE), stereo=(str, ATTR_SIMPLE), timestamp=(int, ATTR_SEARCHABLE)) self.register_file_type_attrs( "audio", title=(unicode, ATTR_SEARCHABLE | ATTR_IGNORE_CASE | ATTR_INVERTED_INDEX, 'keywords'), artist=(unicode, ATTR_SEARCHABLE | ATTR_INDEXED | ATTR_IGNORE_CASE | ATTR_INVERTED_INDEX, 'keywords'), album=(unicode, ATTR_SEARCHABLE | ATTR_IGNORE_CASE | ATTR_INVERTED_INDEX, 'keywords'), genre=(unicode, ATTR_SEARCHABLE | ATTR_INDEXED | ATTR_IGNORE_CASE), samplerate=(int, ATTR_SIMPLE), length=(float, ATTR_SIMPLE), bitrate=(int, ATTR_SIMPLE), trackno=(int, ATTR_SIMPLE), userdate=(unicode, ATTR_SIMPLE), description=(unicode, ATTR_SIMPLE), hash=(str, ATTR_SIMPLE), timestamp=(int, ATTR_SEARCHABLE)) self.register_file_type_attrs( "image", width=(int, ATTR_SEARCHABLE), height=(int, ATTR_SEARCHABLE), comment=(unicode, ATTR_SEARCHABLE | ATTR_IGNORE_CASE | ATTR_INVERTED_INDEX, 'keywords'), rotation=(int, ATTR_SIMPLE), author=(unicode, ATTR_SIMPLE), hash=(str, ATTR_SIMPLE), timestamp=(int, ATTR_SEARCHABLE)) # tracks for rom discs or iso files self.register_track_type_attrs("dvd", length=(float, ATTR_SIMPLE), audio=(list, ATTR_SIMPLE), chapters=(int, ATTR_SIMPLE), subtitles=(list, ATTR_SIMPLE)) self.register_track_type_attrs("vcd", audio=(list, ATTR_SIMPLE)) self.register_track_type_attrs( "cdda", title=(unicode, ATTR_SEARCHABLE | ATTR_INVERTED_INDEX, 'keywords'), artist=(unicode, ATTR_SEARCHABLE | ATTR_INDEXED | ATTR_INVERTED_INDEX, 'keywords')) # list of current clients self.clients = [] # Config file is synced in Thumbnailer. See its constructor for # rationale. config.load(os.path.join(dbdir, "config")) config.watch() if scheduler: config.scheduler.policy = scheduler else: config.autosave = True # commit and wait for the results (there are no results, # this code is only used to force waiting until the db is # set up. self._db.commit() # give database to controller / hardware monitor rootfs = { 'beacon.id': 'root-' + get_machine_uuid(), 'block.device': '', 'volume.mount_point': '/' } self.item_controller = Controller(self, self._db, rootfs) self._db.commit() # load plugins plugins.load(self, self._db) for dir in config.monitors: self.monitor_directory(os.path.expandvars(os.path.expanduser(dir))) # scanner self.scanner = Crawler(self._db, monitor=False)
def __init__(self): # print "DEBUG: constructor for handler initing" self.plugins = plugins_(self) if not self.plugins: print "DEBUG: unable to make self.plugins!?!" self.newplugins = plugins.load()
def _on_connect(self): """handle connection/reconnection""" logger.debug("connected") plugins.tracking.set_bot(self) command.set_tracking(plugins.tracking) command.set_bot(self) self.tags = tagging.tags(self) self._handlers = handlers.EventHandler(self) handlers.handler.set_bot(self) # shim for handler decorator """ monkeypatch plugins go heere # plugins.load(self, "monkeypatch.something") use only in extreme circumstances e.g. adding new functionality into hangups library """ #self._user_list = yield from hangups.user.build_user_list(self._client) self._user_list, self._conv_list = ( yield from hangups.build_user_conversation_list(self._client)) self.conversations = yield from permamem.initialise_permanent_memory( self) plugins.load(self, "commands.plugincontrol") plugins.load(self, "commands.basic") plugins.load(self, "commands.tagging") plugins.load(self, "commands.permamem") plugins.load(self, "commands.convid") plugins.load(self, "commands.loggertochat") plugins.load_user_plugins(self) self._conv_list.on_event.add_observer(self._on_event) self._client.on_state_update.add_observer(self._on_status_changes) logger.info("bot initialised")
""" Automatically load certain plugins after bot initialization. """ import importlib import logging import util.db.kv import plugins conf = util.db.kv.Config(__name__) if conf.autoload == None: conf.autoload = [] def get_autoload(): return conf.autoload def set_autoload(autoload): conf.autoload = autoload logger = logging.getLogger(__name__) for name in conf.autoload: try: # Sidestep plugin dependency tracking plugins.load(name) except: logger.critical("Exception during autoload of {}".format(name), exc_info=True)
def run(results, cmdenv, tdb): # If we're using a plugin, initialize that first. if cmdenv.plug: if cmdenv.pluginOptions: cmdenv.pluginOptions = chain.from_iterable( opt.split(',') for opt in cmdenv.pluginOptions) try: pluginClass = plugins.load(cmdenv.plug, "ImportPlugin") except plugins.PluginException as e: raise CommandLineError("Plugin Error: " + str(e)) # Initialize the plugin plugin = pluginClass(tdb, cmdenv) # Run the plugin. If it returns False, then it did everything # that needs doing and we can stop now. # If it returns True, it is returning control to the module. if not plugin.run(): return None tdb.reloadCache() tdb.close() if cmdenv.filename: if re.match(r"^https?://", cmdenv.filename, re.IGNORECASE): cmdenv.url, cmdenv.filename = cmdenv.filename, None if cmdenv.url: cmdenv.filename = cmdenv.filename or "import.prices" transfers.download(cmdenv, cmdenv.url, cmdenv.filename) if cmdenv.download: return None # If the filename specified was "-" or None, then go ahead # and present the user with an open file dialog. if not cmdenv.filename and hasTkInter: tk = tkinter.Tk() tk.withdraw() filetypes = ( ("TradeDangerous '.prices' Files", "*.prices"), ("All Files", "*.*"), ) filename = tkfd.askopenfilename( title="Select the file to import", initialfile="TradeDangerous.prices", filetypes=filetypes, initialdir='.', ) if not filename: raise SystemExit("Aborted") cmdenv.filename = filename # check the file exists. if cmdenv.filename != "-": fh = None filePath = Path(cmdenv.filename) if not filePath.is_file(): raise CommandLineError("File not found: {}".format(str(filePath))) else: filePath = "stdin" fh = sys.stdin if cmdenv.plug: if not plugin.finish(): cache.regeneratePricesFile() return None cache.importDataFromFile(tdb, cmdenv, filePath, pricesFh=fh, reset=cmdenv.reset) return None
def run(results, cmdenv, tdb): # If we're using a plugin, initialize that first. if cmdenv.plug: if cmdenv.pluginOptions: cmdenv.pluginOptions = chain.from_iterable( opt.split(',') for opt in cmdenv.pluginOptions ) try: pluginClass = plugins.load(cmdenv.plug, "ImportPlugin") except plugins.PluginException as e: raise CommandLineError("Plugin Error: "+str(e)) # Initialize the plugin plugin = pluginClass(tdb, cmdenv) # Run the plugin. If it returns False, then it did everything # that needs doing and we can stop now. # If it returns True, it is returning control to the module. if not plugin.run(): return None tdb.reloadCache() tdb.close() if cmdenv.filename: if re.match(r"^https?://", cmdenv.filename, re.IGNORECASE): cmdenv.url, cmdenv.filename = cmdenv.filename, None if cmdenv.url: cmdenv.filename = cmdenv.filename or "import.prices" transfers.download(cmdenv, cmdenv.url, cmdenv.filename) if cmdenv.download: return None # If the filename specified was "-" or None, then go ahead # and present the user with an open file dialog. if not cmdenv.filename and hasTkInter: tk = tkinter.Tk() tk.withdraw() filetypes = ( ("TradeDangerous '.prices' Files", "*.prices"), ("All Files", "*.*"), ) filename = tkfd.askopenfilename( title="Select the file to import", initialfile="TradeDangerous.prices", filetypes=filetypes, initialdir='.', ) if not filename: raise SystemExit("Aborted") cmdenv.filename = filename # check the file exists. if cmdenv.filename != "-": fh = None filePath = Path(cmdenv.filename) if not filePath.is_file(): raise CommandLineError("File not found: {}".format( str(filePath) )) else: filePath = "stdin" fh = sys.stdin if cmdenv.plug: if not plugin.finish(): cache.regeneratePricesFile() return None cache.importDataFromFile(tdb, cmdenv, filePath, pricesFh=fh, reset=cmdenv.reset) return None
if args.no_overwrite and path.exists(fout): print "Skipped! \"" + fout + "\" exists."; else: print "Building ePub"; epub(web, fout, styler, args); print "Done! Written output to \"" + fout + "\""; if __name__ == "__main__": # Parse incoming arguments: parser = argparse.ArgumentParser(description='Converts articles/posts/entries from online sources into an ePub file.'); parser.add_argument('url', type=arg_url, help='A URL to start from. Must end with a forward slash (/) if there is no path.'); parser.add_argument('-o', '--out', type=str, metavar="OUTPUT", nargs=1, help='The directory or filename to write to. epub automatically appended if necessary. The target directory must exist.'); parser.add_argument('-s', '--style', type=str, metavar="STYLE", nargs=1, default=["def"], help='The output style to use.'); parser.add_argument('-c', '--cover', type=str, metavar="COVER", nargs=1, default="png", help='The cover generator to use, if the parser does not find it.'); parser.add_argument('--no-cover', action='store_const', default=False, const=True, help='Do not generate a cover page if one does not already exist.'); parser.add_argument('--no-cache', action='store_const', default=False, const=True, help='Force a cache miss and redownload the source material on this request.'); parser.add_argument('--no-overwrite', action='store_const', default=False, const=True, help='Skip if the destination file exists.'); args = parser.parse_args(); try: plugins.load(); run(args); except (RuntimeError, TypeError) as e: print "Error: {0}".format(e); raise;
return name + ext name = os.path.join(path, name) if os.access(name, os.R_OK): return name if os.access(name + ext, os.R_OK): return name + ext # _MAIN_ CODE ################################################################# exec_rel = os.path.join(os.getcwd(), sys.argv[0]) exec_abs = os.path.realpath(exec_rel) path = os.path.dirname(exec_abs) plugGet = plugins.load(path, 'get') plugProc = plugins.load(path, 'proc') parser = argparse.ArgumentParser( description='Find wallpapers online and manipulate them.', add_help=False) parser.add_argument( 'script', nargs='?', help='the wallpaper script to execute (look in subdir scripts)') parser.add_argument('-h', '--help', action='store_true', help='show global or script help and exit') parser.add_argument('-p', '--plugins', nargs='?',
def main(): global actions, command_counter # Load the tiles folder. media.load_textures() plugins.load(plugins.tiles, "tiles") plugins.load(plugins.effects, "effects") plugins.load(plugins.lights, "lights") plugins.load(plugins.workers, "workers", needs_id=False) system_manager = SystemManager() player_control_system = system_manager.add_system(PlayerControlSystem()) collision_system = system_manager.add_system(CollisionSystem()) move_system = system_manager.add_system(MoveSystem(collision_system)) draw_system = system_manager.add_system(DrawSystem(window)) level = Level(0) level_manager.register_level(level) e = Entity(system_manager) e.add_component(PositionComponent(0, 0)) e.add_component(VelocityComponent(0, 0)) e.add_component(PlayerControlComponent()) e.add_component(CollisionComponent(50, 50)) e.add_component(DrawComponent(0)) e.refresh() for x in range(0, 290, 50): e = Entity(system_manager) e.add_component(PositionComponent(x+200, 0)) e.add_component(CollisionComponent(50, 50)) e.add_component(DrawComponent(0)) e.refresh() networking.register_messages() window.framerate_limit = 60 window.vertical_sync_enabled = True running = True old_direction = 0 speed = 5 command_counter = 0 connection = networking.Connection() # FPS variables. frame_counter = 0 fps = 0 old_time = datetime.datetime.now() # Camera variables. speed = 10 em = plugins.get_effect("fire").Effect(0, 0) #print dir(em) plugins.get_worker("sample_worker").crap_work(level, 2, "stone_wall") while running: for event in window.iter_events(): if event.type == sf.Event.CLOSED: running = False if sf.Keyboard.is_key_pressed(sf.Keyboard.ESCAPE): running = False # Super basic camera controls. if sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN): camera.y = camera.y + speed if sf.Keyboard.is_key_pressed(sf.Keyboard.UP): camera.y = camera.y - speed if sf.Keyboard.is_key_pressed(sf.Keyboard.LEFT): camera.x = camera.x - speed if sf.Keyboard.is_key_pressed(sf.Keyboard.RIGHT): camera.x = camera.x + speed player_control_system.update() move_system.update() """ connection.update() command_counter = command_counter + 1 if not direction == old_direction: old_direction = direction message = messages.InputState() message.direction = direction message.tick = command_counter connection.send(message) if not direction == 0: actions.append((command_counter, direction)) x_pos = last_x #util.lerp(float(inter_x), float(last_x), len(actions) / 80.0) y_pos = last_y #util.lerp(float(inter_y), float(last_y), len(actions) / 80.0) #for d in actions: # if d[0] <= last_tick: # actions.remove(d) #print len(actions) for d in actions: x, y = vector.get_vector(d[1]) x_pos = x_pos + x * 5 y_pos = y_pos + y * 5 #print last_tick, command_counter #print x_pos, y_pos """ window.clear(sf.Color.BLACK) #window.draw(sprite) #Draw the tiles. level_manager.update_level(0) level_manager.draw_level_diffuse(0, window) draw_system.draw_light_layer() level_manager.draw_level_lightmap(0, window) # Calculate mouse coordinates. xp = int(sf.Mouse.get_position(window)[0] + camera.x) yp = int(sf.Mouse.get_position(window)[1] + camera.y) # Draw fps text. t = sf.Text(str(fps) + " x:" + str(xp) + " y:" + str(yp)) t.color = sf.Color(155,55,55); window.draw(t) em.update() em.draw(window) """ rect = sf.Shape.rectangle(x_pos - camera.x, y_pos - camera.y, 50, 50, sf.Color.WHITE) window.draw(rect) """ window.display() # Calculate the FPS. frame_counter = frame_counter + 1 new_time = datetime.datetime.now() if new_time.second - old_time.second >= 1: fps = frame_counter old_time = new_time frame_counter = 0 window.close() print "exiting gracefully." sys.exit(0)