Exemple #1
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)
Exemple #2
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...')
Exemple #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
def run():
    fObj = open("NotifierConfig.json", "r")
    config = json.load(fObj)

    fromAddr = config["email"]["fromAddr"]
    toAddr = config["email"]["toAddr"]

    msg = MIMEMultipart()
    msg["From"] = fromAddr
    msg["To"] = toAddr
    msg["Subject"] = config["email"]["subject"]["eth"]

    senderAddr = fromAddr
    senderPasswd = config["email"]["passwd"]

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(senderAddr, senderPasswd)

    notifier = Notifier(msg, server, config, "eth", "usd")

    scheduler = BlockingScheduler()
    scheduler.add_job(notifier.sendUpdate,
                      "interval",
                      minutes=config["interval"]["min"])
    scheduler.start()

    server.close()
Exemple #5
0
    def __init__(self, master=Tk()):
        Frame.__init__(self, master)

        configuration = Configuration().get_values()

        self.__pomodorotime = configuration['pomodoro']  #minute of work
        self.__shortbreaktime = configuration[
            'shortbreak']  #minute of short break
        self.__longbreaktime = configuration[
            'longbreak']  #minute of long break
        #number of session before a long break
        self.__sprintsessions = configuration['beforelongbreak']
        alarm = configuration['alarm']

        self.__npomodoro = 0  # number of session done
        self.__notifier = Notifier(alarm)
        self.__working = False

        self.master.title("Pomodoro Timer")
        self.master.minsize(230, 220)
        self.master.maxsize(400, 300)
        self.master.configure(background='white')

        self.master.tk.call('wm', 'iconphoto', self.master._w,
                            PhotoImage(file='./res/icon.png'))

        self.pack()
        self.__createWidgets()
Exemple #6
0
    def check_for_high_battery(self, high_level: int = 80) -> None:
        """
        Checking of low battery percentage. By default it check for 80
        Args:
            high_level: battery percentage number
        """
        high_battery_flag = False
        notifier = Notifier(self._app_name,
                            self._high_battery_summary,
                            self._high_battery_message,
                            self._high_battery_icon)

        try:
            while True:
                percentage = self._battery.get_percentage()
                plugged = self._battery.is_plugged()

                if percentage >= high_level:
                    if plugged is False and high_battery_flag:
                        notifier.close()
                        high_battery_flag = False

                    if plugged and high_battery_flag is False:
                        notifier.show(URGENCY_CRITICAL)
                        high_battery_flag = True

                else:
                    high_battery_flag = False

                time.sleep(3)

        except KeyboardInterrupt:
            print("User interrupted!")
Exemple #7
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
Exemple #8
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()
def prepare_content_and_notify(simple_out, target_email, slack_channel):
    filtered_output = check_if_output_falls_within_day_range(simple_out)
    notifier = Notifier()
    if not filtered_output:
        print(
            "Notifications not being sent. Breaches are older than {days} days."
            .format(days=days_range))
        return

    filtered_breach_info = [{
        ('Total accounts Breached' if req_key == 'PwnCount' else req_key):
        item[req_key]
        for req_key in REQUIRED_BREACH_FIELDS
    } for item in filtered_output]
    if slack_channel:
        formatted_text = format_slack_message(filtered_breach_info,
                                              target_email)
        notifier.slack_notify(slack_channel, formatted_text)

    if check_email_params(EMAIL_CONFIG) and send_email:
        email_text = unescape(
            get_email('email_template.html', filtered_breach_info,
                      target_email))
        email = Email(send_from=EMAIL_CONFIG['send_from'],
                      send_to=target_email + ',' + EMAIL_CONFIG['send_to'],
                      host=EMAIL_CONFIG['host'],
                      port=EMAIL_CONFIG['port'],
                      username=EMAIL_CONFIG['username'],
                      password=EMAIL_CONFIG['password'],
                      content=email_text,
                      subject=EMAIL_CONFIG['subject'])
        notifier.email_notify(email)
