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()
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)
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)
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)
def main(): im = Image.open("taehui.jpg") g_im = im.convert('L') g_im.save('taehui_gray.jpg', 'JPEG') pb = Pushbullet('o.cJzinoZ3SdlW7JxYeDm7tbIrueQAW5aK') with open('taehui_gray.jpg', 'rb') as pic: file_data = pb.upload_file(pic, 'taehui_gray.jpg') print(**file_data)
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
def push_item(items): pb = Pushbullet(API_KEY) for item in items: if item["price"] == -1: price_info = "No price: " else: price_info = str(item["price"]) + ":- | " push = pb.push_link(price_info + item["title"], item["url"])
def on_file_received(self, file): print "File received " + file #super(MyHandler, self).on_file_sent(self, file) pb = Pushbullet(api_key) with open(file, "rb") as pic: file_data = pb.upload_file(pic, file) push = pb.push_file(**file_data)
def push_chart(self): """ Pushes the chart to a Pushbullet account. """ pb = Pushbullet(config.PB_API_KEY) with open('./today.jpg', 'rb') as pic: file_data = pb.upload_file(pic, 'today.jpg') pb.push_file(**file_data)
def loop(): reduser = reddit_object.redditor("{redditor username}") for post in reduser.submissions.new(limit=1): if "ama" in post.title.lower() and post.id != last_ama_id: push_bullet = Pushbullet(pushbullet_access_token) my_phone = push_bullet.get_device("{device identifier}") my_phone.push_note("AMA Posted","User {redditor username} is doing an AMA!") exit() threading.Timer(10.0,loop).start()
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"
def on_change(title, link): title = HTMLParser().unescape(title) api_key = read_file('api_key') if api_key: pb = Pushbullet(api_key.strip()) pb.push_link(title, link) else: print('No api_key file available. Push not sent')
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
def push(msg): api_key="kO3wYXQB6WQlQp7A5AN7WcPqdMOWy1Xx" pb = Pushbullet(api_key) # ip = subprocess.check_output("/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'", shell=True) devlist=[x.nickname.encode('UTF-8') for x in pb.devices] if 'Rpi' not in devlist: pb.new_device('Rpi') for dev in pb.devices: push = dev.push_note('Rpi is up! ',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'] )
def send_pushbullet_message(metro_time): from pushbullet import Pushbullet pb = Pushbullet(conn['pushbullet_api_key']) # If device name is provided, push to this device only to = pb.get_device(conn['pushbullet_device']) if conn['pushbullet_device'] else pb to.push_note("Time to go home!", "You have {0} minutes for the metro.".format(metro_time)) print("Message pushed")
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
def push_file(filename): if is_device_connected(DEVICE_MAC): print "Device is connected, not sending" return print "Sending", filename pushbullet = Pushbullet(PUSHBULLET_API_KEY) my_device = pushbullet.get_device(PUSHBULLET_DEVICE_NAME) file_data = pushbullet.upload_file(open(filename, "rb"), filename) pushbullet.push_file(device = my_device, **file_data) print "Sent!"
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)
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, '')
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'])
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)
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)
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)
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)
def rgc_runner_run(forum_url, search_strings, pb_key): fr = ForumRunner(url=forum_url) results = fr.run() search_results = fr.search(search_strings) for res in search_results: if res.is_new: print "%s (%s) new?%s" % (res.title, res.price, res.is_new) #if the pushbullet key is set, send a link to pushbullet containing the information and URL that we found if pb_key: pb = Pushbullet(pb_key) found_text = 'RCGBot -- Match Found: %s %s' % (res.title, res.price) push = pb.push_link(found_text, res.url)
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)
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)
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)
def main(): with open("token.secret") as f: token = f.read().strip() print(token) pb = Pushbullet(token) # print(pb.push_note("this is title", "hoehoe")) for d in pb.devices: print(d.nickname) print(d.device_iden) myiphone = pb.get_device("yuk-iPhoneSE-g") print(myiphone) print(myiphone.push_note("title", "body")) return
class Room: def __init__(self, entrance_cnt=0, exit_cnt=0): self.pb = Pushbullet(config.PUSH_KEY) self.entrance_cnt = entrance_cnt self.exit_cnt = exit_cnt self.objects_inside = 0 self.overpopulation_notification_send = False self.underpopulation_notification_send = False def proceed_population_notifications(self): self.objects_inside = self.get_objects_inside_cnt() if self.objects_inside > config.LIMIT and not self.overpopulation_notification_send: print("Room overpopulated") self.send_overpopulation_push() self.overpopulation_notification_send = True self.underpopulation_notification_send = False elif self.objects_inside <= config.LIMIT and not self.underpopulation_notification_send: print("Room is not overpopulated") self.send_underpopulation_push() self.overpopulation_notification_send = False self.underpopulation_notification_send = True def get_objects_inside_cnt(self): return self.entrance_cnt - self.exit_cnt def send_overpopulation_push(self): title = "Ostrzeżenie" message = "Limit miejsc: " + str(config.LIMIT) + " wyczerpany." self.send_push(title, message) def send_underpopulation_push(self): title = "Powiadomienie" message = "Ilość osób w pomieszczeniu mieści się w limicie: " + str( config.LIMIT) self.send_push(title, message) def send_push(self, title: str, message: str): self.pb.push_note(title, message)
def api_link(self, title, url, channel=None): """ send a link through pushbullet @Ytitle@w = the title of the note @Yurl@w = the body of the note @Ychannel@w = the pushbullet channel to send to this function returns True if sent, False otherwise""" apikey = self.api('%s.apikey' % self.sname)() if not apikey: return False pbc = PUSHBULLET(apikey) rval = {} nchannel = channel or self.api.get('setting.gets')('channel') if nchannel: for i in pbc.channels: if str(i.channel_tag) == nchannel: found = True rval = i.push_link(title, url) break if not found: self.api('send.error')('There was no channel %s' % nchannel) return False else: rval = pbc.push_link(title, url) pbc._session.close() if 'error' in rval: self.api('send.error')('Pushbullet send failed with %s' % rval) return False else: self.api('send.msg')('pb returned %s' % rval) return True
def config(): try: global pb API_Key = weechat.config_get_plugin('api_key') if API_Key == '': raise Exception() pb = Pushbullet(API_Key) print_hook = weechat.hook_print('', '', '', 1, 'handle_msg', '') except: weechat.config_set_plugin('api_key', '') prnt( 'Please `/set plugins.var.python.weebullet.api_key <API_KEY>` to use this plugin.' )
def __init__(self, token, device='Platypush', proxy_host=None, proxy_port=None, **kwargs): """ :param token: Your Pushbullet API token, see https://docs.pushbullet.com/#authentication :type token: str :param device: Name of the virtual device for Platypush (default: Platypush) :type device: str :param proxy_host: HTTP proxy host (default: None) :type proxy_host: str :param proxy_port: HTTP proxy port (default: None) :type proxy_port: int """ # noinspection PyPackageRequirements from pushbullet import Pushbullet super().__init__(**kwargs) self.token = token self.device_name = device self.proxy_host = proxy_host self.proxy_port = proxy_port self.pb = Pushbullet(token) self.listener = None # noinspection PyBroadException try: self.device = self.pb.get_device(self.device_name) except: self.device = self.pb.new_device(self.device_name) self.pb_device_id = self.get_device_id()
def __init__(self, token=None, **kwargs): super(ServicePushbullet, self).__init__(token, **kwargs) self.AUTH_URL = 'https://pushbullet.com/authorize' self.ACC_TOKEN = 'https://pushbullet.com/access_token' self.REQ_TOKEN = 'https://api.pushbullet.com/oauth2/token' self.consumer_key = settings.TH_PUSHBULLET['client_id'] self.consumer_secret = settings.TH_PUSHBULLET['client_secret'] self.scope = 'everything' self.service = 'ServicePushbullet' self.oauth = 'oauth2' if token: self.token = token self.pushb = Pushb(token)
def main(): try: api_key = request.headers[HEADER_PB_APIKEY] except KeyError: return "No Pushbullet Apikey provided (expected in header: '{}')".format( HEADER_PB_APIKEY), 400 payload = json.loads(request.get_data(as_text=True)) current_app.logger.info(payload) note_title = payload["title"] note_body = payload["body"] current_app.logger.info( "Sending pushbullet notification: '{} -- {}'".format( note_title, note_body)) try: pb = Pushbullet(api_key) except InvalidKeyError: return "Provided Pushbullet Apikey is invalid", 400 push = pb.push_note(note_title, note_body) return Response(json.dumps(push), mimetype='application/json')
def main(): setup_logging() # The first (and only) argument should be the location ID as found here: # http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/xml/sitelist # ?res=daily&key=<MET OFFICE API KEY> if len(sys.argv) != 2: logging.error('Please enter a Met Office location ID as the first' 'argument') return location_name, forecasts = get_met_office_3hourly_forecast(sys.argv[1]) try: body = '' for i, forecast in enumerate(forecasts): # Only send a forecast for periods 4 (9am-12pm) and 5 (12pm-3pm) if forecast['period'] == 4 or forecast['period'] == 5: logging.info('Calculating new forecast for {}'.format( forecast['from'].strftime('%a %d/%m/%Y %H:%M'))) if body != '': body += '\n' # Day of week (MON, TUE, WED etc) body += string_to_fullwidth( forecast['from'].strftime('%a').upper()) # am or pm body += get_am_pm(forecast['from'].time()) # Nice day emoticon body += calc_nice_day_emoticon(i, forecasts) # weather icon body += get_weather_icon(forecast['weather_type']) # temprature in C body += get_temperature(forecast['temperature_c']) # wind speed in mph body += get_wind_speed(forecast['wind_speed_mph']) # Send this message to pushbullet pb = Pushbullet(PUSHBULLET_API_KEY) pb.push_note('Weather for {}'.format(location_name), body) logging.info('Forecast sent to pushbullet') except: logging.exception('Error occurred:')
def pbpush(self): """ Send a PushBullet notification either privately or to a channel, depending on whether or not PB_CHANNEL is set in config. """ from pushbullet import Pushbullet pb = Pushbullet(config.PB_API_KEY) minutes, seconds = divmod(self.delta.total_seconds(), 60) time_remaining = str(int(minutes)) + 'm' + str(round(seconds)) + 's.' if config.AREA_NAME: if self.longspawn: title = ('A wild ' + self.name + ' will be in ' + config.AREA_NAME + ' until at least ' + self.expire_time + '!') else: title = ('A wild ' + self.name + ' will be in ' + config.AREA_NAME + ' until ' + self.expire_time + '!') elif self.longspawn: title = ('A wild ' + self.name + ' will expire within 45 minutes of ' + self.expire_time + '!') else: title = ('A wild ' + self.name + ' will expire at ' + self.expire_time + '!') if self.longspawn: body = 'It will be ' + self.place + ' for 15-60 minutes.' else: body = 'It will be ' + self.place + ' for ' + time_remaining try: channel = pb.channels[config.PB_CHANNEL] channel.push_link(title, self.map_link, body) except (IndexError, KeyError): pb.push_link(title, self.map_link, body) return True
class PushNotification: def __init__(self): with open("/home/payam/Workspace/piNotification/settings.yaml", 'r') as stream: try: self.settings = yaml.safe_load(stream) self.pushbullet = Pushbullet(self.settings['access_token']) self.device = self.pushbullet.get_device( self.settings['device_name']) except yaml.YAMLError as exc: print(exc) def notify(self, notificationType, message): self.device.push_note(notificationType, message)
def check_webserver(): print('\ncheck_webserver()') try: code_ws = urllib.request.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)
class PushBulletNotificationService(NotificationService): """ Use pypi library pushbullet.py to send push into phone. Need to register and get an api_key """ def _setup(self): # api_key gives access to account, so not to be shared! self.pb = Pushbullet(self.params['api_key']) def _notify(self, events): push = self.pb.push_note(self.short_messages(events), self.long_messages(events)) #print("le retour du push {}".format(push)) if not push: raise Exception('Error with PushBulletNotificationService')
def sendRecord(inputStreamLines): data = inputStreamLines.map( lambda x: json.loads(x.encode('utf-8'))).collect() for row in data: result = 0 if int(row['amount']) > float( dict_userid_meanPlus2sd.get(row['userid'])) or int( row['amount']) < float( dict_userid_meanMinus2sd.get(row['userid'])): result = 1 if result == 1: message = "FRAUD DETECTED!!!! Your account ID" + str( row['userid']) + " has " + str(row['action']) + " " + str( row['amount']) + " baht (It is above " + str( float(dict_userid_meanPlus2sd.get( row['userid']))) + " )" s.send(message) g.sendmail("EMAIL", "EMAIL", message) pb = Pushbullet( "APIKEY" ) # API ->> notifiy to chrome and mobile phone # old key= APIKEY push = pb.push_note("Fraud Detected", message) result = 0
def push(): # load config file config = None with open('./config.json') as f: config = json.load(f) # pushbullet pb = Pushbullet(config['access_token']) target = None for dev in pb.devices: if dev.nickname == config['device_name']: target = dev if target == None: print 'target device not found.' else: # push as file if config['send_file']: if os.path.exists(config['send_file']): file_data = None try: with open(config['send_file'], 'rb') as f: file_data = pb.upload_file( f, os.path.basename(config['send_file'])) except: pass target.push_file(**file_data) print 'pushed as file : {0}'.format(config['send_file']) return # push as text target.push_note(config['send_title'], config['send_body']) print 'pushed as text : {0} / {1}'.format(config['send_title'], config['send_body'])
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 check_leave_dates(): """Compare annual leave dates in an Outlook calendar and in the list submitted to Oracle.""" oracle_off_dates = get_oracle_off_dates() outlook_off_dates = outlook.get_away_dates(min(oracle_off_dates), 0, look_for=outlook.is_annual_leave) not_in_outlook = oracle_off_dates - outlook_off_dates toast = '' if not_in_outlook: toast = f'Missing from Outlook: {list_missing(not_in_outlook)}\n' not_in_oracle = outlook_off_dates - oracle_off_dates if not_in_oracle: toast += f'Missing from Oracle: {list_missing(not_in_oracle)}' if toast: print(toast) Pushbullet(api_key).push_note('📅 Check leave dates', toast)
def _get_pb_obj(): # Lazy load global PBOBJ if PBOBJ is None: try: pushbullet_token = CONFIG.get('NOTIFY', 'PUSHBULLET_TOKEN') if not pushbullet_token: raise InvalidKeyError PBOBJ = Pushbullet(pushbullet_token) except (NoOptionError, NoSectionError, InvalidKeyError) as e: log('NO Pushbullet config ({} [{}])' .format(e, e.__class__), 'error', False) PBOBJ = None return PBOBJ
class PushBulletAPI: # def main(self): # self.pushNotification(10, "Toyota") def __init__(self): self.pb = Pushbullet('o.BfDh4Z35MEnCyxal5J0dcIuMamGyU38a') def pushNotification(self, carID, car_make): push = self.pb.push_note( "Car require repair\n", "Car ID: " + str(carID) + " ,Car Make: " + car_make) # PushBulletAPI().main()
class TestPushBullet(unittest.TestCase): # connecting to push bullet api _pb = Pushbullet("<API-KEY>") # push = pb.push_note("Title","body") # check the available devices print(_pb.devices) # set your device _huawei = _pb.get_device('<DEVICE-NAME>') def test_pushbullet(self): print('sending push notification with image...') with open("cameratest.jpg", "rb") as pic: img = self._pb.upload_file(pic, "Test Notification") self._huawei.push_file(**img) print('Notification successfully pushed to the device via PushBullet')
def run(self): pb = Pushbullet(self.access_token) while True: result = self.do_crawling(self.url) result2 = self.do_crawling(self.url[:-1] + '2') # slicing if result2 == self.error_mes: pb.push_note(u"Internship notices", self.error_mes) else: result += result2 if result == "": pb.push_note(u"Internship notices", "no recent notices") else: pb.push_note(u"Internship notices", result) time.sleep(48600)
def push_file(filename): if is_device_connected(DEVICE_MAC): print "Device is connected, not sending" return print "Sending", filename pushbullet = Pushbullet(PUSHBULLET_API_KEY) my_device = pushbullet.get_device(PUSHBULLET_DEVICE_NAME) file_data = pushbullet.upload_file(open(filename, "rb"), filename) pushbullet.push_file(device=my_device, **file_data) print "Sent!"
class PushBulletNotification(NotificationHelper): """ Send notification using PushBullet. https://www.pushbullet.com """ def __init__(self) -> None: token = input("Access Token: ") self.pb = Pushbullet(token) def notify(self, subject: str, text: str) -> None: print("Message:", '"""', text, '"""', sep="\n") push = self.pb.push_note(subject, text) if push["active"]: print("Sent!") else: raise Exception(str(push))
def check_staff_list(page, check_function, return_button_text, toast_title): """Go to a specific page for each staff member and perform a function.""" web = go_to_oracle_page(page, show_window=False) row_count = get_staff_table(web) toast = [] try: for i in range(1, row_count): # first one is mine - ignore this web.click(return_button_text) web.click(id=f'N3:Y:{i}') # link from 'Action' column at far right toast.append(check_function(return_button_text, web)) finally: web.driver.quit() if toast := '\n'.join(filter(None, toast)): print(toast_title) print(toast) Pushbullet(api_key).push_note(toast_title, toast)
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)
def initialise(): """Initialise the program with yout API key and preffered device.""" if version_info[0] == 2: rawinput = raw_input else: rawinput = input click.secho( "Please enter your API Key, you can obtain it from here: https://www.pushbullet.com/#settings/account", bold=True) api_key = rawinput() try: pb = Pushbullet(api_key) except pushbullet.errors.InvalidKeyError: click.secho( "Please check your API key again. Run this command again and try.") quit() click.secho( "Enter the serial number (eg 1 or 2) for your preffered device to send your music files", bold=True) i = 0 for device in pb.devices: print("{0} : {1}".format(i + 1, device)) i += 1 device_id = int(rawinput()) - 1 os.chdir(real_path_of_MobOff) if not os.path.exists('Music'): os.makedirs('Music') click.secho("The music would be downloaded to {0}/Music".format( os.getcwd())) data = {} data['user'] = [] data['user'].append({ 'api_key': api_key, 'device': str(pb.devices[device_id]), }) with open('data.txt', 'w') as outfile: json.dump(data, outfile) click.secho("Now you can run `moboff download` :) ", fg="green", bold=True)
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())
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)
def initialise(): """Initialise the program with your API key and preferred device.""" click.secho( "Please enter your API Key, you can obtain it from here: https://www.pushbullet.com/#settings/account", bold=True) api_key = rawinput() try: pb = Pushbullet(api_key) except pushbullet.errors.InvalidKeyError: click.secho( "Please check your API key again. Run this command again and try.") quit() click.secho( "Enter the serial number (eg 1 or 2) for your preferred device to send your music files", bold=True) for i, device in enumerate(pb.devices, 1): print("{0} : {1}".format(i, device.nickname)) device_id = int(rawinput()) - 1 if not 0 <= device_id <= len(pb.devices): click.secho("Choose from available device.") quit() click.secho("Please Select a directory for store the Downloads", bold=True) directory = select_directory() click.secho("The music would be downloaded to {0}".format(directory)) data = { 'user': { 'api_key': api_key, 'device': pb.devices[device_id].nickname, 'directory': directory, } } with open(os.path.join(real_path_of_MobOff, 'moboff_cfg.json'), 'w') as outfile: json.dump(data, outfile) click.secho("Now you can run `moboff download` :) ", fg="green", bold=True)
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))
def copy_60_minutes(): user_folder = os.environ['UserProfile'] Folder = namedtuple('Folder', ['address', 'min_length', 'max_length', 'min_count']) copy_folder_list = [Folder(os.path.join(user_folder, 'Commute'), 55, 70, 4), Folder(os.path.join(user_folder, '40 minutes'), 35, 40, 2)] # toast = '' toast, copy_folder_list = check_folder_list(copy_folder_list) if not copy_folder_list: print('Not ready to copy new album.') return albums = scan_music_folder(os.path.join(user_folder, 'Music')) toast += copy_albums(copy_folder_list, albums) if toast: Pushbullet(api_key).push_note('🎵 Commute Music', toast)
def clean(self): data = self.cleaned_data phone_number = (data['phone_country_code'] or '') + (data['phone_number'] or '') if phone_number: try: phone_number = phonenumbers.parse(phone_number, None) if not phonenumbers.is_valid_number(phone_number): self.add_error('phone_number', 'Invalid phone number') except phonenumbers.NumberParseException as e: self.add_error('phone_number', e) if data['pushbullet_access_token']: pushbullet_access_token = data['pushbullet_access_token'] try: Pushbullet(pushbullet_access_token) except PushbulletError: self.add_error('pushbullet_access_token', 'Invalid pushbullet access token.')