Example #1
0
def term_notifier(new_event):
    new_event = new_event
    filename = os.path.split(new_event)[1]
    
    # Notifier.notify('Hello World', title = 'New file received')
    Notifier.notify('New file from', title = filename, open="open, -R, "+str(new_event))
    print 'Did something'
Example #2
0
def main():

    def sigterm_handler(_signo, _stack_frame):
        try:
            Notifier.notify('Unregistering fs watch', title='LittleHelp', subtitle=project_path)
        except:
            pass
        logging.info("Sigterm handler called")
        observer.unschedule(stream)
        observer.stop()
        observer.join()
        try:
            Notifier.notify('Unregistered fs watch', title='LittleHelp', subtitle=project_path)
        except:
            pass
        sys.exit(0)

    try:
        Notifier.notify('Registering watch', title='LittleHelp', subtitle=project_path)
        observer = Observer()
        stream = Stream(file_event_callback, project_path, file_events=True)
        observer.schedule(stream)
        observer.start()

        signal.signal(signal.SIGTERM, sigterm_handler)

        while True:
            sleep(0.1)
    except:
        logging.exception("Unhandled exception")
Example #3
0
def alert(user, repo, file, range, pr_link):
    msg = 'Found a PR effecting {file} {range}'.format(file=file,
                                                       range=str(range))
    subprocess.call('say ' + msg, shell=True)
    Notifier.notify(msg, title='Github Watcher', open=pr_link)
    sys.stdout.write('\a')
    sys.stdout.flush()
Example #4
0
    def on_any_event(self, event: FileSystemEvent):
        """
        Events are queued.
        """
        log.debug(event)

        secs_since_last_run = abs(
            (self.last_run - datetime.now()).total_seconds())
        if secs_since_last_run < MAKE_MIN_PERIOD:
            log.info(
                f'Waiting at least {MAKE_MIN_PERIOD} seconds to start next run...'
            )
            try:
                time.sleep(MAKE_MIN_PERIOD)
            except KeyboardInterrupt:
                sys.exit(0)

        self.last_run = datetime.now()
        try:
            subprocess.check_call(['make'])
            Notifier.notify('😎😎😎😎😎😎',
                            title='Build succeeded')
        except subprocess.CalledProcessError:
            Notifier.notify('😡😡😡😡😡😡', title='Build failed')
            sys.exit(1)
Example #5
0
def notify(text):
    Notifier.notify('VACCINE NOTIFIER',
                    title=text,
                    execute='say "Opening Cowin App"',
                    open='https://selfregistration.cowin.gov.in/')
    os.system("afplay /System/Library/Sounds/Glass.aiff")
    os.system("say 'Coawin vaccines found'")
Example #6
0
    def mac_notify(self, title, message, config):
        config = self.prepare_config(config)
        try:
            from pync import Notifier
        except ImportError as e:
            logger.debug('Error importing pync: {}', e)
            raise DependencyError(plugin_name, 'pync',
                                  'pync module required. ImportError: %s' % e)

        icon_path = None
        try:
            import flexget.ui

            icon_path = os.path.join(flexget.ui.__path__[0], 'src',
                                     'favicon.ico')
        except Exception as e:
            logger.debug(
                'Error trying to get flexget icon from webui folder: {}', e)

        try:
            Notifier.notify(
                message,
                subtitle=title,
                title='FlexGet Notification',
                appIcon=icon_path,
                timeout=config['timeout'],
                open=config.get('url'),
            )
        except Exception as e:
            raise PluginWarning('Cannot send a notification: %s' % e)
Example #7
0
def search(num_colors, graph):
    # Do a depth-first search over the configuration space, keeping a
    # stack of assignments and variable domains.

    init_cfg = Assignment(num_colors, graph)
    stack = [(init_cfg, init_cfg.choose())]

    while stack and not stack[-1][0].complete():
        
        cur_var, cur_vals = stack[-1][1]

        if not cur_vals:
            stack.pop()
        else:
            # If we still have options with our current stack frame
            new_val = cur_vals.pop(0)
            new_cfg = stack[-1][0].set(cur_var, new_val)

            if new_cfg.propagate():
                stack.append((new_cfg, new_cfg.choose()))

    if stack and stack[-1][0].complete():
        Notifier.notify("Found a solution!",title="GraphColorizer")
        return [v[0] for v in stack[-1][0].table] 
    else:
        print "Failed @num_colors=%d" % num_colors
        Notifier.notify("Failed @num_colors=%d. :(" % num_colors, title="GraphColorizer")
        return search(num_colors+1, graph)
