Exemple #1
0
def main():
    getDefaults()
    pb = Pushbullet(PBKEY)

    websites = open(websitelist, 'rb+')
    status = pickle.load(websites)

    for site in status:
        headers = {
            'User-Agent':
            'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
        }
        response = requests.get(site, headers=headers)

        comp = SequenceMatcher(None, status[site][0], response.text)
        print(site, comp.ratio())
        if comp.ratio() < status[site][1]:
            pb.push_note("Shiba Alert",
                         site + " has updated!" + str(comp.ratio()))
            status[site] = [response.text, comp.ratio()]
        #status[site] = [response.text, comp.ratio()]

    websites.seek(0)
    pickle.dump(status, websites)
    websites.close()
def checkupsstatus():
	print '\ncheckupsstatus()'
	
	global ups_status
	global battery_charge
	global battery_runtime	
	global output_voltage
	try :
		#initialize pushbullet 
		global ACCESS_TOKEN
		# if 230V is present
		if ups_status == "OL CHRG":
			logmessage = " OK, ups is powered"
			
		# if power outtage is detected
		elif ups_status == "OB DISCHRG" :
			logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n panne de courant !\n Batterie a "+ str(battery_charge) +"%, "+ str(battery_runtime) +" minutes restantes."
			# send message through pushbullet to user
			pb = Pushbullet(ACCESS_TOKEN)	
			push = pb.push_note("Domini - onduleur", logmessage)
		else :
			# status unknow
			logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n etat inconnu : " + str(ups_status)+ ".\n Batterie a "+ str(battery_charge) +"%, "+ str(battery_runtime) +" minutes restantes."
			# send message through pushbullet to user
			pb = Pushbullet(ACCESS_TOKEN)
			push = pb.push_note("Domini - onduleur", logmessage)
		# print message and log it
		print logmessage
		syslog.syslog(logmessage)
		
	except :
		logmessage = " Error while reading or parsing UPS Variables"
		print logmessage
		syslog.syslog(logmessage)
Exemple #3
0
def pushGoodMorning():
    #PushBullet API
    pb = Pushbullet(api_key)

    #getting time
    now = datetime.now().time()
    #AM or PM
    mornAfternoon = datetime.now().strftime('%p')

    #Here we push the notifcation(s)
    if now.hour == 6 and now.minute == 30:
        #Getting the weather
        weather_results = pywapi.get_weather_from_weather_com(weatherCode)
        weather_saying = ("The weather is " +
                          weather_results['current_conditions']['text'])
        #pushing
        push = pb.push_note(
            name + ", it's currently " + str(now.hour - 12) + ":" +
            str(now.minute) + mornAfternoon + ".", weather_saying)
    else:
        #Put something else here
        print "Oh darn, the time is off for the weather, we'll try again soon"

    if now.hour == 22 and now.minute == 17:
        #getting reddit post title
        user_agent = "Bot that grabs top title in /r/ news"
        r = praw.Reddit(user_agent=user_agent)
        submission = r.get_subreddit('news').get_hot(limit=1)
        for x in submission:
            topTitle = str(x.title)
        #Pushing
        push = pb.push_note(name + ", the latest news is:", topTitle)
    else:
        print "Uh oh! The time didnt match up for your reddit post, we'll try again later"
def notify(job, title, body):
    # Send notificaions
    # title = title for notification
    # body = body of the notification

    if job.config.PB_KEY != "":
        try:
            from pushbullet import Pushbullet
            pb = Pushbullet(job.config.PB_KEY)
            pb.push_note(title, body)
        except:  # noqa: E722
            logging.error(
                "Failed sending PushBullet notification.  Continueing processing..."
            )

    if job.config.IFTTT_KEY != "":
        try:
            import pyfttt as pyfttt
            event = job.config.IFTTT_EVENT
            pyfttt.send_event(job.config.IFTTT_KEY, event, title, body)
        except:  # noqa: E722
            logging.error(
                "Failed sending IFTTT notification.  Continueing processing..."
            )

    if job.config.PO_USER_KEY != "":
        try:
            from pushover import init, Client
            init(job.config.PO_APP_KEY)
            Client(job.config.PO_USER_KEY).send_message(body, title=title)
        except:  # noqa: E722
            logging.error(
                "Failed sending PushOver notification.  Continueing processing..."
            )
Exemple #5
0
class PushBullet:
    def __init__(self):
        self.pb = Pushbullet(os.environ.get('PUSHBULLET_MEC_API'))
        self.contacts = self.pb.chats
        return

    def push(self, title, body):
        return self.pb.push_note(title, body)

    def get_contacts(self):
        a = self.contacts[0].name
        b = self.contacts[0].email
        print(a, b)
        return self.contacts

    def send_msg_to_contact(self, email, title, body):
        contact = self.get_contact(email)
        return self.pb.push_note(title, body, chat=contact)

    def get_contact(self, email):
        for contact in self.contacts:
            if contact.email == email:
                return contact
        # print(self.contacts)
        contact = self.pb.new_chat("NEW", email)
        # self.pb.push_note('Registered to COWIN Cron Service', 'You will receive notifs if vaccine slots if any are found.', chat=contact)
        return contact