Exemple #10
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
Exemple #11
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
Exemple #12
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)
Exemple #13
0
 def OnAddedToSpace(self, ballpark, dbspacecomponent):
     persister = Persister(ballpark.solarsystemID, self.itemID,
                           dbspacecomponent)
     bountyEscrowBonus, bounties = persister.GetStateForSystem()
     iskRegistry = IskRegistry(bounties)
     iskMover = IskMover(ballpark.broker.account)
     itemCreator = GetItemCreator(ballpark.inventory2, ballpark,
                                  self.attributes.tagTypeIDs.keys())
     escrow = Escrow(self, ballpark, iskRegistry, iskMover, itemCreator,
                     persister)
     item = ballpark.inventory2.GetItem(self.itemID)
     eventLogger = EventLogger(ballpark.broker.eventLog,
                               ballpark.solarsystemID, item.ownerID,
                               self.itemID)
     notifier = Notifier(ballpark.broker.notificationMgr)
     self.rangeNotifier = RangeNotifier(ballpark.solarsystemID, ballpark,
                                        ballpark.broker.machoNet,
                                        self.GetWallclockTime)
     ballpark.proximityRegistry.RegisterForProximity(
         self.itemID, 30000, self.rangeNotifier.PlayerInRange)
     lock = Lock(self)
     self.warpScrambler = WarpScrambler(self.itemID, lock, ballpark.dogmaLM)
     self.Initialize(ballpark, escrow, lock, persister, eventLogger,
                     notifier)
     self.escrow.SetBonus(bountyEscrowBonus)
Exemple #14
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()
    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()
Exemple #17
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)
Exemple #18
0
def main():
	cs = CSAdapter()
	db = MongoDBAdapter()
	notifier = Notifier()

	# Check for availability every 15 minutes.
	# TODO: Perhaps make it a bit more intelligent and adjust the sleep time.
	while True:
		check_availability(cs, db, notifier)
		time.sleep(15 * 60)
Exemple #19
0
    async def send_book(cls, msg: Message, book_id: int, file_type: str):
        async with Notifier(cls.bot, msg.chat.id, "upload_document"):
            book = await BookAPI.get_by_id(book_id)

            if book is None:
                await msg.reply("Книга не найдена!")
                return
            
            pb = await PostedBookDB.get(book_id, file_type)
            if pb:
                try:
                    await cls.bot.send_document(msg.chat.id, pb.file_id, reply_to_message_id=msg.message_id,
                                                 caption=book.caption, reply_markup=book.share_markup)
                except exceptions.BadRequest:
                    await cls.bot.send_document(msg.chat.id, pb.file_id,
                                                 caption=book.caption, reply_markup=book.share_markup)
            else:
                book_on_channel = await get_book_from_channel(book_id, file_type)

                if book_on_channel is not None:
                    try:
                        send_response = await cls.bot.forward_message(msg.chat.id, book_on_channel["channel_id"], 
                                                                      book_on_channel["message_id"])
                        await DownloadAPI.update(book_id, msg.chat.id)
                        return
                    except exceptions.MessageToForwardNotFound:
                        pass

                book_bytes = await BookAPI.download(book_id, file_type)
                if not book_bytes:
                    await cls.try_reply_or_send_message(msg.chat.id, 
                                                               "Ошибка! Попробуйте позже :(",
                                                               reply_to_message_id=msg.message_id)
                    await DownloadAPI.update(book_id, msg.chat.id)
                    return
                if book_bytes.size > 50_000_000:
                    await cls.try_reply_or_send_message(
                        msg.chat.id, 
                        book.download_caption(file_type), parse_mode="HTML",
                        reply_to_message_id=msg.message_id
                    )
                    await DownloadAPI.update(book_id, msg.chat.id)
                    return
                book_bytes.name = await normalize(book, file_type)
                try:
                    send_response = await cls.bot.send_document(msg.chat.id, book_bytes,
                                                                reply_to_message_id=msg.message_id,
                                                                caption=book.caption, reply_markup=book.share_markup)
                except exceptions.BadRequest:
                    book_bytes = book_bytes.get_copy()
                    send_response = await cls.bot.send_document(msg.chat.id, book_bytes,
                                                                caption=book.caption, reply_markup=book.share_markup)
                await PostedBookDB.create_or_update(book_id, file_type, send_response.document.file_id)
                await DownloadAPI.update(book_id, msg.chat.id)
Exemple #20
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()
Exemple #21
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()
Exemple #22
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()
Exemple #23
0
def notifyNew(bot: Bot, update: Update):
    chat_id = update.message.chat_id
    chat = db.getchat(chat_id)

    notifier: Notifier = Notifier(bot, chat)
    any: bool = notifier.notify()

    if not any:
        bot.send_message(chat_id=chat_id, text="No updates")
        return

    db.update(chat)
    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)
    def __init__(self):
        # Setup Notifier connection
        notifier = Notifier()
        addr, name = notifier.discover(2)
        notifier.connect(addr)
        notifier.set_mode(Command.Mode.Steady)

        # Setup GUI
        app = QApplication(sys.argv)
        window = MainWindow(notifier)
        window.show()
        app.exec_()
    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)
Exemple #27
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])
Exemple #28
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)
Exemple #29
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()
Exemple #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