Example #8
0
    def heartbeat(self):
        while True:
            tag, ci = self.fetch_status()
            if self.app == None:
                time.sleep(1)
                continue
            if ci == None:
                self.logger.warning(f'tag {tag} has no pipeline associated')
                time.sleep(60)
                continue

            if self.ci_status == 'running' and ci.status == 'success':
                tag_url = f'https://gitlab.com/consensusaps/connect/-/tags/{tag}'
                # rumps.notification('Build Completed', f'Completed build for {tag}', f'Docker build for {tag} has not completed', sound=True)
                Notifier.notify(f'Docker build for {tag} has not completed',
                                title=f'Completed build for {tag}',
                                open=tag_url)
            self.ci_status = ci.status

            if self.ci_status == 'success':
                self.app.title = f't: {tag}'
            elif self.ci_status == 'running':
                self.logger.info(
                    f'building {tag} -- {ci.completed_jobs} / {ci.job_count} -- {ci.pending_jobs} pending'
                )
                self.app.title = f'👷🏼‍♀️ {tag} ({ci.completed_jobs} / {ci.job_count})[{ci.pending_jobs}]'
            elif self.ci_status == 'pending':
                self.app.title = f'🍿 {tag}'
            else:
                self.app.title = f'☔️ {tag}'
                self.logger.info(f'ci status for {tag}: {ci}')
            time.sleep(20)
Example #9
0
def makeTweet(author, url):
    code = requests.get(url)
    text = code.text
    soup = BeautifulSoup(text)

    title = soup.findAll(attrs={'name' : 'twitter:title'})[1].get('content')

    twitterHandle = ''
    twitterUser = ''
    twitterUrl = ''

    if soup.findAll(attrs={'name' : 'twitter:creator'}):
        twitterHandle = soup.findAll(attrs={'name' : 'twitter:creator'})[0].get('content')

        twitterUser = twitterHandle

        if 'http://twitter.com/' in twitterHandle:
            twitterUser = twitterHandle.replace("http://twitter.com/", "")
        elif 'https://twitter.com/' in twitterHandle:
            twitterUser = twitterHandle.replace("https://twitter.com/", "")
        elif 'http://www.twitter.com/' in twitterHandle:
            twitterUser = twitterHandle.replace("http://www.twitter.com/", "")
        elif 'https://www.twitter.com/' in twitterHandle:
            twitterUser = twitterHandle.replace("https://www.twitter.com/", "")

        twitterUser = twitterUser.replace("@", "")

        twitterUrl = ' - (http://twitter.com/' + twitterUser + ')'

    tweet = prepareTweet(title, author, twitterUser, url)

    print(time.strftime("%m/%d/%Y %I:%M %p") + '\n' + title + ' by ' + author + twitterUrl + '\nLD Entry Page: ' + url)
    Notifier.notify(title + ' by ' + author + twitterHandle, contentImage='img.jpg', appIcon='pp.png', title='@LDJAMBot', open='http://twitter.com/ldjambot')
    
    return tweet
def notify(data, buffer, date, tags, displayed, highlight, prefix, message):
	if weechat.config_get_plugin('show_highlights') == 'on' and highlight == '1':
		channel = weechat.buffer_get_string(buffer, 'localvar_channel')
		Notifier.notify(message, title='%s %s' % (prefix, channel))
	elif weechat.config_get_plugin('show_private_message') == 'on' and 'notify_private' in tags:
		Notifier.notify(message, title='%s [private]' % prefix)
	return weechat.WEECHAT_RC_OK
Example #11
0
def main():
    last_currency = None

    while True:
        try:
            html = requests.get(ENDPOINT).text
            tree = fromstring(html)
            el = tree.xpath(XPATH)[0]
            value = int(''.join(re.findall(r'\d', el.text)))
        except Exception as e:
            print(e)
            time.sleep(TIMEOUT)
            continue

        if last_currency != value:
            last_currency = value

            try:
                Notifier.notify(TITLE,
                                open=ENDPOINT,
                                title=unicode(value) + u' uah')
            except Exception as e:
                print(e)
                pass

        time.sleep(TIMEOUT)
Example #12
0
 def get_live_score(self):
     """ show live notification score """
     while True:
         if self.score():
             score = self.score()
             Notifier.notify(score, title=self.match_title)
             time.sleep(self.delay)            
    def finalize(self, result):
        failures = len(result.failures)
        errors = len(result.errors)
        folder = result.config.workingDir.strip('/').split('/')[-1]

        if result.wasSuccessful():
            title = "Tests passed in: %s" % folder
            msg = '%s All of your %s test(s) passed!' % (
                self.success_msg,
                result.testsRun,
            )
        else:
            msg = '%s %s failures, %s errors from %s tests' % (
                self.failure_msg,
                failures,
                errors,
                result.testsRun,
            )
            title = "Tests failed in: %s" % folder

        Notifier.notify(
            msg,
            title=title,
            group='%s_%s_tests' % (folder, self.name),
        )
