Esempio n. 1
0
def main():
    """
	Setup and run all subroutines.
	"""
    global socks, queue, authed, sessions, queuehash, upkeepThread, pluginUpkeeps

    pluginList = plugins.getPlugins()
    pluginUpkeeps = list(
        filter(lambda module: hasattr(module, "upkeep"), pluginList))
    comm.buildCommands(pluginList)
    laserqueue.buildLists(pluginList)

    # Load the queue if -b is used
    if args.backup:
        if os.path.exists("cache.json"):
            queue = laserqueue.Queue.load(open("cache.json"))
        else:
            json.dump({}, open("cache.json", "w"))

    color_print("Serving WebSockets on 0.0.0.0 port {port} ...",
                port=config["port"])

    # Create the upkeep thread
    upkeepThread = threading.Thread(target=upkeep)
    upkeepThread.daemon = True
    upkeepThread.start()

    # Create the server event loop
    start_server = websockets.serve(server, "0.0.0.0", config['port'])
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(start_server)
        loop.run_forever()
    except KeyboardInterrupt:
        quit(0)
Esempio n. 2
0
def main():
	"""
	Setup and run all subroutines.
	"""
	global socks, queue, authed, sessions, queuehash, upkeepThread, pluginUpkeeps

	pluginList = plugins.getPlugins()
	pluginUpkeeps = list(filter(lambda module: hasattr(module, "upkeep"), pluginList))
	comm.buildCommands(pluginList)
	laserqueue.buildLists(pluginList)

	# Load the queue if -b is used
	if args.backup:
		if os.path.exists("cache.json"):
			queue = laserqueue.Queue.load(open("cache.json"))
		else:
			json.dump({}, open("cache.json", "w"))

	color_print("Serving WebSockets on 0.0.0.0 port {port} ...", port=config["port"])

	# Create the upkeep thread
	upkeepThread = threading.Thread(target=upkeep)
	upkeepThread.daemon = True
	upkeepThread.start()

	# Create the server event loop
	start_server = websockets.serve(server, "0.0.0.0", config['port'])
	loop = asyncio.get_event_loop()
	try:
		loop.run_until_complete(start_server)
		loop.run_forever()
	except KeyboardInterrupt:
		quit(0)
Esempio n. 3
0
def process(messages):
    """
    This function processes the updates in the Updates URL at Telegram
    for finding commands, karma changes, config, etc
    """

    logger = logging.getLogger(__name__)

    # check if Log level has changed
    loglevel()

    # Main code for processing the karma updates
    date = 0
    lastupdateid = 0
    logger.info(msg="Initial message at %s" % date)
    texto = ""
    count = 0

    # Process each message available in URL and search for karma operators
    for message in messages:
        # Count messages in each batch
        count += 1

        # Call plugins to process message
        for i in plugins.getPlugins():
            plug = plugins.loadPlugin(i)
            logger.debug(msg="Processing plugin: %s" % i["name"])
            plug.run(message=message)

        msgdetail = getmsgdetail(message)

        # Update last message id to later clear it from the server
        if msgdetail["update_id"] > lastupdateid:
            lastupdateid = msgdetail["update_id"]

        # Write the line for debug
        messageline = "TEXT: %s : %s : %s" % (msgdetail["chat_name"], msgdetail["name"], msgdetail["text"])
        texto = msgdetail["text"]
        logger.debug(msg=messageline)

    logger.info(msg="Last processed message at: %s" % date)
    logger.debug(msg="Last processed update_id : %s" % lastupdateid)
    logger.debug(msg="Last processed text: %s" % texto)
    logger.info(msg="Number of messages in this batch: %s" % count)

    # clear updates (marking messages as read)
    clearupdates(offset=lastupdateid + 1)
Esempio n. 4
0
def main():
    """
    Main code for the bot
    """

    # Main code
    logger = logging.getLogger(__name__)

    # Set database name in config
    if options.database:
        plugin.config.setconfig(key='database', value=options.database)

    if not logger.handlers:
        conflogging()

    logger.info(msg="Started execution")

    if not plugin.config.config(key='sleep'):
        plugin.config.setconfig(key='sleep', value=10)

    # Check if we've the token required to access or exit
    if not plugin.config.config(key='token'):
        if options.token:
            token = options.token
            plugin.config.setconfig(key='token', value=token)
        else:
            msg = "Token required for operation, please check"
            msg += " https://core.telegram.org/bots"
            logger.critical(msg)
            sys.exit(1)

    # Check if we've URL defined on DB or on cli and store
    if not plugin.config.config(key='url'):
        if options.url:
            plugin.config.setconfig(key='url', value=options.url)

    # Check if we've owner defined in DB or on cli and store
    if not plugin.config.config(key='owner'):
        if options.owner:
            plugin.config.setconfig(key='owner', value=options.owner)

    # Initialize modules
    for i in plugins.getPlugins():
        plug = plugins.loadPlugin(i)
        logger.debug(msg="Processing plugin initialization: %s" % i["name"])
        plug.init()

    # Check operation mode and call process as required
    if options.daemon or plugin.config.config(key='daemon'):
        plugin.config.setconfig(key='daemon', value=True)
        logger.info(msg="Running in daemon mode")
        while plugin.config.config(key='daemon') == 'True':
            process(getupdates())
            sleep(int(plugin.config.config(key='sleep')))
    else:
        logger.info(msg="Running in one-shoot mode")
        process(getupdates())

    logger.info(msg="Stopped execution")
    logging.shutdown()
    sys.exit(0)