Exemple #6
0
    def run(self, msg: str = None, access_token: str = None) -> None:
        """
        Run method for this Task. Invoked by calling this Task after initialization within a
        Flow context, or by using `Task.bind`.

        Args:
            - msg (str): The message you want sent to your phone; defaults to the one provided
                at initialization
            - access_token (str): a Pushbullet access token, provided with a Prefect secret.
                Defaults to the "PUSHBULLET_TOKEN" secret
        """
        try:
            from pushbullet import Pushbullet
        except ImportError as exc:
            raise ImportError(
                "Using pushbullet tasks requires Prefect to be installed with the 'pushbullet' extra."
            ) from exc

        if access_token is None:
            access_token = Secret("PUSHBULLET_TOKEN").get()

        pb = Pushbullet(access_token)

        if msg is None:
            raise ValueError("A message must be provided")

        # send the request
        pb.push_note("Flow Notification", msg)
Exemple #7
0
    def run(self, msg: str = None, access_token: str = None) -> None:
        """
        Run method for this Task. Invoked by calling this Task after initialization within a Flow context,
        or by using `Task.bind`.

        Args:
            - msg (str): The message you want sent to your phone; defaults to the one provided
                at initialization
            - access_token (str): a Pushbullet access token, provided with a Prefect secret. Defaults to the "PUSHBULLET_TOKEN" secret

        Raises:
            - None

        Returns:
            - None
        """
        if access_token is None:
            access_token = Secret("PUSHBULLET_TOKEN").get()

        pb = Pushbullet(access_token)

        if msg is None:
            raise ValueError("A message must be provided")

        ## send the request
        pb.push_note("Flow Notification", msg)
def on_complete(user, filename):
    if not user:
        return

    if six.PY2:
        curr_user = filter(lambda person: person['username'] == user,
                           conf["users"])[0]
    else:
        curr_user = next(
            filter(lambda person: person['username'] == user, conf["users"]))

    if curr_user["notify_via_pushbullet"]:
        try:
            from pushbullet import Pushbullet
            pb = Pushbullet(curr_user["pushbullet_token"])
            pb.push_note("Download finished", filename)
            return True
        except ImportError:
            print(
                "Cant notify via PushBullet. Missing librabry. Install via pip install pushbullet.py",
                file=sys.stderr)
            return False
        except Exception:
            print("Invalid Api key for PushBullet. Please insert correct one.",
                  file=sys.stderr)
            return False
Exemple #9
0
def push(text: str, details: str, r: praw) -> None:
    """
    Push a message to computer
    :param text: MNT or WNT
    :param details: Match details
    :param r: PRAW instance
    :return: None
    """
    try:
        from pushbullet import Pushbullet
        with open('token.txt') as files:
            token = files.read().strip()
        pb = Pushbullet(token)
        try:
            lst = text.split('?')
            pb.push_note('{} match today at {} on {}'.format(details, lst[4], lst[3]),
                         '', device=pb.get_device('iPhone'))
        except IndexError:
            pb.push_note('{}{}'.format(text, details),
                         '', device=pb.get_device('iPhone'))

    except ImportError:
        lst = text.split('?')
        r.send_message('RedRavens', '{} Match Today'.format(details),
                       '{} match today at {} on {}'.format(details, lst[4], lst[3]))
Exemple #10
0
def main():
    apikey = settings.key
    users = settings.users

    if apikey == '':
        print('No pushbullet apikey found in pushy.conf file, or bad formatting')
        input('Press enter to exit\n>>')
        return

    if len(users) < 1:
        print('No users found in settings.py. Please specifiy at least one (main) user.')
        input('Press enter to exit \n>>')
        return

    pb = Pushbullet(apikey)
    startup = pb.push_note("Pushy Listener Initiated", "auto start on reboot")
    handler = PushHandler(pb, users)

    s = Listener(account=pb,
        on_push = handler.receive,
        http_proxy_host = Http_Proxy_Host,
        http_proxy_port = Http_Proxy_Port)
    try:
        s.run_forever()
    except (Exception, KeyboardInterrupt) as exc:
        close = pb.push_note('Pushy Listener Closed', '{}'.format(exc))
    else:
        s.close()
Exemple #11
0
def push(msg):
    print(msg)
    actuallyPush = True
    if actuallyPush:
        apiKey = getKey('pushbullet.key')
        pb = Pushbullet(apiKey)
        pb.push_note("Alpaca: Wood Gold", msg)
Exemple #12
0
def pushbullet_notify(message):
    if "pushbullet_token" not in CONFIG["notifications"]:
        print("Tried to send pushbullet message [%s] but no `notifications.pushbullet_token` was found" % message)
        return
    pb = Pushbullet(CONFIG["notifications"]["pushbullet_token"])
    now = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
    pb.push_note("Twitter Watch", "%s\n\n%s" % (now, message))
    print(message, flush=True)  # also prints to stdout
Exemple #13
0
def push_bullet(message, title='Fishing', forced=False):
    ini = Config.getboolean('notification', 'pushbullet', fallback=True)
    if not forced and not ini:
        return

    api_key = Config['pushbullet']['key']
    pb = Pushbullet(api_key)
    pb.push_note(title, message)
 def _send_message(self, message, **kwargs):
     try:
         pb = Pushbullet(autosubliminal.PUSHBULLETAPI)
         pb.push_note(title=self.notification_title, body=message)
         return True
     except Exception:
         log.exception('%s notification failed', self.name)
         return False