Example #14
0
def alert(file: str,
          range: Tuple[int, int],
          pr_link: str,
          silent=False) -> None:
    """
    Alerts that a file has been changed over range `range`. Also provides a link as supported by the target system.

    :param str file: The name of the file that has been changed.
    :param tuple range: The range over which the change coincides with the watcher configuration.
    :param str pr_link: A link to the pull request containing the change.
    :param bool silent: Whether or not to silence audio alerts.
    :return: None
    """
    msg = 'Found a PR effecting {file} {range}'.format(file=file,
                                                       range=str(range))
    logging.info(msg)
    if SYSTEM == 'Darwin':
        if not silent:
            subprocess.call('say ' + msg, shell=True)
        Notifier.notify(msg, title='Github Watcher', open=pr_link)
    elif SYSTEM == 'Linux' and os.environ.get('TRAVIS') != 'true':
        notify2.init(app_name='github-watcher')
        note = notify2.Notification('Github Watcher', message=msg)
        note.show()
        time.sleep(5)
        note.close()
Example #15
0
def notify(showfeed):
    try:
        for feed in showfeed:
            content = feed['content']
            retext = re.sub(ur'<.*?>', '', content, 0)
            keyword = re.compile(ur'常客说|李凯|young|水洋|协议|转让', re.M)
            if re.search(keyword, retext) == None:
                notice = ''
            else:
                notice = '    ' + '⚠️' + '注意'
            if feed['userinfo']['ext_info']['special_description'] == '':
                description = ''
            else:
                description = '    ' + '🏁' + \
                    feed['userinfo']['ext_info']['special_description']
            title = feed['userinfo']['nickname'] + notice + description
            try:
                contentImage = feed['images'][0]
            except:
                contentImage = ''
            appicon = feed['userinfo']['ext_info']['avatar']
            feedurl = 'https://cms.changker.com/index.php?r=weibo/view&id=' + str(feed['id'])
            Notifier.notify(retext, title=title, sound='default',
                            appIcon=appicon, open=feedurl, contentImage=contentImage)
            time.sleep(6)
    except:
        Notifier.notify(
            '请重新启动新内容推送', title='注意!线上数据获取不成功!', sound='default', appIcon=appicon)
Example #16
0
def main():
    
    
    if (Time < StartTime or EndTime < Time):
        return
    
    opacity = 1.0 if Time == StartTime else Opacity
    frame = Time.GetFrame(24) if IsRendering else -1
    
    osc.initOSCClient(port=1234)
    osc.sendOSCMsg("/update", [frame, Speed / 100, opacity, Threshold, Offset, Suffix])
    
    if IsRendering:
        if Time == StartTime:
            "Start Rendering~~~~~~~~~"
            
        print "Rendering %d" % frame
        
        if EndTime == Time:
            doc.SearchObject("====OSC===")[c4d.ID_USERDATA,8] = False
            print "END!!"
            Notifier.notify("END!!!")
    
    if osc.server == 0:
        print "init osc server"
        osc.initOSCServer(port=4321)
        osc.startOSCServer()
    
    osc.setOSCHandler(address="/save-frame", hd=onSaved)
    
Example #17
0
    def mac_notify(self, title, message, config):
        config = self.prepare_config(config)
        try:
            from pync import Notifier
        except ImportError as e:
            log.debug('Error importing pync: %s', e)
            raise DependencyError(plugin_name, 'pync', 'pync module required. ImportError: %s' % e)

        icon_path = None
        try:
            import flexget.ui

            icon_path = os.path.join(flexget.ui.__path__[0], 'src', 'favicon.ico')
        except Exception as e:
            log.debug('Error trying to get flexget icon from webui folder: %s', e)

        try:
            Notifier.notify(
                message,
                subtitle=title,
                title='FlexGet Notification',
                appIcon=icon_path,
                timeout=config['timeout'],
                open=config.get('url'),
            )
        except Exception as e:
            raise PluginWarning('Cannot send a notification: %s' % e)
def notify(message):
    Notifier.notify(
        title="Irssi Notification",
        message=message,
        group=os.getpid(),
        activate='com.googlecode.iterm2'
    )
Example #19
0
def main():
    parser = optparse.OptionParser()
    using_help = '''
    the service that you want to use. For example: gist for Github's Gist,
    pastebin for PasteBin.com
    '''
    parser.add_option('-u', '--using', dest='using',
                      help=using_help)

    (options, args) = parser.parse_args()

    using = options.using
    if not using:
        using = 'pastebin'

    obj = SharePastesFactory.create(using)
    try:
        url = obj.api_call(xerox.paste())
        xerox.copy(url)
    except xerox.base.XclipNotFound:
        print 'xclip not found. Install xclip for SharePastes to work.'
        sys.exit(1)

    try:
        from pync import Notifier
        Notifier.notify('URL added to your clipboard %s.' % url,
                        title='SharePastes')
    except:
        pass
Example #20
0
 def mac_notifier(*kwargs):
     Notifier.notify(
         kwargs.get('message', ''),
         open=kwargs.get('link', ''),
         title=kwargs.get('title', '')
     )
     return