Esempio n. 5
0
	def getPlugins(self):
		return plugins.getPlugins()
Esempio n. 6
0
phrase = phrase['hypotheses'][0]['utterance']

# output to stderr for debug purposes
sys.stderr.write(phrase + "\n")

# strip "computer" and "caroline" from beginning of phrase
if phrase.lower().startswith("computer "):
    phrase = phrase[9:]
if phrase.lower().startswith("caroline "):
    phrase = phrase[9:]

# set global variable phrase so plugins can access it
plugins.setPhrase(phrase)

# find and execute plugins
plugins.getPlugins()

# the following code will run only if the plugins don't run and exit

key = os.environ.get('WOLFRAM_API_KEY')
if not key:
    print "I can't contact the knowledge base without an API key. Set one in an environment variable."
    sys.exit(0)
client = wolframalpha.Client(key)

# ask wolfram alpha for any info based on the query
res = client.query(phrase)

if len(res.pods) == 0:
    print "I couldn't find any results for the query, '" + phrase + "'"
    sys.exit(0)
Esempio n. 7
0
 def getPlugins(self):
     return plugins.getPlugins()
Esempio n. 8
0
def add(req, **kw):
    serv_plug = plugins.getPlugins()
    if serv_plug == None or 'protocol' in kw  and not kw['protocol']  in serv_plug :
        logger.error('Protocol %s is not exisit'%(kw['protocol']))
        raise Http404
    return serv_plug[kw['protocol']]['pyobject'].views.add(req, **kw)
Esempio n. 9
0
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('Scrapbook (' + config.notespath + ')')
        self.setWindowIcon(
            QtGui.QIcon(
                os.path.join(os.path.dirname(os.path.realpath(__file__)),
                             "W_Book01.png")))
        #Setup menu bar
        self.menubar = self.menuBar()
        self.fileMenu = self.menubar.addMenu('&File')
        self.tools = self.menubar.addMenu('&Tools')
        self.help = self.menubar.addMenu('&Help')

        opennotebook = QAction('Open Notebok Folder', self)

        def opennb(*a):
            b = QFileDialog.getExistingDirectory(
                self, "Open Directory", os.path.expanduser("~"),
                QFileDialog.ShowDirsOnly
                | QFileDialog.DontResolveSymlinks)
            subprocess.Popen([os.path.realpath(__file__), b], close_fds=True)

        opennotebook.triggered.connect(opennb)
        self.fileMenu.addAction(opennotebook)

        setnotebook = QAction('Set as Default Notebook', self)

        def setnb(*a):
            if config.notespath:
                config.setNotebookLocation(config.notespath)

        setnotebook.triggered.connect(setnb)
        self.fileMenu.addAction(setnotebook)

        showabout = QAction('About', self)

        def f(*a):
            self.tabs.open("mdnotes://about.html")

        showabout.triggered.connect(f)
        self.help.addAction(showabout)

        #Make a folder for each of our builtins in the builtins folder. Right now it's just an example though
        for i in [
                i for i in os.listdir(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 'builtins'))
                if os.path.isfile(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 'builtins', i))
        ]:
            a = QAction(i[:-8], self)

            def f(*a):
                self.tabs.open(
                    os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 'builtins', i))

            a.triggered.connect(f)
            self.tools.addAction(a)

        for i in plugins.getPlugins("tool"):
            a = QAction(i.title, self)

            def f(*a):
                i.function(self.tabs)

            a.triggered.connect(f)
            self.tools.addAction(a)
        #
        # editcss = QAction('Edit User CSS Theme', self)
        # def f(*a):
        #     self.tabs.open(os.expanduser("~/.mdnotes/style.css"))
        # editcss.triggered.connect(f)

        showtodos = QAction('Todo List', self)

        #Use x[0] as a mutable flag to stop the search
        x = [0]

        def stop(o):
            x[0] = 1

        def f(*a):
            if not config.notespath:
                return
            html = "<style>" + styles.style + '</style>' + """<h1>Todos in this notebook</h2><p>Add todo entries by putting todo: something, Todo: A thing, or TODO: this thing
            anywhere in any .md note in the notebook folder, with one todo per line. There should not be any letters of numbers before the todo: marker.
              Change them to done: to indicate you have done them.<dl>"""
            tab = self.tabs.openVirtual(html=html, title="Todo List")
            for f, c in (findTodos(config.notespath)):
                #Keep the program responsive
                app.processEvents()
                if x[0]:
                    break
                html = html + '<dt>In <a href="' + f + '">' + f + '</a>:</dt><dd><ul>'
                for i in c:
                    todo = str(i)
                    text = re.search(
                        "((TODO)|(Todo)|(todo)|(done)|(Done)|(DONE)):(.*)",
                        todo).group(8)
                    if re.match("^.*((done)|(Done)|(DONE)):", todo):
                        html += ("<li><s>" + text + "</s></li>")
                    else:
                        #Exclamation points make it bold.
                        if "!" in todo:
                            html += ("<li><b>" + text + "</b></li>")
                        else:
                            html += ("<li>" + text + "</li>")
                html += ("</li></dd>")
            html += '</dl>'
            tab.setHtml(html)

        showtodos.triggered.connect(f)
        self.tools.addAction(showtodos)

        self.split = QSplitter()
        self.setCentralWidget(self.split)
        self.tabs = Notebook()
        self.browser = Browser(self.tabs)
        self.split.addWidget(self.browser)

        self.split.addWidget(self.tabs)
        self.split.setSizes([250, 900])