Exemple #15
0
 def _send_message(self, message, **kwargs):
     try:
         pb = Pushbullet(autosubliminal.PUSHBULLETAPI)
         pb.push_note(title=self.notification_title, body=message)
         return True
     except Exception:
         log.exception('%s notification failed', self.name)
         return False
Exemple #16
0
def sendPushNotification(msg):
    try:
        key = getKey()
        pb = Pushbullet(key)
        dt = datetime.datetime.now()
        s = dt.strftime('%Y-%m-%d %H:%M:%S')
        pb.push_note('Code Messenger', f'{s}\n{msg}')
    except FileNotFoundError:
        logger.error(f'Could not send push notification: "{msg}"')
 def send_pushbullet(self):
     pb = Pushbullet(self.pushbullet_token)
     if self.file_path is not None:
         with open(self.file_path, "rb") as f:
             file_data = pb.upload_file(f, f.name.replace("-", ""))
             response = pb.push_file(**file_data)
     else:
         pb.push_note("Motion detected!", "Motion detected, could not find preview image")
     print "PiSN: Pushbullet notification succesfully pushed"
Exemple #18
0
def send_pb_msg(title, msg):
    ACCESS_TOKEN = 'o.aLZj2KPbkK3HIgYkiK0QaXoXioAc6FxN'
    ACCESS_TOKEN2 = 'o.3aJg1PdLnf5z0m9KDcCCbCytVislbCzG'

    pb = Pushbullet(ACCESS_TOKEN)
    push = pb.push_note(title, msg)

    pb2 = Pushbullet(ACCESS_TOKEN2)
    push2 = pb2.push_note(title, msg)
 def cancel(self, alert, options):
     api_key = self.context.client.call_sync('alert.emitter.pushbullet.get_api_key')
     pb = Pushbullet(api_key)
     pb.push_note(
         'Alert on {0} canceled: {1}'.format(
             socket.gethostname(),
             alert['title']
         ),
         alert['description']
     )
Exemple #20
0
class PushbulletController:

    def __init__(self):
        self.__pb = Pushbullet('o.ZsHeeLnFuB0xUUWs6lqpshRWCYniVD6B')

    def notifyEngineer(self, title, note):
        self.__pb.push_note(title, note)

    def main(self):
        self.notifyEngineer()
class PushbulletClient:
    def __init__(self):
        self.__pb = Pushbullet(API_KEY)
        self.__emails = [
            '*****@*****.**', '*****@*****.**',
            '*****@*****.**'
        ]

    def push(self, body, title):
        for email in self.__emails:
            self.__pb.push_note(body=body, email=email, title=title)
Exemple #22
0
 def notif(self, users, title, body, pushbullet_notif= True):
     for user in users:
         if self.settings()[user]["profile"].get("pushbullet") and pushbullet_notif is True:
             try:
                 pb = Pushbullet(self.settings()[user]["profile"]["pushbullet"]["api_key"])
                 pb.push_note("Hervé | {title}".format(title=title), body)
             except Exception as e:
                 print("[erreur] " + e)
         self.users[user]["notif"].append(
             {"title": title, "body": body}
         )
 def _send_pushbullet(self, payload):
     e2e_password = config.get('Alerts',
                               'pushBulletEncryptionPassword',
                               fallback=None)
     pb = Pushbullet(config.get('Alerts', 'pushBulletKey'),
                     encryption_password=e2e_password)
     if payload.url:
         pb.push_link(title=self.title,
                      body=payload.generate_message(),
                      url=payload.url)
     else:
         pb.push_note(self.title, payload.generate_message())
Exemple #24
0
def push_msg(token, title, message):
    try:
        if token == '':
            return False
        driver_push = Pushbullet(token)

        driver_push.push_note(title, message)
    except:
        print('push Error--')
        return False

    return True
Exemple #25
0
def updatePushBullet(days, htmlResp, updatedContent):
    daysStr = "days since last updates "+str(days)	
    if updateExist:
        soup = BeautifulSoup(html,'lxml')
        pb = Pushbullet(pushBulletId)
        for br in soup.find_all("br"):
            br.replace_with("\n")
        push = pb.push_note("Order "+trackNum , daysStr+'\n'+soup.get_text())
    else:
        if days % 5 == 0:
            pb = Pushbullet(pushBulletId)
            push = pb.push_note("Order "+trackNum , daysStr)
Exemple #26
0
def send_pb(text):
    try:
        pb = Pushbullet(PUSHBULLET['API'])
        s7 = pb.devices[1]
    # Gets the device to sent the alert
    except InvalidKeyError:
        print ('Wrong Pushbullet API Key')
    except IndexError:
        print ('Your PB device doesnt exist')
    else:
        pb.push_note('Caixa.py', str(text), device=s7)
        print ('PushBullet alert sent!')