Example #21
0
	def compare_values(self,flag):
		current=datetime.datetime.now()
		count=0
		for row in c.execute('SELECT * FROM battery'):
			count=count+1
		if count==0:
			Notifier.notify("No values to compare")
			return
		direct_output = subprocess.check_output('pmset -g batt', shell=True)
		(b,d)=direct_output.split('%')
		(d,percentage)=b.split('InternalBattery-0\t')
		if flag==1:
			c.execute("INSERT INTO battery VALUES(?,? ,?)",(count+1,str(current),percentage))
			conn.commit()
		raw=c.execute("SELECT date,status FROM  battery WHERE  sl=?",(str(count)))
		for i in raw:
			print ''
		that_time=str(i[0])
		that_time=datetime.datetime.strptime(that_time, "%Y-%m-%d %H:%M:%S.%f")
		that_percentage=i[1]
		direct_output = subprocess.check_output('pmset -g batt', shell=True)
		(b,d)=direct_output.split('%')
		(d,percentage)=b.split('InternalBattery-0\t')
		difference_in_percentage=int(percentage)-int(that_percentage)
		difference_in_time=current-that_time
		difference_in_time=str(difference_in_time)
		Notifier.notify("Difference in battery percentage = {}\nDifference in time = {}".format(difference_in_percentage, difference_in_time))
Example #22
0
def notification(num,soup):
	tag = soup(id=num)[0]
	price = tag.parent.parent(class_="gr")[0].text
	rate = tag.parent.parent(class_="bg")[0].text
	brand = tag.parent.parent.a.text.encode('utf-8')
	value = '%s\t%s' % (price, rate)
	Notifier.notify(value.encode('utf-8'),title=brand,group=num, remove=num, sound='Glass')
Example #23
0
def show_procastination_warning():
    today_procastinated_min = get_today_procastion_time()
    Notifier.notify(
        'Procastinated %s min\n(%.2d%% from today max)' %
        (today_procastinated_min, float(today_procastinated_min) /
         settings.MAX_PROCASTINATION_TIME_DAY_MIN * 100),
        title='Procastimeter',
    )
Example #24
0
def notify(title, message):
	if hexchat.get_prefs('away_omit_alerts') and hexchat.get_info('away'):
		return

	if hexchat.get_prefs('gui_focus_omitalerts') and hexchat.get_info('win_status') == 'active':
		return
	
	Notifier.notify(hexchat.strip(message), title=hexchat.strip(title), sender='org.hexchat', sound='default')
    def __init__(self, text, screen_name, status_id, title='TweetBot'):
        url = self.base_url % {'screen_name': screen_name, 'id': status_id}

        Notifier.notify(
            text.encode('utf-8'),
            title=title.encode('utf-8'),
            open=url,
        )
Example #26
0
def job():
    url = "http://www.espncricinfo.com/west-indies-v-india-2016/engine/match/1022597.html"  #link here , default invalid for now
    raw = requests.get(url)
    plain_text = raw.text
    obji = BeautifulSoup(plain_text)
    for data in obji.findAll('span', {'class': "innings-1-score innings-current"}): #search tags
        href = data.string
        Notifier.notify(href, title="Match Score")
Example #27
0
def notify(title, content, force=False):
    '''
    Handle notifications depending on whether pync is installed
    '''
    if not has_pync or force:
        sys.stdout.write(str(content) + "\n")
    else:
        Notifier.notify(content, title=title)
Example #28
0
def main():
    # Config Facebook ID and Tokens (using for testing - in process of implementing browser OAuth for long life tokens)
    fbConfig = {"page_id": page_id, "access_token": access_token}

    # Mac
    # AppleScript to get currently playing artist and song from Spotify (no auth req)
    scpt = applescript.AppleScript('''
        on run
            set appName to \"Spotify\"
            set isRunning to false
            tell application \"System Events\"
                if exists process appName then
                    set isRunning to true
                end if
            end tell
            
            if isRunning is true then
                tell application \"Spotify\"
                    set artistName to artist of current track as string
                    set songName to name of current track as string 
                    set currentSong to artistName & \" - \" & songName
                end tell
            end if
        return currentSong
        end run
    ''')

    nowPlaying = scpt.run()

    # Search for video of currently playing song
    # Telling urllib what the query text will be
    query = urllib.parse.quote(nowPlaying)

    # Get video URL for nowPlaying
    url = "https://www.youtube.com/results?search_query=" + query
    response = urllib.request.urlopen(url)
    html = response.read()
    soup = BeautifulSoup(html, "html.parser")
    video = soup.find(attrs={'class': 'yt-uix-tile-link'})
    videoURL = 'https://www.youtube.com' + video['href']

    Notifier.notify(title='LazySearch',
                    message='Successfully Shared: ' + nowPlaying,
                    open='https://www.facebook.com/?sk=h_chr')

    # Post video for currently playing song
    graph = facebook.GraphAPI(fbConfig['access_token'])

    attachment = {
        'name': nowPlaying,
        'link': videoURL,
        'caption': '',
        'description': '',
        'picture': ''
    }

    # Post to wall
    graph.put_wall_post(message='', attachment=attachment)
