class QuoteNotifier:
    def __init__(self):
        self._notifier = Notifier()

    @staticmethod
    def _get_quotes():
        filename = "quotes.json"
        with open(filename, "r") as fh:
            return load(fh)

    def generate(self):
        quotes = self._get_quotes()
        shuffle(quotes)

        quote = choice(quotes)
        print(f"sending \"{quote}\"")

        email = "*****@*****.**"
        subject = "Daily Quote"
        self._notifier.send(email, subject, quote)

    def run(self, interval_mins):
        with LastRun() as lr:
            while True:
                last_run = lr.timestamp
                next_run = last_run + timedelta(minutes=interval_mins)

                now = datetime.utcnow()
                if now > next_run:
                    self.generate()
                    lr.timestamp = datetime.utcnow()

                sleep(10)
Beispiel #2
0
 def __init__(self, persona, mic, profile, house):
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, house)
     self.notifier = Notifier(profile, house)
     self.house = house
Beispiel #3
0
 def __init__(self, mic, profile, logger):
     self.persona = profile['persona']
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, logger)
     self.notifier = Notifier(profile, logger)
     self.logger = logger
Beispiel #4
0
 def __init__(self, persona, mic, profile):
     self._logger = logging.getLogger(__name__)
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile)
     self.notifier = Notifier(profile)