def main():

    request_links_list = []
    for course in targets:
        print(course)
        temp = 'https://www.bu.edu/phpbin/summer/rpc/openseats.php?sections%5B%5D=' + term + course
        request_links_list.append(temp)

    courses_open = get_open_courses(request_links_list, targets, term)
    print(courses_open)

    #test input in config file for token
    config = None

    with open('config.yml', 'r') as config_file:
        try:
            config = yaml.load(config_file)
        except yaml.YAMLError as err:
            print(err)
            exit(1)

    if config is None:
        print('Error with your config')
        exit(1)
    elif 'pb_token' not in config:
        print('Config must contain your Pushbullet Access Token!')
        exit(1)

    pb = Pushbullet(config['pb_token'])

    while True:
        print("Starting check... ",
              datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

        courses_open = get_open_courses(request_links_list, targets, term)

        if len(courses_open) == 0:
            print("No new courses found!!!")
        else:

            title = "Open Class"
            message = ""
            for item in courses_open:
                message += item + " "

            pb.push_note(title, message)

            print(message)
            break

        time.sleep(300)
Exemple #28
0
def checkWebPage():

    headers = {
        'headers': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'}
    url = "https://www.ufmg.br/copeve/Arquivos/2018/trob_edital_ufmg2019.pdf"
    pb = Pushbullet("pushbullet-key")
    r = requests.get(url, headers=headers, timeout=5)

    time = strftime('%X')
    print(time, r.status_code)
    if r.status_code == 200:
        print("Saiu o edital!")
        # os.system('ntfy -t "SITE UP!!" send "%s"' % url)
        pb.push_note("UFMG", "Saiu EDITAL")
Exemple #29
0
def main(argv):
    geolocator = Nominatim()
    pb = Pushbullet(settings.pushBulletApiKey)
    print(pb.devices)
    # push = pb.push_note("Today's Weather Update", "It's so cold. You should wear a jacket.")

    location = geolocator.geocode(settings.home)
    forecast = forecastio.load_forecast(settings.forecastioKey,location.latitude ,location.longitude )

    # Get the upcoming events for the day with location information
    events = gcal.get_events(hour_offset=settings.hoursAhead, include_calendars=settings.include_calendars)

    precipType = 'None'
    precipIntensity = 0
    today = processDay(forecast)

    # Conditionally set precip type and intensity because they do not exist if
    # there is no chance of precipitation
    if forecast.daily().data[0].precipProbability is not 0:
        precipType = forecast.daily().data[0].precipType
        precipIntensity = forecast.daily().data[0].precipIntensity



    msg = 'You should wear '
    clothingOption = 'summer clothes, it\'s warm today'
    for key in sorted(settings.tempPreference, reverse=True):
        if today['avgTemp'] < key:
            clothingOption = settings.tempPreference[key]
        else:
            break

    msg += clothingOption + '. '

    if today['maxPrecipChance'] > settings.precipThreshold:
        if precipType is not 'snow':
            msg += 'Bring an umbrella, there is a ' + str(today['maxPrecipChance']*100) + '% chance of rain. '
        else:
            msg += 'You should layer up, there is a ' + str(today['maxPrecipChance']*100) + '% chance of snow. '

    if today['avgCloudCover'] < 0.25:
        msg += 'Consider some sunscreen/sunglasses, it\'s going to be sunny today.'



    msg += '\nIt\'s going to be about ' + str(round(today['avgTemp'])) + '˚F today. (Low: ' + str(round(today['minTemp'])) + ', High: ' + str(round(today['maxTemp'])) +')'

    print(msg)
    pb.push_note("Today's Update", msg)
Exemple #30
0
class PushbullectHelper():
    def __init__(self):
        self.pb = Pushbullet(api_key)
        self.iphone = self.pb.devices[0]
        self.device = self.pb.devices

    def sendnote(self, title, str):
        self.pb.push_note(title, str, device=self.iphone)

    def sendall(self, title, str):
        self.pb.push_note(title, str)

    def sendfile(self, file, name):
        filedata = self.pb.upload_file(file, name)
        self.pb.push_file(**filedata)
Exemple #31
0
class PushBulletHandler(logging.Handler):

    def __init__(self, api_key, title='', email=None, level=logging.WARNING):
        super().__init__(level)
        self.client = Pushbullet(api_key)
        self.title = title
        self.email = email

    def emit(self, record):
        try:
            self.client.push_note(
                title=self.title, body=self.format(record), email=self.email
            )
        except Exception:
            self.handleError(record)
Exemple #32
0
def send_pushbullet_notification(curr_user, filename):
    try:
        from pushbullet import Pushbullet
        pb = Pushbullet(curr_user["pushbullet_token"])
        pb.push_note("Download finished", filename)
        return True
    except ImportError:
        print(
            "Cant notify via PushBullet. Missing librabry. Install via pip install pushbullet.py",
            file=sys.stderr)
        return False
    except Exception:
        print("Invalid Api key for PushBullet. Please insert correct one.",
              file=sys.stderr)
        return False
Exemple #33
0
 def write_log(self, logger, warn, temp, humidity, upper, lower,
               pushbullet):
     if (warn and (temp > upper) or (temp < lower)):
         logger.warning('Temp: {:0.1f} Humidity: {:0.1f}%'.format(
             temp, humidity))
         if pushbullet:
             try:
                 pb = Pushbullet(pushbullet)
                 pb.push_note(
                     'Warning', 'Temp: {:0.1f} Humidity: {:0.1f}%'.format(
                         temp, humidity))
             except InvalidKeyError:
                 logger.error('Invalid Pushbullet API key')
     else:
         logger.info('Temp: {:0.1f} Humidity: {:0.1f}%'.format(
             temp, humidity))
Exemple #34
0
def sendPushBullet(title, message):

    pb = Pushbullet(PB_API)
    push = pb.push_note(title, message)
    debug("\nStatus for Push Bullet\n================")
    for key, value in push.items():
        debug("{} : {}".format(key, push[key]))
Exemple #35
0
def check_receiver():
    print('\ncheck_receiver()')
    processname = 'pyreceiver.py'
    tmp = os.popen("ps -Af | grep '.py'").read()
    proccount = tmp.count(processname)

    if proccount > 0:
        logmessage = " OK, pyreceiver is running"
    else:
        global ACCESS_TOKEN
        pb = Pushbullet(ACCESS_TOKEN)
        logmessage = time.strftime(
            "%Y-%m-%d %H:%M:%S") + "\n Domini - Erreur : pyreceiver est arrete"
        push = pb.push_note("Domini", logmessage)

        #running pyreceiver
        print('\nrunning pyreceiver manually')
        args = [
            'python3',
            '/home/jcaulier/src/domini/serveur/pyReceiver/pyreceiver.py'
        ]
        subprocess.Popen(args, shell=False, stdout=subprocess.PIPE)

        #os.system("python3 /home/jcaulier/src/domini/serveur/pyReceiver/pyreceiver.py &")

    print(logmessage)
    syslog.syslog(logmessage)
def check_db():
    print('\ncheck_db()')
    # requete pour tester si la bdd tourne
    try:
        # Open MySQL session
        con = mdb.connect(user="******",
                          password="******",
                          host="localhost",
                          database="domotique")
        # If connection fail, see except process hereafter
        #else
        # Close MySQL session
        con.close()
        # add some log
        logmessage = " OK, Database is running"

    except mdb.Error as e:
        # Display MySQL errors
        try:
            print("MySQL Error [%d]: %s" % (e.args[0], e.args[1]))
            logmessage = time.strftime(
                "%Y-%m-%d %H:%M:%S"
            ) + " DoMini - Error : Database is NOT running"
            global ACCESS_TOKEN
            pb = Pushbullet(ACCESS_TOKEN)
            push = pb.push_note("Domini", logmessage)
        except IndexError:
            print("MySQL Error: %s" % str(e))

    print(logmessage)
    syslog.syslog(logmessage)
Exemple #37
0
def notify():
    """
    push call notification.
    """
    pushb = Pushbullet(os.environ.get('PUSHBULLET_KEY', ''))
    push = pushb.push_note("野水さんから", "橋本さん、早く来て!")
    print push
Exemple #38
0
def main():
    parser = argparse.ArgumentParser(
        description="Supervisor event listener to notify on process events.")
    parser.add_argument("--apikey",
                        help="Specify the pushbullet api key",
                        required=True)
    args = parser.parse_args()

    pb_api_key = Pushbullet(args.apikey)

    while True:
        headers, body = listener.wait(sys.stdin, sys.stdout)
        body = dict([pair.split(":") for pair in body.split(" ")])

        write_stderr("Headers: %r\n" % repr(headers))
        write_stderr("Body: %r\n" % repr(body))

        #Check if the process is in "STOPPED STATE" and send a pushbullet notification
        if headers["eventname"] == "PROCESS_STATE_EXITED":
            write_stderr("Process state stopping...\n")
            process_name = body.get('processname')
            push = pb_api_key.push_note(
                "Supervisord Alert",
                "Process in stopped state: " + process_name)
            push
        #Supervisor acknowledge
        write_stdout("RESULT 2\nOK")
Exemple #39
0
 def on_notification(change):
     pb = Pushbullet(self.access_token)
     for group in change.n_groups:
         for n in group.notifications:
             msg = u"Repo. : {0}\n".format(group.group_name)
             msg += u"Title : {0}\nLink : {1}\nPerson : {2}\nText : {3}".format(n.title, n.link, n.person, n.text)
             push = pb.push_note(u"Github Pushbullet - Notification", msg)
Exemple #40
0
def notify(game, team, seconds, minutes, pushbullet, pushbullet_key, force):
    team = team.lower().strip()
    if pushbullet:
        if not pushbullet_key:
            pushbullet_key = os.environ.get('PUSHBULLET_API', '')
        if not pushbullet_key:
            click.secho('To use pushbullet notification supply --pushbulet-key '
                        'or enviroment variable PUSHBULLET_API', err=True, fg='red')
            return
        try:
            from pushbullet import Pushbullet
        except ImportError:
            click.secho('To use pushbullet notification install pusbullet.py package;'
                        ' pip install pushbullet.py', err=True, fg='red')
            return

    if minutes:
        seconds = minutes * 60
    matches = download_matches(game)
    re_team = re.compile(team, flags=re.I)
    for match in matches:
        if int(match['time_secs']) > int(seconds):
            continue
        if re_team.match(match['t1']) or re_team.match(match['t2']):
            # already in history?
            if not force:
                with open(HISTORY_LOCATION, 'r') as f:
                    if match.id in f.read():
                        continue
            # notify
            title = "{} vs {} in {}".format(match['t1'], match['t2'], match['time'])
            body = match.get('stream') or match['url']
            if pushbullet:
                push = Pushbullet(pushbullet_key)
                push.push_note(title, body)
            else:
                # The if check below is for fixing notify-send to work with cron
                # cron notify-send requires $DBUS_SESSION_BUS_ADDRESS to be set
                # as per http://unix.stackexchange.com/questions/111188
                subprocess.call('if [ -r "$HOME/.dbus/Xdbus" ]; '
                                'then . $HOME/.dbus/Xdbus; '
                                'fi && notify-send "{}" "{}"'.format(title, body),
                                shell=True)
            # add to history
            with open(HISTORY_LOCATION, 'a') as f:
                f.write('{}\n'.format(match.id))
Exemple #41
0
	def post(self):
	    pb = Pushbullet(API_KEY)
 	    push = pb.push_note(title, note)

	    s = Listener(account=pb,
 	                on_push=on_push,
 	                http_proxy_host=HTTP_PROXY_HOST,
 	                http_proxy_port=HTTP_PROXY_PORT)
Exemple #42
0
def send_push():
    try:
        title = "INTRUSION"
        text = "movement detected"
        from pushbullet import Pushbullet
        API_KEY = 'o.nYHrQiyqBr2NTj59HaQFSSGsgoLDYQrv'
        pb = Pushbullet(API_KEY)
        push = pb.push_note(title,text)
    except: pass
Exemple #43
0
def check_webserver():
	print '\ncheck_webserver()'
	try:
		code_ws = urllib.urlopen("http://localhost/index.php").getcode()
		
		if( code_ws != '200') :
			logmessage = " OK, server web is running"
		else :
			global ACCESS_TOKEN
			pb = Pushbullet(ACCESS_TOKEN)
			logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n Domini - Erreur : serveur web est arrete"
			push = pb.push_note("Domini", logmessage)	
	except:
		logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n Domini - Erreur : etat serveur web inconnu"
		push = pb.push_note("Domini", logmessage)
		
	print logmessage
	syslog.syslog(logmessage)	
Exemple #44
0
class PushBulletRoute(Route):
    """SmartHome using pushbullet."""

    def __init__(self, cfg):
        super(PushBulletRoute).__init__(cfg)
        
        self.lastFetch = time.time()
        self.apiKey = self.cfg.get('global', 'api_key')
        self.pb = Pushbullet(self.apiKey)

    def run(self):
        try:
            deviceIden = self.cfg.get('global', 'device_iden')
        except NoOptionError:
            deviceIden = self.pb.new_device('SmartHome').device_iden
            self.cfg.set('global', 'device_iden', deviceIden)
            with open(CONFIG_FILE, 'w') as f:
                self.cfg.write(f)

        def on_push(msg):
            journal.send('Got message: ' + json.dumps(msg))
            try:
                pushes = self.pb.get_pushes(self.lastFetch)
                journal.send('Got pushes: ' + json.dumps(pushes))
                self.lastFetch = time.time()
                if type(pushes) is types.TupleType and len(pushes)>1 \
                        and type(pushes[1]) is types.ListType:
                    for push in pushes[1]:
                        journal.send('Check push: ' + json.dumps(push))
                        if push.has_key('target_device_iden') and push['target_device_iden'] == deviceIden:
                            cmd = json.loads(push['body'])
                            self.home.followCommand(cmd)
                            fromIden = push['source_device_iden']
                            fromDevice = self.getDevice(fromIden)
                            if fromDevice is None:
                                journal.send('get_status: Cannot find device with iden "' + fromIden + '"', PRIORITY=journal.LOG_ERR)
                                return
                            self.pb.push_note('status', self.home.getStatus(), fromDevice)
            except (PushbulletError, IOError, ValueError, KeyError), e:
                journal.send(str(e), PRIORITY=journal.LOG_ERR)

        lsr = Listener(Account(self.apiKey), on_push)
        lsr.run()
Exemple #45
0
def new_transaction():
    r = json.loads(request.data)
    if r['type'] == 'transaction.created':
        amount = '\u00a3{0:.2f}'.format(float(r['data']['amount'])*-1)
        description = r['data']['description']
        message_title = '{} spent'.format(amount, description)
        message_body = '@ {}'.format(amount, description)
        pb = Pushbullet(os.environ.get('pushbullet_key'))
        push = pb.push_note(message_title, message)
        return message
Exemple #46
0
def Error_loop():
	# un peu bourrin : on boucle sur le message d'erreur + envoie d'info tant que le pb n'est pas resolu
	while True :
		logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "Alarme en mode ERROR !"
		print logmessage
		syslog.syslog(logmessage)
		# send message through pushbullet to user
		# initialize pushbullet 
		pb = Pushbullet(ACCESS_TOKEN)
		push = pb.push_note("Domini - Alarme", logmessage)
		time.sleep(600)
class push_bullet:
    """Random Commands"""
    def __init__(self, bot):
        self.bot = bot
        self.pb = Pushbullet(config['push']['id'])

    async def on_message(self, message):
        if not message.channel.is_private and message.server.me.mentioned_in(message) and not message.author.bot and message.author != message.server.me: #Send push update if I am Mentioned
            me_mentioned = datetime.datetime.now().strftime("""%b %d, %Y at %I:%M %p (%H:%M)""")+"\nI have been mentioned in '"+message.channel.name+"' on '"+message.server.name+"' by '"+message.author.name+"#"+message.author.discriminator+"'\nMessage: "+message.content
            print("==============================\n"+me_mentioned)
            push = self.pb.push_note('Discord Mention', me_mentioned+"\nhttps://discordapp.com/channels/"+str(message.server.id)+"/"+str(message.channel.id))
Exemple #48
0
def pushnote(msg):
    homeDir =  os.path.expanduser('~')
    configFile = os.path.join(homeDir, '.pushbullet')
    config = load_config(configFile)
    try:
        api_key = config['pushnote']
    except KeyError:
        msg = '"pushnote" API key not found in config file: {}'
        raise KeyError, msg.format(configFile)
        
    pb = Pushbullet(api_key)
    push = pb.push_note(msg, '')
Exemple #49
0
def main():
    getDefaults()
    pb = Pushbullet(PBKEY)

    websites = open(websitelist, 'rb+')
    status = pickle.load(websites)

    for site in status:
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
        response = requests.get(site, headers=headers)

        comp = SequenceMatcher(None, status[site][0], response.text)
        print(site, comp.ratio())
        if comp.ratio() < status[site][1]:
            pb.push_note("Shiba Alert", site + " has updated!" + str(comp.ratio()))
            status[site] = [response.text, comp.ratio()]
        #status[site] = [response.text, comp.ratio()]
    
    websites.seek(0)
    pickle.dump(status, websites)
    websites.close()
Exemple #50
0
def check_webserver():
	print '\ncheck_webserver()'
	code_ws = urllib.urlopen("http://192.168.0.102/index.php").getcode()
	
	if( code_ws != '200') :
		logmessage = " OK, server web is running"
	else :
		pb = Pushbullet('o.OVDjj6Pg0u8OZMKjBVH6QBqToFbhy1ug') 
		logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n Domini - Erreur : serveur web est arrete"
		push = pb.push_note("Domini", logmessage)	
	
	print logmessage
	syslog.syslog(logmessage)	
Exemple #51
0
def sendnotifpir():
	global timeoutnotification
	
	now = int(time.time())
	
	#check if a notification was send before recently
	if now > timeoutnotification :
		# launch timeoutnotification
		timeoutnotification = int(time.time()) + TIMEOUT_NOTIF
		# initialize pushbullet 
		pb = Pushbullet(ACCESS_TOKEN)
		logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "Detection PIR"
		push = pb.push_note("Domini - Alarme", logmessage)
class PushbulletPipeline(object):

    @classmethod
    def from_crawler(cls, crawler):
        return cls(pb_key=crawler.settings.get('PUSHBULLET_APIKEY'))

    def __init__(self, pb_key):
        super(PushbulletPipeline, self).__init__()
        self.pb = Pushbullet(pb_key)  # pylint: disable=C0103

    def process_item(self, item, spider):
        content = TEMPLATE % item
        spider.log(content)

        try:
            self.pb.push_note('Resumo da fatura Submarino', content)
        except Exception as exc:
            print(exc)
            spider.log(exc, level=log.ERROR)
            raise DropItem()

        return item
    def action(self):
        # fill in the shared kvp in your instance
        pb_api = Pushbullet(shared.pb_api_key)
        notif_dict = self.notif_dict

        if notif_dict['type'] == 'note':
            note = pb_api.push_note(notif_dict['title'], notif_dict['note'])
        elif notif_dict['type'] == 'link':
            link = pb_api.push_link(notif_dict['title'], notif_dict['link'])
        elif notif_dict['type'] == 'list':
            pb_list = pb_api.push_list(notif_dict['title'], notif_dict['list'])
        elif notif_dict['type'] == 'address':
            address = pb_api.push_address(notif_dict['title'], notif_dict['address'])
Exemple #54
0
def send_push():
    from pushbullet import Pushbullet
    API_KEY = 'o.nYHrQiyqBr2NTj59HaQFSSGsgoLDYQrv'
    # API_KEY = 'o.gmWPEjdjJvbZRqnTvCc7sHkonggCW48I'
    pb = Pushbullet(API_KEY)
    print pb.devices
    company_list = ["ARVINFRA","BHEL","COALINDIA","ICICIBANK","LTI","MRF","POWERGRID","RPOWER","SBBJ","SBIN","SPICEJET","STOREONE","TATASTEEL","THYROCARE","VOLTAS"]
    title = "Share"
    text = ""
    for item in company_list:
        t1,t2,t3,t4,t5,t6 = my_funct(item,60,1)
        text = item+' '+str(t1)+' '+str(t2)+' '+str(t3)+' '+str(t4)+' '+str(t6)+"\n"
        push = pb.push_note(title,text)
Exemple #55
0
def check_receiver():
	print '\ncheck_receiver()'
	processname = 'pyreceiver.py'
	tmp = os.popen("ps -Af | grep '.py'").read()
	proccount = tmp.count(processname)

	if proccount > 0:
		logmessage = " OK, pyreceiver is running"
	else :
		pb = Pushbullet('o.OVDjj6Pg0u8OZMKjBVH6QBqToFbhy1ug') 
		logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n Domini - Erreur : pyreceiver est arrete"
		push = pb.push_note("Domini", logmessage)
		
	print logmessage
	syslog.syslog(logmessage)	
Exemple #56
0
def check_receiver():
	print '\ncheck_receiver()'
	processname = 'pyreceiver.py'
	tmp = os.popen("ps -Af | grep '.py'").read()
	proccount = tmp.count(processname)

	if proccount > 0:
		logmessage = " OK, pyreceiver is running"
	else :
		global ACCESS_TOKEN
		pb = Pushbullet(ACCESS_TOKEN)
		logmessage = time.strftime("%Y-%m-%d %H:%M:%S") + "\n Domini - Erreur : pyreceiver est arrete"
		push = pb.push_note("Domini", logmessage)
		
	print logmessage
	syslog.syslog(logmessage)	
Exemple #57
0
def send_links(channel):
	#this sends a list of streaming video links as a note to
	#your pushbullet account
	global response
	links = response["launches"][0]["vidURLs"]

	linkstring = ""
	for link in links:
		linkstring = linkstring + link + "\r\n"

	WriteLCDLine4("Sending links...")
	pb = Pushbullet(PUSHBULLET_API_KEY)
	push = pb.push_note(response["launches"][0]["name"] +" Links", linkstring)
	time.sleep(1)
	WriteLCDLine4("Links sent!     ")
	time.sleep(5)
	WriteLCDLine4("                ")
Exemple #58
0
    def submit(self):

        body_text = '\n'.join(super().submit())

        if not body_text:
            logger.debug('Not sending pushbullet (no changes)')
            return

        if len(body_text) > 1024:
            body_text = body_text[0:1023]
            
        try:
            pb = Pushbullet(self.config['api_key'])
        except:
            logger.error("Failed to load Pushbullet - is it installed ('pip install pushbullet.py')")
            return

        push = pb.push_note("Website Change Detected", body_text)
Exemple #59
0
def send_push():
	from pushbullet import Pushbullet
	API_KEY = 'o.nYHrQiyqBr2NTj59HaQFSSGsgoLDYQrv'
	# API_KEY = 'o.gmWPEjdjJvbZRqnTvCc7sHkonggCW48I'
	pb = Pushbullet(API_KEY)
	url = "http://www.espncricinfo.com/ci/engine/match/index.html"
	data = BeautifulSoup(requests.get(url).text)
	search_list = data.findAll('a',href=True,text='Live scorecard')
	for item in search_list:
		link = "http://www.espncricinfo.com"+item['href']
		data = BeautifulSoup(requests.get(link).text).select('.match-information-strip')[0].findAll(text=True)[0].strip().split("\n")
		tournament = data[0].replace(",","")
		team_1 = BeautifulSoup(requests.get(link).text).select('.team-1-name')[0].findAll(text=True)[0].strip()
		team_2 = BeautifulSoup(requests.get(link).text).select('.team-2-name')[0].findAll(text=True)[0].strip()
		match_status = BeautifulSoup(requests.get(link).text).select('.innings-requirement')[0].findAll(text=True)[0].strip()
		title = "Cricket"
		text = team_1+" vs "+team_2+"\n"+match_status
		push = pb.push_note(title,text)
Exemple #60
0
def pushbullet_listening():
    week = ['mon','tue','wed','thu','fri','sat','sun']
    day_of_week = week[datetime.today().weekday()]
    hour_of_day = datetime.now().hour
    minute_of_day = datetime.now().minute

    title = 'Khaleesi notifications'
    now_time = '{hour}:{minute}:00'.format(hour=hour_of_day, minute=minute_of_day)

    list_notifications = {
        'start_time': {
            'text': 'Buen día. Es hora de comenzar a trabajar. No olvides activar tus tareas.',
            'filter': {'start_time': now_time},
            'type': 'note'
         },
        'lunch_time': {
            'text': 'Hora de comer ! Recuerda pausar tus tareas activas.',
            'filter': {'lunch_time': now_time},
            'type': 'image'
         },
        'end_time': {
            'text': 'Tu día parece haber terminado. Buen trabajo. Recuerda que a las 6pm todas las tareas activas se pausarán automáticamente.',
            'filter': {'end_time': now_time},
            'type': 'link',
            'url': 'http://khaleesi.unisem.mx/admin/track/tarea/'
         }
    }

    for profile in UserProfile.objects.filter(Q(**{day_of_week: True}) & Q(token__isnull=False)):
        try:
            pb = Pushbullet(profile.token)
            #print profile.user
            for notification in list_notifications.keys():
                if UserProfile.objects.filter(id=profile.id).filter(Q(**list_notifications[notification]['filter'])).count() > 0:
                    if list_notifications[notification]['type'] == 'note':
                        push = pb.push_note(title, list_notifications[notification]['text'])
                    elif list_notifications[notification]['type'] == 'link':
                        push = pb.push_link(title, url=list_notifications[notification]['url'], body=list_notifications[notification]['text'])
                    elif list_notifications[notification]['type'] == 'image':
                        push = pb.push_file(file_url=get_url_image(), file_name=title, file_type='image/jpeg', body=list_notifications[notification]['text'])
                    print push
        except Exception as e:
            #print 'Error: ', e
            pass