Example #29
0
def show_procastination_warning():
    today_procastinated_min = get_today_procastion_time()
    Notifier.notify(
        'Procastinated %s min\n(%.2d%% from today max)' % (
            today_procastinated_min,
            float(today_procastinated_min) / settings.MAX_PROCASTINATION_TIME_DAY_MIN * 100
        ),
        title='Procastimeter',
    )
Example #30
0
 def sync_start(self, local_path, remote_path, remote_host):
     Notifier.notify(
         "Starting to sync %s and %s on %s" % (
             local_path,
             remote_path,
             remote_host,
         ),
         title='GitSync'
     )
Example #31
0
 def sync_done(self, local_path, remote_path, remote_host):
     Notifier.notify(
         "Completed sync of %s and %s on %s" % (
             local_path,
             remote_path,
             remote_host,
         ),
         title='GitSync'
     )
def main():
    if len(sys.argv) < 2:
        fire_usage_error()

    service_type = sys.argv[1]
    cwd = "/Users/anas/projects/main_private_repo/task_automation/"

    user_agents = load_user_agent(uafile=cwd + "user_agents")
    header = {
        "ACCEPT":
        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "ACCEPT_ENCODING": "gzip, deflate, sdch, br",
        "CACHE_CONTROL": "max-age=0",
        "Connection": "close",
        "User-Agent": user_agents[0].decode("utf-8"),
        "ACCEPT_LANGUAGE":
        "en-US,en;q=0.8,de-DE;q=0.6,de;q=0.4,ar;q=0.2,fr;q=0.2"
    }

    http = urllib3.PoolManager(10, headers=header)
    base_url = "https://bostad.stockholm.se"
    browse_url = '/lista'
    res = http.request("GET", (base_url + browse_url),
                       timeout=urllib3.Timeout(connect=1.0, read=2.0))

    now = datetime.datetime.now()
    now_str = now.strftime("%d, %b %Y - %X ")
    print(now_str, end=" :: ")
    print("Downloading the page {0}".format(base_url + browse_url) + ' - ' +
          service_type)
    print("..............")

    type_attr = "data-lagenhetstyp-" + service_type.lower()
    print(bs4.BeautifulSoup(res.data, "html.parser"))
    apartments_list = bs4.BeautifulSoup(res.data, "html.parser").find_all(
        'div', {
            type_attr: "True",
            "class": 'kort'
        })

    if len(apartments_list) > 0:
        apartments_details = get_apartments_details(apartments_list, base_url)

        Notifier.notify("Bostad " + service_type + " " +
                        str(len(apartments_list)),
                        title="Bostad")

        today = datetime.date.today()
        today_date_str = today.strftime("%d, %b %Y")
        with open(cwd + "credentials.json") as cred:
            credentials = json.load(cred)
        email_title = service_type + " - Bostad Report - " + today_date_str

        send_mail("Anas <*****@*****.**>",
                  "Bostad Report <*****@*****.**>",
                  email_title, str(apartments_details), credentials)
    exit(0)
def on_message(mosq, userdata, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))

    cf = userdata['cf']
    application = cf.get('notifier', 'application')

    s = str(msg.topic) + "\n" + str(msg.payload)

    Notifier.notify(s, title=application)
def on_message(mosq, userdata, msg):
    print(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))

    cf = userdata['cf']
    application = cf.get('notifier', 'application')

    s = str(msg.topic) + "\n" + str(msg.payload)

    Notifier.notify(s,  title=application)
Example #35
0
def send_to_db(args):
    '''
    Create your MySQL table with this command:

    CREATE TABLE `Email` (
    `email_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `email` VARCHAR(58) NOT NULL,
    `is_opted_out` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
    `has_bounced` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
    PRIMARY KEY (`email_id`),
    UNIQUE (`email`)
    ) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;

    '''
    host = args.host
    user = args.user
    if args.port:
        port = args.port
    else:
        port = 3306
    passwd = args.password
    database = args.database
    file_to_send = args.file

    # Establish connection to local MySQL database
    db = pymysql.connect(host=host,
                         port=port,
                         user=user,
                         passwd=passwd,
                         db=database)

    cursor = db.cursor()

    s = str(file(file_to_send).read())
    w = s.split('\n')

    success = 0
    failed = 0

    for e in w:
        try:
            cursor.execute("INSERT INTO email(email) VALUES(%s)", (e))
            db.commit()
            success += 1
            print e + " was successfully added to database."
        except:
            db.rollback()
            failed += 1
            print e + " has failed to be added to database."

    db.close()
    return send_to_db
    Notifier.notify('Your import is complete.',
                    title='Python email list importer')
    print 'There were %s emails successfully added to the database.' % success
    print 'There were %s emails that failed to be added to the database.' % failed