Beispiel #5
0
 def __init__(self, parent = None, settings_path = ""):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('scudcloud.png'))
     self.settings = QSettings(self.settings_path + '/scudcloud.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(ScudCloud.minimized)
     self.installEventFilter(self)
     if self.identifier is None:
         webView.load(QtCore.QUrl(Resources.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
Beispiel #6
0
    def detection_thread(cls):
        while Detector.running:
            motion = cls.detect_motion()
            full_frame = None
            face_frame = None
            name = "Unknown"

            # if there is motion look for faces and save images
            if motion is True:
                Notifier.notify_movement()
                face_frame, name, full_frame = cls.detect_faces()

                if face_frame is None:
                    log('DETECTOR', 'No faces.')
                else:
                    log('DETECTOR', 'Found ' + name)
                    if globals.OFFLINE_MODE:
                        cv2.imshow('Face', face_frame)

                for frame_obj in cls.motion_frames:
                    for movement in frame_obj['motion_boxes']:
                        cv2.imwrite(
                            SNAPSHOT_DIR + pretty_time() + '_motion.jpg',
                            frame_obj['frame'])

                cls.motion_frames = []

            if face_frame is not None:
                Notifier.notify(name)
                cv2.imwrite(SNAPSHOT_DIR + pretty_time() + '_face.jpg',
                            full_frame)
Beispiel #7
0
 def __init__(self, max_age_hours=None):
     self.reddit = Reddit()
     self.reddit.set_filter_func(self._filter_post)
     self.seen_posts = []
     self.notifier = Notifier()
     self.first_run = True
     self.max_age_hours = max_age_hours
Beispiel #8
0
 def __init__(self, parent=None, settings_path=""):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME,
                              Resources.get_path('scudcloud.png'))
     self.settings = QSettings(self.settings_path + '/scudcloud.cfg',
                               QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id(
             "scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     self.stackedWidget = QtGui.QStackedWidget()
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.startURL = Resources.SIGNIN_URL
     if self.identifier is not None:
         self.startURL = self.domain()
     self.addWrapper(self.startURL)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(ScudCloud.minimized)
     self.installEventFilter(self)
     self.statusBar().showMessage('Loading Slack...')
Beispiel #9
0
class Broker():
    def __init__(self, config, door_detector, broker_q: SingletonBlockingQueue,
                 notify_q: SingletonBlockingQueue):
        self.config = config
        self.door_detector = door_detector
        self.broker_q = broker_q
        self.notify_q = notify_q
        self.notifier = Notifier(self.config, notify_q)
        self.stopped = False
        self.t = threading.Thread(target=self.broke)
        self.t.daemon = True
        self.t.start()

    def broke(self):
        while not self.stopped:
            notification_type, notification_payload = self.broker_q.dequeue()
            if notification_type is NotificationTypes.OBJECT_DETECTED:
                if self.config.door_movement_detection:
                    self.door_detector.add_object_state(*notification_payload)
            self.notify_q.enqueue((notification_type, notification_payload))

    def stop(self):
        self.stopped = True
        self.t.join()
        self.notifier.stop()
Beispiel #10
0
def run (repository):
    n = Notifier( title=NOTIFIER_TITLE )
    n.message( message=( "committer::run( '%s' )" % repository ) )

    # - create a lock file
    file_lock = open( Config.PATH_TETHERBALL_COMMIT, 'w' )
    file_lock.write( str( os.getpid() ) )
    file_lock.close()

    # timeout
    time.sleep( SEC_SLEEP )
    try:
        str_last = subprocess.check_output( COMMAND, shell=True )
        ms_now = int( time.time() * 1000 )

        if str_last != '':
            ms_last = int( str_last.strip() )
        else:
            ms_last = ms_now - int(SEC_SLEEP * 1000) - 1

        if (ms_now - ms_last) > (SEC_SLEEP * 1000):
            _run_main(repository)
        else:
            run(repository)
    except Exception, e:
        l = Logger(Config)
        l.debug( 'Failed on committer.py: %s' % e)
Beispiel #11
0
def main():
    while True:
        try:
            notifier = Notifier()
            dc = database.DatabaseController()

            tweets = twitterprovider.get_tweets()
            keywords = []
            for row in dc.get_all_keyword():
                keywords.append(row[1])

            tweet = random.choice(tweets)['text']
            keyword = random.choice(keywords)

            print(tweet, keyword)

            gs = GoogleSearch()
            search_word = tweet + " " + keyword
            gs.search(search_word)
            gs.view()
            result_title = random.choice(gs.get_articles())[0]
            result_url = random.choice(gs.get_articles())[1]
            print(result_title)

            notifier.notify(title=search_word, body=result_title, data=result_url)
            time.sleep(60 * 20)
        except Exception as e:
            pass
def notify(jobid, ntypes):
    log.debug("ntypes in notify is {}".format(ntypes))
    for ntype in ntypes:
        log.info("Putting result into notifier queue:{} \
                with addr:{}".format(ntype["ntype"], ntype["naddr"]))

        notifier = Notifier(config.redisserver, ntype["ntype"])
        notifier.notify(jobid, ntype["naddr"])
    def test_create_event_dispatcher_on_init(self, dispatcher_constructor_mock,
                                             settings):
        dispatcher = Mock()
        dispatcher_constructor_mock.return_value = dispatcher

        notifier = Notifier()

        self.assertEqual(dispatcher, notifier.get_dispatcher())
    def test_invoke_receiver_start(self, sender, receiver, connection_monitor,
                                   dispatcher, settings):
        bot_receiver = Mock()
        receiver.return_value = bot_receiver

        notifier = Notifier()
        notifier.start()

        bot_receiver.start.assert_called()
Beispiel #15
0
 def __init__(self, persona, mic, profile):
     self._logger = logging.getLogger(__name__)
     self.queue = Queue.Queue()
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile)
     self.notifier = Notifier(profile)
     self.mic.queue = self.queue
     self.listener = Listener(mic, profile, self.queue)
Beispiel #16
0
 def __init__(self, config, door_detector, broker_q: SingletonBlockingQueue,
              notify_q: SingletonBlockingQueue):
     self.config = config
     self.door_detector = door_detector
     self.broker_q = broker_q
     self.notify_q = notify_q
     self.notifier = Notifier(self.config, notify_q)
     self.stopped = False
     self.t = threading.Thread(target=self.broke)
     self.t.daemon = True
     self.t.start()
Beispiel #17
0
def lambda_handler(event: dict = None, context=None):
    """Lambda Handler."""

    config = Config()

    log.info(f'App Version: {config.version}')
    log.info(f'Event: {json.dumps(event, indent=2)}')

    for record in event.get('Records'):
        notifier = Notifier(config, record)
        notifier.send_email()
Beispiel #18
0
class BuildAPcWatch(object):
    def __init__(self, max_age_hours=None):
        self.reddit = Reddit()
        self.reddit.set_filter_func(self._filter_post)
        self.seen_posts = []
        self.notifier = Notifier()
        self.first_run = True
        self.max_age_hours = max_age_hours

    def watch(self):
        s = sched.scheduler(time.time, time.sleep)
        s.enter(config.UPDATE_FREQUENCY, 1, self._update, (s, ))
        s.run()

    def _update(self, s):
        print("%s : Updating..." % str(datetime.now()))
        interested_posts = self.reddit.check_subreddit('buildapcsales')
        new_posts = self._identify_new_posts(interested_posts)
        if new_posts:
            self._update_history(new_posts)
            if not self.first_run:
                print("Found interesting posts, sending notifications...")
                self._handle_new_posts(new_posts)
            else:
                self.first_run = False
                print("Ignoring the following posts on first cycle:")
                for post in new_posts:
                    print(post['title'])
        s.enter(config.UPDATE_FREQUENCY, 1, self._update, (s, ))

    def _identify_new_posts(self, posts):
        filter_seen = lambda post: not (post['id'] in self.seen_posts)
        return list(filter(filter_seen, posts))

    def _handle_new_posts(self, new_posts):
        for post in new_posts:
            self.notifier.alert(post)

    def _update_history(self, new_posts):
        self.seen_posts.extend(list(map(lambda p: p['id'], new_posts)))

    def _filter_post(self, post):
        if self.max_age_hours:
            max_age = datetime.utcnow() - timedelta(hours=self.max_age_hours)
            if datetime.fromtimestamp(post['created']) > max_age:
                return
        matches = [
            keyword for keyword in config.KEYWORDS.keys()
            if keyword.lower() in post['title'].lower()
        ]
        for match in matches:
            if config.KEYWORDS[match].lower() in post['title'].lower():
                return post
Beispiel #19
0
 def sendEmail(self, stream_df):
     notifier = Notifier(config=json.loads(s='''
     {
     "cases": {
         "exit_2": {
         "alert_name": "cms-htcondor-es-validation",
         "email": {
             "send_ok": true,
             "to": [
             "*****@*****.**"
             ]
         },
         "entities": [
             "default entity"
         ],
         "snow": {
             "assignment_level": 3,
             "functional_element": "",
             "grouping": true,
             "service_element": "MONITORING"
         },
         "source": "cms-monit-notifier",
         "status": "ERROR",
         "targets": [
             "email",
             "snow"
         ]
         }
     },
     "default_case": {
         "alert_name": "cms-htcondor-es-validation",
         "email": {
         "send_ok": true,
         "to": [
             "*****@*****.**"
         ]
         },
         "entities": [
         "default entity"
         ],
         "source": "cms-monit-notifier",
         "status": "OK",
         "targets": [
         "email"
         ]
     },
     "notification_endpoint": "http://monit-alarms.cern.ch:10011"
     }'''))
     alert_streaming_flow = stream_df.writeStream.foreach(
         lambda alert: notifier.send_notification(
             subject=alert.system,
             description=json.dumps(alert.asDict(), default=str))).start()
     alert_streaming_flow.awaitTermination()
Beispiel #20
0
async def send():
    n = Notifier()
    print("working 111...")
    msg = n.send_notification()
    print("working 222...")
    print(f"msg ::: {msg}")
    if msg == False:
        pass
    else:
        print('TO TELEGRAM')
        print(f'sending to id={msg[0]} with text: {msg[1]} ')
        await bot.send_message(chat_id=int(msg[0]), text=msg[1])
    def test_pass_dispatcher_to_components_on_start(self, sender, receiver,
                                                    connection_monitor,
                                                    dispatcher, settings):
        event_dispatcher = Mock()
        dispatcher.return_value = event_dispatcher

        notifier = Notifier()
        notifier.start()

        sender.assert_called_with(event_dispatcher)
        receiver.assert_called_with(event_dispatcher)
        connection_monitor.assert_called_with(event_dispatcher)
    def test_create_commands(self, cmd_id, cmd_subscribe, cmd_help, sender,
                             receiver, connection_monitor, dispatcher,
                             settings):
        event_dispatcher = Mock()
        dispatcher.return_value = event_dispatcher

        notifier = Notifier()
        notifier.start()

        cmd_help.assert_called_with(event_dispatcher)
        cmd_id.assert_called_with(event_dispatcher)
        cmd_subscribe.assert_called_with(event_dispatcher)
Beispiel #23
0
def main():
    config_json = json.load(codecs.open("config_release.json", "r", encoding="UTF-8"))
    db_config = config_json["database"]
    smtp_config = config_json["smtp"]
    santa_config = config_json["santa"]

    postgres = PostgresInjection(db_config)

    with Shuffler(postgres, santa_config) as shuffler:
        shuffler.work()

    notifier = Notifier(postgres, smtp_config, santa_config)
    notifier.notify_unawared()
Beispiel #24
0
def do_notify(work=45, rest=5):
    Notifier.notify(
        "You've been working "
        + str(work)
        + " minutes! Now take a "
        + str(rest)
        + " minutes rest.",
        "Take a rest!",
    )
    logger.info("Rest: " + get_current_time())
    time.sleep(rest * 60)
    Notifier.notify("Rest is over", "Time to work!")
    logger.info("Back: " + get_current_time())
Beispiel #25
0
    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(5, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #Reset switch
        GPIO.setup(3, GPIO.IN, pull_up_down=GPIO.PUD_UP)  #Off switch
        GPIO.add_event_detect(3, GPIO.BOTH, callback=self.off_pressed)
        GPIO.add_event_detect(5, GPIO.BOTH, callback=self.reset_pressed)
Beispiel #26
0
def run_training(verbose=False, dump_frequency=10):
    '''
    Launches the training in a notify-eval-dump loop.
    In every dump_frequency cycle the whole vocabulary is dumped.
    '''
    global vocs, config
    notifier = Notifier(verbose=verbose, **config["notifications"])

    for i, voc in enumerate(vocs):
        notifier.notify(voc)
        eval_voc(voc)
        if i % dump_frequency == 0:
            dump_all_vocs()
Beispiel #27
0
def main():
    ''' Instantiates reddit and notification notifier '''
    reddit = Reddit()
    notifier = Notifier()
    while True:
        reddit.fetch_latest_posts()
        for notification in reddit.notifications:
            if notification:
                notifier.send_notification(message=notification.get(
                    'title', ''),
                                           link=notification.get('link', ''),
                                           title='iRNBA')
                time.sleep(5)
        time.sleep(FIVE_MINUTES)
	def update_view(manufacturers):
		list_store = gtk.ListStore(gtk.gdk.Pixbuf, str, str)
		list_store.set_sort_column_id(1, gtk.SORT_ASCENDING)
		game_count = 0

		for manufacturer in manufacturers:
			for device in manufacturer.get_devices():
				for folder in device.get_folders():
					for game in folder.get_games():
						list_store.append([CoverLoader.load(util.ApplicationManager.get_path(), manufacturer, device, game, 184, 256), game.get_name(), folder.get_path()])
						game_count += 1

		CoverViewManager._icon_view.set_model(list_store)
		Notifier.create_info_notification("Search Result", "{0} media{1} found".format(game_count, "" if game_count == 1 else "s"))
Beispiel #29
0
    def __init__(self, user):
        self.user = user
        self.notifier = Notifier()
        self._stop = False
        self._portals = {}
        self._broadcasters = {}

        self.lan_listener = threading.Thread(target=self.listen_for_lan_worlds)
        self.lan_listener.daemon = True
        self.lan_listener.start()

        self.redis_listener = threading.Thread(target=self.subscribe_games)
        self.redis_listener.daemon = True
        self.redis_listener.start()
Beispiel #30
0
    def __init__(self, price_change=0.05):

        self.crypto_data = defaultdict(list)
        self.notifier = Notifier()
        self.price_change = price_change
        self.base_url = 'http://api.coingecko.com/api/v3'
        self.top100 = self.get_top_100()

        try:
            current_path = os.getcwd()
            with open(os.path.join(current_path, 'price_history.json'), 'r+') as infile:
                self.crypto_data = json.load(infile)
        except:
            pass
Beispiel #31
0
    def __init__(self):
        path = '/com/github/sheinz/autobrightness'
        bus_loop = DBusQtMainLoop(set_as_default=True)
        self._bus = dbus.SessionBus(mainloop=bus_loop)

        name = dbus.service.BusName('com.github.sheinz.autobrightness',
                                    bus=self._bus)

        dbus.service.Object.__init__(self, name, path)
        self.notifier = Notifier(self._bus)
        self._auto = False
        self._als = AmbientLightSensor()
        self._br_ctrl = BrightnessCtrl(self._bus)
        self._process_timer = QtCore.QTimer()
        self._process_timer.timeout.connect(self.process)
class Conversation(object):

    def __init__(self, persona, speaker, profile):
        self.persona = persona
        self.speaker = speaker
        self.profile = profile
        self.notifier = Notifier(profile)
        self.brain = Brain(speaker, profile)

    def handleForever(self):

        while True:

            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self.speaker.say(notif)

            threshold, transcribed = self.speaker.passiveListen(self.persona)
            if not threshold or not transcribed:
                continue

            input = self.speaker.activeListenToAllOptions(threshold)

            if input:
                self.brain.query(self.profile, transcribed)
Beispiel #33
0
	def __init__(self,conn):
		
		WADebug.attach(self);
		self.conn = conn;
		super(WAEventHandler,self).__init__();
		
		self.notifier = Notifier();
		self.connMonitor = ConnMonitor();
		
		self.connMonitor.connected.connect(self.networkAvailable);
		self.connMonitor.disconnected.connect(self.networkDisconnected);
		
		

		
		#self.connMonitor.sleeping.connect(self.networkUnavailable);
		#self.connMonitor.checked.connect(self.checkConnection);
		
		self.mediaHandlers = []
		self.sendTyping.connect(self.conn.sendTyping);
		self.sendPaused.connect(self.conn.sendPaused);
		self.getLastOnline.connect(self.conn.getLastOnline);
		
		self.connected.connect(self.conn.resendUnsent);
		
		self.pingTimer = QTimer();
		self.pingTimer.timeout.connect(self.sendPing)
		self.pingTimer.start(180000);
Beispiel #34
0
def main():
	event_queue = EventQueue(['slot_end', 'weight_change', 'pill_change', 'presc_man', 'timeslot', 'alert', 'new_pres', 'timer','slot_begin'])
	prescription_manager = PrescriptionManager(event_queue)	
	inventory_manager = InventoryManager(event_queue)
	timer = Timer(event_queue)

	anomaly = Anomaly(inventory_manager, prescription_manager, event_queue)
	notifier = Notifier(event_queue, 'patient')
	print ('All objects created')
	
	prescription = {'id': '1', 'medicines':{'abc':[2, 1, 1, 1, 1, 1, 1, 1], 'def':[2, 2, 1, 2, 1, 1, 2, 1]}, 'expiry_date':'12/11/2018' }
	new_prescription = Event('presc_man', {'type': 'new', 'prescription':prescription})
	event_queue.new_event(new_prescription)
	
	medicines = {'abc': {'pills': 50, 'weight':0.1}, 'def': {'pills': 40, 'weight':0.2} }
	inventory_manager.update_medicines(medicines)
	print ('Initialised all objects')
	print(event_queue._event_queue)
	event_queue.update()
	sleep(1)

	while(True):
		slot_num= input('>>>')
		if slot_num != '-1':
			slot_num = int(slot_num)
			weight = float(input())
			event = Event('weight_change', {'slot': slot_num, 'weight': weight, 'time': get_current_time()})
			event_queue.new_event(event)
		print(event_queue._event_queue)
		#print("In main")
		event_queue.update()
		sleep(60)
Beispiel #35
0
 def __init__(self, persona, mic, profile):
     self._logger = logging.getLogger(__name__)
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile)
     self.notifier = Notifier(profile)
Beispiel #36
0
 def __init__(self, parent = None, settings_path = ""):
     super(zcswebapp, self).__init__(parent)
     self.setWindowTitle('zcswebapp')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('zcswebapp.png'))
     self.settings = QSettings(self.settings_path + '/zcswebapp.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("zcswebapp.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(zcswebapp.minimized)
     self.installEventFilter(self)
     if self.identifier is None:
         webView.load(QtCore.QUrl(Resources.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
Beispiel #37
0
 def __init__(self, parent=None):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.notifier = Notifier(self.APP_NAME, get_resource_path('scudcloud.png'))
     self.settings = QSettings(expanduser("~")+"/.scudcloud", QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.leftPane = LeftPane(self)
     self.cookiesjar = PersistentCookieJar(self)
     webView = Wrapper(self)
     webView.page().networkAccessManager().setCookieJar(self.cookiesjar)
     self.stackedWidget = QtGui.QStackedWidget()
     self.stackedWidget.addWidget(webView)
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.addMenu()
     self.tray = Systray(self)
     self.systray()
     self.installEventFilter(self)
     self.zoom()
     if self.identifier is None:
         webView.load(QtCore.QUrl(self.SIGNIN_URL))
     else:
         webView.load(QtCore.QUrl(self.domain()))
     webView.show()
Beispiel #38
0
def main():
    try:
        args = parse_args(sys.argv)
        loop = asyncio.get_event_loop()

        os_manager = OSManager()
        os_type = os_manager._get_current_os()
        notifier = Notifier(os_type)
        process_manager = ProcessManager(notifier)

        plugin = Plugin(port=args['port'],
                        pluginUUID=args['pluginUUID'],
                        registerEvent=args['registerEvent'],
                        info=args['info'],
                        loop=loop,
                        process_manager=process_manager,
                        os_manager=os_manager)

        loop.run_until_complete(
            asyncio.gather(plugin.listen(), process_manager.process()))
        loop.run_forever()
        loop.stop()
        loop.close()
    except Exception as err:
        logging.critical(err)
        loop.stop()
        loop.close()
Beispiel #39
0
 def __init__(self, mic, profile, logger):
     self.persona = profile['persona']
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile, logger)
     self.notifier = Notifier(profile, logger)
     self.logger = logger
Beispiel #40
0
 def __init__(self, parent = None, settings_path = ""):
     super(ScudCloud, self).__init__(parent)
     self.setWindowTitle('ScudCloud')
     self.settings_path = settings_path
     self.notifier = Notifier(Resources.APP_NAME, Resources.get_path('scudcloud.png'))
     self.settings = QSettings(self.settings_path + '/scudcloud.cfg', QSettings.IniFormat)
     self.identifier = self.settings.value("Domain")
     if Unity is not None:
         self.launcher = Unity.LauncherEntry.get_for_desktop_id("scudcloud.desktop")
     else:
         self.launcher = DummyLauncher(self)
     self.webSettings()
     self.leftPane = LeftPane(self)
     self.stackedWidget = QtGui.QStackedWidget()
     centralWidget = QtGui.QWidget(self)
     layout = QtGui.QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     layout.setSpacing(0)
     layout.addWidget(self.leftPane)
     layout.addWidget(self.stackedWidget)
     centralWidget.setLayout(layout)
     self.setCentralWidget(centralWidget)
     self.startURL = Resources.SIGNIN_URL
     if self.identifier is not None:
         self.startURL = self.domain()
     self.addWrapper(self.startURL)
     self.addMenu()
     self.tray = Systray(self)
     self.systray(ScudCloud.minimized)
     self.installEventFilter(self)
     self.statusBar().showMessage('Loading Slack...')
Beispiel #41
0
    def save_fetched_data(visa_type: str, location: str,
                          available_visa_date: List[int]):
        """ Write the visa status to the end of the file."""
        logging_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        year, month, day = available_visa_date
        available_date = None if year == month == day == 0 else datetime(
            year, month, day)
        embassy = G.USEmbassy.get_embassy_by_loc(location)

        # decide if a notification should be send BEFORE writing the new data into file
        sent_notification = Notifier.notify_visa_status_change(
            visa_type, embassy, available_date)
        if sent_notification:
            LOGGER.info('Sent notification for %s - %s-%s %s', logging_time,
                        visa_type, location, available_date)

        try:
            LOGGER.debug('WRITING TO DATABASE %s - %s-%s %s', logging_time,
                         visa_type, location, available_date)
            writting_start = datetime.now()
            DB.VisaStatus.save_fetched_visa_status(
                visa_type=visa_type,
                embassy_code=embassy.code,
                write_time=datetime.now(),
                available_date=available_date)
            writting_finish = datetime.now()
        except:
            LOGGER.error(
                'Catch an error when saveing fetched result to database',
                traceback.format_exc())
        else:
            LOGGER.debug('WRITE TO DATABASE SUCCESS %s - %s-%s %s',
                         logging_time, visa_type, location, available_date)
            LOGGER.debug('WRITTING TAKES %f seconds',
                         (writting_finish - writting_start).total_seconds())
def test_notify():
    ntype1 = str(uuid.uuid1())
    ntype2 = str(uuid.uuid1())

    ntypes = [{"ntype": ntype1, "naddr": "127.0.0.1"}, {"ntype": ntype2, "naddr": "*****@*****.**"}]

    notifier1 = Notifier(config.redisserver, ntype1)
    notifier2 = Notifier(config.redisserver, ntype2)

    notify("test-id", ntypes)

    jid, data = notifier1.get()
    assert data == "127.0.0.1"

    jid, data = notifier2.get()
    assert data == "*****@*****.**"
Beispiel #43
0
def run (path, repository):
    #imports
    import daemon

    # daemonize
    pid = daemon.createDaemon()

    # spit pid
    try:
        file_pid = open( os.path.join( Config.PATH_TETHERBALL_PROC, repository ), 'w' )
        file_pid.write( str(pid) )
        file_pid.close()
    except Exception, e:
        # l = Logger(Config)
        # l.debug( "Failed to write pid into file: %s" )
        n = Notifier( title=NOTIFIER_TITLE )
        n.message( message=("Failed to write pid into file: %s" % e) )
Beispiel #44
0
 def __init__(self, persona, mic, profile):
     self._logger = logging.getLogger(__name__)
     self.queue = Queue.Queue()
     self.persona = persona
     self.mic = mic
     self.profile = profile
     self.brain = Brain(mic, profile)
     self.notifier = Notifier(profile)
     self.mic.queue = self.queue
     self.listener = Listener(mic, profile, self.queue)
Beispiel #45
0
class Conversation(object):

    def __init__(self, persona, mic, profile, isPassiveEnabled):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.isPassiveEnabled = isPassiveEnabled

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed, passivePhrases = \
                self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue

            self._logger.info("Keyword '%s' has been said!", self.persona)

            if self.isPassiveEnabled is True and len(passivePhrases) != 0:

                input = passivePhrases
                self._logger.debug("Checking for passive phrase '%s' with " +
                                   "threshold: %r", input, threshold)

            else:

                self._logger.debug("Started to listen actively with " +
                                   "threshold: %r", threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with " +
                                   "threshold: %r", threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Beispiel #46
0
    def __init__(self, name, graph_type):
        """Create a Graph instance

        :type name: str
        :type graph_type: str
        :rtype: Graph
        """
        self.name = name
        self.graph_type = graph_type
        self.root_id = None
        self.notifier = Notifier()
class Conversation(object):

    def __init__(self, persona, mic, profile, house):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile, house)
        self.notifier = Notifier(profile, house)
        self.house = house

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        if any(x in text.upper() for x in ["SPOTIFY", "MUSIC"]):
            # check if mpd client is running
            try:
                client = MPDClient()
                client.timeout = None
                client.idletimeout = None
                client.connect("localhost", 6600)
            except:
                self.mic.say(
                    "I'm sorry. It seems that Spotify is not enabled. Please read the documentation to learn how to configure Spotify.")
                return

            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif
                self.mic.say(notif)
            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")
Beispiel #48
0
def main():
  logging.basicConfig(
    filename = 'info.log',
    level    = logging.DEBUG,
    format   = '%(asctime)s - %(levelname)s - %(message)s'
  )

  logging.info('Start')

  # JSON API
  # client     = JsonApi(config.app_id)
  # latest_czk = client.get_latest_usd_to_czk_rate()

  # cnb.cz text file
  client     = CnbTextFile()
  latest_czk = client.get_latest_usd_to_czk_rate()
  # latest_czk = 19.82228 # Debug

  notifier = Notifier(config.email_settings)
  notifier.send(latest_czk)

  logging.info('Finish')
Beispiel #49
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            # Word we listen for to self terminate
            TERMINATE = 'GOODBYE'

            self._logger.debug("Started listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)
            threshold, transcribed = self.mic.passiveListen(self.persona, TERMINATE)
            self._logger.debug("Stopped listening for keyword '%s' or '%s'",
                               self.persona, TERMINATE)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            # Terminate on goodbye
            if transcribed == TERMINATE:
                friendly.goodbye(self.mic, self.profile)
                sys.exit(0)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while on == True:

            nu()
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                messages = ["what?",
                            "what did you say",
                            "Say that again?", "speak the f**k up", "i cant f*****g hear you", "blah blah blah", "did you say something?"]

                message = random.choice(messages)
                zip2()
                self.mic.say(message)
class HudsonNotifier:
    def __init__(self):
        dir_path = os.path.dirname(__file__)
        LOGO_IMG = os.path.abspath(dir_path + "/../imgs/logo.png")

        self.statusIcon = gtk.StatusIcon()
        self.statusIcon.set_from_file(LOGO_IMG)
        self.statusIcon.set_visible(True)
        self.statusIcon.set_tooltip("Hudson notifier")

        self.menu = gtk.Menu()
        #    self.menuItem = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        #    self.menuItem.connect('activate', self.prefs_cb, self.statusIcon)
        #    self.menu.append(self.menuItem)
        self.menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        self.menuItem.connect("activate", self.quit_cb, self.statusIcon)
        self.menu.append(self.menuItem)

        self.statusIcon.connect("popup-menu", self.popup_menu_cb, self.menu)
        self.statusIcon.set_visible(1)
        self.notifier = Notifier()

        gobject.timeout_add(6000, self.poll)
        gtk.main()

    def getUrls(self):
        fileHandle = open("config.txt")
        return fileHandle.readlines()

    def poll(self):
        urls = self.getUrls()
        return self.notifier.poll(urls)

    def prefs_cb(self, widget, event, data=None):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_border_width(10)

        button = gtk.Button("Close")
        button.connect_object("clicked", gtk.Widget.destroy, window)
        window.add(button)
        button.show()
        window.show()

    def quit_cb(self, widget, data=None):
        gtk.main_quit()

    def popup_menu_cb(self, widget, button, time, data=None):
        if button == 3:
            if data:
                data.show_all()
                data.popup(None, None, gtk.status_icon_position_menu, 3, time, self.statusIcon)
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while True:
            # Print notifications until empty
            try:
                notifications = self.notifier.getAllNotifications()
                for notif in notifications:
                    self._logger.info("Received notification: '%s'", str(notif))

                self._logger.debug("Started listening for keyword '%s'",
                                   self.persona)
                threshold, transcribed = self.mic.passiveListen(self.persona)
                self._logger.debug("Stopped listening for keyword '%s'",
                                   self.persona)

                if not transcribed or not threshold:
                    self._logger.info("Nothing has been said or transcribed.")
                    continue
                self._logger.info("Keyword '%s' has been said!", self.persona)

                self._logger.debug("Started to listen actively with threshold: %r",
                                   threshold)
                input = self.mic.activeListenToAllOptions(threshold)
                self._logger.debug("Stopped to listen actively with threshold: %r",
                                   threshold)

                if input:
                    self.brain.query(input)
                else:
                    self.mic.say("Pardon?")
            except KeyboardInterrupt:
                print "Keyboard Interrupt!"
                try:
                    sys.exit(0)
                except SystemExit:
                    os._exit(0)
Beispiel #53
0
class Conversation(object):
  def __init__(self, persona, mic, server, profile):
    self._logger = logging.getLogger(__name__)
    self.persona = persona
    self.mic = mic
    self.profile = profile
    self.brain = Brain(mic, profile)
    self.notifier = Notifier(profile)
    self.server = server

  def handleForever(self):
    """
    Delegates user input to the handling function when activated.
    """
    self._logger.info("Starting to handle conversation with keyword '%s'.",
                      self.persona)
    while True:
      # Print notifications until empty
      notifications = self.notifier.getAllNotifications()
      for notif in notifications:
        self._logger.info("Received notification: '%s'", str(notif))

      if 'jasper.server.enabled' in self.profile and self.profile['jasper.server.enabled']:
        inputDevice = self.server
        self._logger.debug("Listening to tcp socket with Jasper server")
      else:
        inputDevice = self.mic
        self._logger.debug("Listening to attached microphone")

      self._logger.debug("Started listening for keyword '%s'",
                         self.persona)
      threshold, transcribed = inputDevice.passiveListen(self.persona)
      self._logger.debug("Stopped listening for keyword '%s'",
                         self.persona)

      if not transcribed or not threshold:
        self._logger.info("Nothing has been said or transcribed.")
        continue
      self._logger.info("Keyword '%s' has been said!", self.persona)

      self._logger.debug("Started to listen actively with threshold: %r",
                         threshold)
      input = inputDevice.activeListenToAllOptions(threshold)
      self._logger.debug("Stopped to listen actively with threshold: %r",
                         threshold)

      if input:
        self.brain.query(input)
      else:
        inputDevice.say("Pardon?")
Beispiel #54
0
	def __init__(self,conn):
		
		WADebug.attach(self);
		self.conn = conn;
		super(WAEventHandler,self).__init__();
		
		self.notifier = Notifier();
		self.connMonitor = ConnMonitor();
		
		self.connMonitor.connected.connect(self.networkAvailable);
		self.connMonitor.disconnected.connect(self.networkDisconnected);
		
		self.account = "";

		self.blockedContacts = "";

		self.resizeImages = False;
		self.disconnectRequested = False

		#self.interfaceHandler = LibInterfaceHandler()
		
		self.jid = self.conn.jid
		
		self.username = self.jid.split('@')[0]

		self.interfaceHandler = LibInterfaceHandler(self.username)
		self.registerInterfaceSignals()
		
		self.interfaceVersion = self.interfaceHandler.call("getVersion")
		
		self._d("Using Yowsup version %s"%self.interfaceVersion)

		
		self.listJids = [];

		self.mediaHandlers = []
		self.sendTyping.connect(lambda *args: self.interfaceHandler.call("typing_send", args));
		self.sendPaused.connect(lambda *args: self.interfaceHandler.call("typing_paused",args));
		self.getLastOnline.connect(lambda *args: self.interfaceHandler.call("presence_request", args));
		self.getGroupInfo.connect(lambda *args: self.interfaceHandler.call("group_getInfo", args));
		self.createGroupChat.connect(lambda *args: self.interfaceHandler.call("group_create", args));
		self.addParticipants.connect(lambda *args: self.interfaceHandler.call("group_addParticipants", args));
		self.removeParticipants.connect(lambda *args: self.interfaceHandler.call("group_removeParticipants", args));
		self.getGroupParticipants.connect(lambda *args: self.interfaceHandler.call("group_getParticipants", args));
		self.endGroupChat.connect(lambda *args: self.interfaceHandler.call("group_end", args));
		self.setGroupSubject.connect(lambda jid, subject: self.interfaceHandler.call("group_setSubject", (jid, self.strip(subject))));
		self.getPictureIds.connect(lambda *args: self.interfaceHandler.call("picture_getIds", args));
		self.changeStatus.connect(lambda status: self.interfaceHandler.call("profile_setStatus", (self.strip(status),)));

		self.state = 0
Beispiel #55
0
class NotifyFlow:
  NotifyFlows = [7000, 7500, 8000, 8300]
  def __init__(self):
    self.flowIter = iter(self.NotifyFlows)
    self.notifyFlows = next(self.flowIter)
    self.notifier = Notifier()
    self.needUpdate = True

  def checkAndNotify(self, flow):
    if datetime.now().hour == 0 and self.needUpdate:
      self.flowIter = iter(self.NotifyFlows)
      self.needUpdate = False
      self._nextFlow()
    else:
      self.needUpdate = True
    if flow > self.notifyFlows:
      self.notifier.notify("Notice: Now flow is {0}".format(flow))
      self._nextFlow()

  def _nextFlow(self):
    try:
      self.notifyFlows = next(self.flowIter)
    except StopIteration:
      pass
    def __init__(self):
        path = '/com/github/sheinz/autobrightness'
        bus_loop = DBusQtMainLoop(set_as_default=True)
        self._bus = dbus.SessionBus(mainloop=bus_loop)

        name = dbus.service.BusName('com.github.sheinz.autobrightness',
                                    bus=self._bus)

        dbus.service.Object.__init__(self, name, path)
        self.notifier = Notifier(self._bus)
        self._auto = False
        self._als = AmbientLightSensor()
        self._br_ctrl = BrightnessCtrl(self._bus)
        self._process_timer = QtCore.QTimer()
        self._process_timer.timeout.connect(self.process)
Beispiel #57
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        
        try_num =0
        while True:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            #msg = xbee.Receive()   #this is where we get our serial data during downtime
            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self._logger = logging.getLogger(__name__)
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)
        self.shutdown = False

    def handleForever(self):
        """
        Delegates user input to the handling function when activated.
        """
        self._logger.info("Starting to handle conversation with keyword '%s'.",
                          self.persona)
        while not self.shutdown:
            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                self._logger.info("Received notification: '%s'", str(notif))

            self._logger.debug("Started listening for keyword '%s'",
                               self.persona)
            threshold, transcribed = self.mic.passiveListen(self.persona)
            self._logger.debug("Stopped listening for keyword '%s'",
                               self.persona)

            if not transcribed or not threshold:
                self._logger.info("Nothing has been said or transcribed.")
                continue
            self._logger.info("Keyword '%s' has been said!", self.persona)

            self._logger.debug("Started to listen actively with threshold: %r",
                               threshold)
            self.mic.say(random.choice(["your wish is my command", "what is thy bidding, my master", "I live to serve"]))
            input = self.mic.activeListenToAllOptions(threshold)
            self._logger.debug("Stopped to listen actively with threshold: %r",
                               threshold)

            if input:
                self.brain.query(input)
            else:
                self.mic.say("Pardon?")
Beispiel #59
0
class Conversation(object):

    def __init__(self, persona, mic, profile):
        self.persona = persona
        self.mic = mic
        self.profile = profile
        self.brain = Brain(mic, profile)
        self.notifier = Notifier(profile)

    def delegateInput(self, text):
        """A wrapper for querying brain."""

        # check if input is meant to start the music module
        '''
	if any(x in text.upper() for x in ["SPOTIFY","MUSIC"]):
            self.mic.say("Please give me a moment, I'm loading your Spotify playlists.")
            music_mode = MusicMode(self.persona, self.mic)
            music_mode.handleForever()
            return
        '''

        self.brain.query(text)

    def handleForever(self):
        """Delegates user input to the handling function when activated."""
        while True:

            # Print notifications until empty
            notifications = self.notifier.getAllNotifications()
            for notif in notifications:
                print notif

            try:
                threshold, transcribed = self.mic.passiveListen(self.persona)
            except:
                continue

            if threshold:
                input = self.mic.activeListen(threshold)
                if input:
                    self.delegateInput(input)
                else:
                    self.mic.say("Pardon?")