Example #36
0
 def notify(self, *args, **kw):
     """docstring for notify"""
     message_l = None
     title_l = None
     keys = kw.keys()
     if "message" in keys:
         message_l = kw["message"]
     if "title" in keys:
         title_l = kw["title"]
     Notifier.notify(message_l, title=title_l)
Example #37
0
def main():
    while True:
        if START + DURATION < time.time():
            exit()
        quote = QUOTES[random.randint(0, len(QUOTES) - 1)]
        Notifier.notify(quote,
                        sound='default',
                        title="Drink Water 😃",
                        appIcon='rain.png')
        time.sleep(FREQUENCY)
Example #38
0
def notify(title, message, is_pass=True):
    if is_pass:
        icon = "pass"
    else:
        icon = "fail"
    icon = os.path.join(os.path.dirname(__file__), icon + ".png")
    if Notifier is not None:
        Notifier.notify(message, title=title)
    else:
        call(["terminal-notifier", "-title", title, '-message', message, '-appIcon', icon])
Example #39
0
 def sync(self):
     while True:
         #Check back in 30 mins
         time.sleep(1800)
         for sub in self.sub_reddit:
             new_post = self.get_new_post(sub)
             print("new post id {}".format(new_post.id))
             if new_post.id != self.post_ids[sub]:
                 self.post_ids[sub] = new_post.id
                 Notifier.notify(new_post.title, title='New post on /r/'+sub, open='http://www.reddit.com/r/'+sub+'/new/')
Example #40
0
 def line_added_cb(self, line):
     if line['highlight'] == b'\x01':
         channel = self.buffers.get(line['buffer'], '#unknown').rsplit('.', 1)[-1]
         Notifier.notify(
             strip_formatting(line['message']),
             title=strip_formatting(f'{line["prefix"]} in {channel}'),
             activate='com.googlecode.iterm2',
             appIcon='./weechat.png',
             contentIcon='./weechat.png',
         )
Example #41
0
def notification(num, soup):
    tag = soup(id=num)[0]
    price = tag.parent.parent(class_="gr")[0].text
    rate = tag.parent.parent(class_="bg")[0].text
    brand = tag.parent.parent.a.text.encode('utf-8')
    value = '%s\t%s' % (price, rate)
    Notifier.notify(value.encode('utf-8'),
                    title=brand,
                    group=num,
                    remove=num,
                    sound='Glass')
Example #42
0
def displayRec(dic, sound=None, formatRec=formatRec):
    message, title, sub = formatRec(dic)
    if sound != None:
        Notifier.notify(message,
                        group=title,
                        title=title,
                        subtitle=sub,
                        sound=sound)
        time.sleep(2)
    else:
        Notifier.notify(message, group=title, title=title, subtitle=sub)
def check_and_notify():
    while True:
        time.sleep(30)
        if len(events) == 0:
            continue

        if time.time() < events[0].time:
            continue

        next_event = events.pop(0)
        Notifier.notify(next_event.message, title='Marley')
Example #44
0
 def notify_mountainlion(n):
     notify_normal(n)
     return
     group_id = '%d-%s' % (os.getpid(),n.id)
     text = n.text
     if len(_notify_tree):
         temp_tree = [x.text for x in _notify_tree] + [text]
         text = '\n'.join(['%s%s' % ('  '*i,temp_tree[i]) for i in xrange(len(temp_tree))])
         group_id = '%d-%s' % (os.getpid(),_notify_tree[0].id)
         Notifier.remove(group_id)
     Notifier.notify(text,title='Jarvis',group=group_id)
Example #45
0
def notify_user(newJobsList, numOfNewJobs):
    if numOfNewJobs < 1 or len(newJobsList) is 0:
        return
    for job in newJobsList:
        careerTitle = job[1]
        jobLocation = job[2]
        Notifier.notify(careerTitle,
                        title='New Job!',
                        subtitle=jobLocation,
                        open='https://careers.eskaton.org/',
                        sound='Hero')
Example #46
0
def notify(title, message):
    if hexchat.get_prefs('away_omit_alerts') and hexchat.get_info('away'):
        return

    if hexchat.get_prefs('gui_focus_omitalerts') and hexchat.get_info(
            'win_status') == 'active':
        return

    Notifier.notify(hexchat.strip(message),
                    title=hexchat.strip(title),
                    sender='org.hexchat',
                    sound='default')
Example #47
0
def poll_chargepoint_stations(scraper, stations_of_interest=None, stations_to_ignore=None):
    if stations_to_ignore is None:
        stations_to_ignore = []
    if stations_of_interest is None:
        stations_of_interest = scraper.get_station_data()['stations'].keys()
    stations_of_interest = [x for x in stations_of_interest if x not in stations_to_ignore]
    old_free_spots = None
    old_open_stations = []
    t = Terminal()
    try:
        i = 0
        while True:
            new_free_spots = 0
            new_open_stations = []
            try:
                data = scraper.get_station_data()
            except ChargePointAuthenticationExpiredException:
                data = scraper.get_station_data()
            if i % 10 == 0:
                print '\t\t\t' + '\t'.join([station for station in stations_of_interest])
            line_parts = [data['time'].strftime('%Y/%m/%d %H:%M:%S')]
            for k in stations_of_interest:
                line_part = '%d / %d'.center(9) % (data['stations'][k]['available'], data['stations'][k]['total'])
                if data['stations'][k]['available'] == data['stations'][k]['total']:
                    line_part = t.black_on_green(line_part)
                elif data['stations'][k]['available'] == 0:
                    line_part = t.black_on_red(line_part)
                else:
                    line_part = t.black_on_yellow(line_part)
                line_parts.append(line_part)
                new_free_spots += data['stations'][k]['available']
                new_open_stations.extend([k] * data['stations'][k]['available'])
            print '\t'.join(line_parts)
            if old_free_spots is not None and new_free_spots > old_free_spots:
                newly_open_stations = new_open_stations
                for elem in old_open_stations:
                    try:
                        newly_open_stations.remove(elem)
                    except ValueError:
                        pass
                title = '%s station(s) are open' % ', '.join(newly_open_stations)
                message = '%d Free Spots' % new_free_spots
                if _platform == 'darwin':
                    Notifier.notify(title=title, message=message)
                send_boxcar_notification(title=title, message=message)
            old_free_spots = new_free_spots
            old_open_stations = new_open_stations
            i += 1
            sleep(60)
    except KeyboardInterrupt:
        pass
    except KeyError:
        exit("Unexpected response json.")
Example #48
0
def plugin(srv, item):

    srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target)

    text = item.message
    application_name = item.get("title", item.topic)

    try:
        Notifier.notify(text, title=application_name)
    except Exception, e:
        srv.logging.warning("Cannot invoke Notifier to osx: %s" % (str(e)))
        return False
Example #49
0
 def on_data(self, raw_data):
     try:
         y = json.loads(raw_data)
         print("Text:", y['text'])
         print("In Reply to:", y['in_reply_to_screen_name'])
         Notifier.notify(y['text'], title='Python')
         #with open() as tf:
         #tf.write(raw_data)
         return True
     except BaseException as e:
         print("Error on data %s" % str(e))
     return True
Example #50
0
def send_to_db(args):
    '''
    Create your MySQL table with this command:

    CREATE TABLE `Email` (
    `email_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `email` VARCHAR(58) NOT NULL,
    `is_opted_out` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
    `has_bounced` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
    PRIMARY KEY (`email_id`),
    UNIQUE (`email`)
    ) ENGINE=InnoDB CHARSET=utf8 COLLATE utf8_unicode_ci;

    '''
    host = args.host
    user = args.user
    if args.port:
        port = args.port
    else:
        port = 3306
    passwd = args.password
    database = args.database
    file_to_send = args.file

    # Establish connection to local MySQL database
    db = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=database)

    cursor = db.cursor()

    s = str(file(file_to_send).read())
    w = s.split('\n')

    success = 0
    failed = 0

    for e in w:
        try:
            cursor.execute("INSERT INTO email(email) VALUES(%s)", (e))
            db.commit()
            success += 1
            print e + " was successfully added to database."
        except:
            db.rollback()
            failed += 1
            print e + " has failed to be added to database."


    db.close()
    return send_to_db
    Notifier.notify('Your import is complete.', title='Python email list importer')
    print 'There were %s emails successfully added to the database.' % success
    print 'There were %s emails that failed to be added to the database.' % failed
Example #51
0
def notify(title, message, is_pass=True):
    if is_pass:
        icon = "pass"
    else:
        icon = "fail"
    icon = os.path.join(os.path.dirname(__file__), icon + ".png")
    if Notifier is not None:
        Notifier.notify(message, title=title)
    else:
        call([
            "terminal-notifier", "-title", title, '-message', message,
            '-appIcon', icon
        ])
Example #52
0
def send_macos_notification(unread_count, message_senders, title, arg_dict):
    notification_group_id = "notifier"

    Notifier.notify(
        message="BaseMessage" + ("s" if (len(message_senders) > 1 and unread_count > 1) else "") + " from: " +
                ", ".join(message_senders),  # content of notification
        title=title + ": " + str(unread_count) + " unread message" + (
            "s" if unread_count > 1 else ""),  # notification title
        group=notification_group_id,  # ID used to group notification with previous notifications
        **arg_dict
    )

    Notifier.remove(notification_group_id)
Example #53
0
def tell_notifier(message, title, **kwargs):
    # passing `None` or `''` still plays the default sound so we pass a lambda instead
    sound = weechat.config_get_plugin(
        'sound_name') if weechat.config_get_plugin(
            'sound') == 'on' else lambda: _
    weechat_icon = weechat.config_get_plugin('weechat_icon')
    activate_bundle_id = weechat.config_get_plugin('activate_bundle_id')
    Notifier.notify(message,
                    title=title,
                    sound=sound,
                    appIcon=weechat_icon,
                    activate=activate_bundle_id,
                    group='weechat')
    def after_remote_ip_update(self, ip, status):
        """
        Handle the after_remote_ip_update plugin hook.

        :param ip: ip address
        :param status: string
        """
        default_title = "Dynamic DNS"
        if status == 0:
            message = "Remote IP updated to %s" % ip
        else:
            message = "Problem updating remote IP to %s" % ip
        Notifier.notify(message, title=default_title, group=os.getpid())
Example #55
0
def ISSnotifier():
    url = 'http://api.open-notify.org/iss-now.json' # define url 
    r = urllib2.urlopen(url) # open the specified url
    data = json.loads(r.read()) # read the json into python 

    issLatitude = (data['iss_position']['latitude']) # extract the latitude 
    issLongitude = (data['iss_position']['longitude']) # extract the longitude

    print "ISS's latitude, longitude: ", (issLatitude, issLongitude) # current position of the ISS

    if g < issLatitude < c and f < issLongitude < b: # if the ISS is inside the notification area 
        print ('The ISS is inside the notification area')
        Notifier.notify('Look up mate, you might see the ISS pass by', title='ISS')
        sys.exit() # stop script once user has been notified
Example #56
0
 def sigterm_handler(_signo, _stack_frame):
     try:
         Notifier.notify('Unregistering fs watch', title='LittleHelp', subtitle=project_path)
     except:
         pass
     logging.info("Sigterm handler called")
     observer.unschedule(stream)
     observer.stop()
     observer.join()
     try:
         Notifier.notify('Unregistered fs watch', title='LittleHelp', subtitle=project_path)
     except:
         pass
     sys.exit(0)
def notify(data, buffer, date, tags, displayed, highlight, prefix, message):

        # ignore if it's yourself
        own_nick = w.buffer_get_string(buffer, 'localvar_nick')
        if prefix == own_nick or prefix == ('@%s' % own_nick):
            return w.WEECHAT_RC_OK

        # Skip alerting if you're already looking at it and you're not /away
        if (buffer == w.current_buffer()
           and w.buffer_get_string(buffer, 'localvar_away') == ''):
            return w.WEECHAT_RC_OK

        if w.config_get_plugin('show_highlights') == 'on' and int(highlight):
                channel = w.buffer_get_string(buffer, 'localvar_channel')
                if w.config_get_plugin('show_message_text') == 'on':
                        N.notify(message, title='%s %s' % (prefix, channel))
                else:
                        N.notify('In %s by %s' % (channel, prefix),
                                 title='Highlighted Message')
        elif (w.config_get_plugin('show_private_message') == 'on'
              and 'notify_private' in tags):
                if w.config_get_plugin('show_message_text') == 'on':
                        N.notify(message, title='%s [private]' % prefix)
                else:
                        N.notify('From %s' % prefix, title='Private Message')
        return w.WEECHAT_RC_OK
def notify(data, buffer, date, tags, displayed, highlight, prefix, message):
	# ignore if it's yourself
	own_nick = weechat.buffer_get_string(buffer, 'localvar_nick')
	if prefix == own_nick or prefix == ('@%s' % own_nick):
		return weechat.WEECHAT_RC_OK

	# ignore messages older than the configured theshold (such as ZNC logs) if enabled
	if weechat.config_get_plugin('ignore_old_messages') == 'on':
		message_time = datetime.datetime.utcfromtimestamp(int(date))
		now_time = datetime.datetime.utcnow()

		# ignore if the message is greater than 5 seconds old
		if (now_time - message_time).seconds > 5:
			return weechat.WEECHAT_RC_OK

	# passing `None` or `''` still plays the default sound so we pass a lambda instead
	sound = weechat.config_get_plugin('sound_name') if weechat.config_get_plugin('sound') == 'on' else lambda:_
	activate_bundle_id = weechat.config_get_plugin('activate_bundle_id')
	if weechat.config_get_plugin('show_highlights') == 'on' and int(highlight):
		channel = weechat.buffer_get_string(buffer, 'localvar_channel')
		if weechat.config_get_plugin('show_message_text') == 'on':
			Notifier.notify(message, title='%s %s' % (prefix, channel), sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
		else:
			Notifier.notify('In %s by %s' % (channel, prefix), title='Highlighted Message', sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
	elif weechat.config_get_plugin('show_private_message') == 'on' and 'notify_private' in tags:
		if weechat.config_get_plugin('show_message_text') == 'on':
			Notifier.notify(message, title='%s [private]' % prefix, sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
		else:
			Notifier.notify('From %s' % prefix, title='Private Message', sound=sound, appIcon=WEECHAT_ICON, activate=activate_bundle_id)
	return weechat.WEECHAT_RC_OK