def monitor(self): current_model_list = os.listdir(self.model_path) from pushbullet import PushBullet pb = PushBullet(api_key=self.api_key) res1 = self.get_model_status(self.model_path, time.ctime()) res2, status = self.get_process_status(self.pid) pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body=res1 + res2) while True: now_model_list = os.listdir(self.model_path) if now_model_list == current_model_list: res2, status = self.get_process_status(self.pid) if status == 'fail': pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body='运行结束或者异常,请检查电脑运行情况!!!!!!!') break else: pass else: res1 = self.get_model_status(self.model_path, time.ctime()) res2, status = self.get_process_status(self.pid) current_model_list = now_model_list if status == 'fail': pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body='运行结束或者异常,请检查电脑运行情况!!!!!!!') break else: pb.push_note(title='神经网络进程运行情况监视器 made by 李帅', body=res1 + res2)
def add_alert(self, module, message): """ajoute une alerte""" if (not module in self.alertes) or self.alertes[module] != message: self.alertes[module] = message self.write_config() pb = PushBullet(self.api_key) note = pb.push_note(self.title + " - " + module, message)
def test__push_ok(): mock_response = Mock() mock_response.status_code = 200 mock_response.headers = {"X-Ratelimit-Remaining": "1000"} mock_response.json.return_value = {} session = Mock() session.post.return_value = mock_response pb = PushBullet("apikey") pb._session = session server_response = pb._push({"key": "value"}) session.post.assert_called_once_with( pb.PUSH_URL, data=json.dumps({"key": "value"}), ) assert server_response == { "rate_limit": { "remaining": "1000", "limit": None, "reset": None, } }
def send_alert_pushbullet(alert, email): pb = PushBullet(settings.PUSHBULLET_ACCESS_TOKEN) title = 'new alert: %s' % (alert.title, ) pb.push_link(title, 'http://127.0.0.1:8000/', body=alert.get_body(), email=email)
def __init__(self, auth_key, temp_folder, device_name, last_push=time.time(), device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:", device_name, "iden:", device.device_iden) self.device = device except Exception: print("Error: Unable to create device") raise self.check_pushes()
def __init__(self, config, store): self.key_words = config.key_words self.pushbullet = PushBullet(config.pushbullet_token) self.updated_streams = store.stream_changes.pipe( filter(lambda change: change['type'] == 'add' or (change[ 'type'] == 'change' and 'name' in change['changed_fields'])), pluck('stream'))
def notifyPushbullet(downlist): """ """ #prepare the interface pb = PushBullet(config.get("pushbullet_api_key")) devices = [] #identify desired targets for device in pb.devices: devicename = device.name deviceno = device.device_id target = config.get("pushbullet_target_dev") if target is not "": if target == devicename: devices.append(deviceno) else: devices.append(deviceno) #prepare message message = "The host(s): \n" for dom in downlist: message += " "+dom+" \n" message += "seems to be down." #actually push the messages for deviceno in devices: device = pb.get(deviceno) push = device.push_note("server monitor", message) if (push is None) or (push.status_code is not 200): return False return True
def pushFile(args): p = PushBullet(args.api_key) file = p.pushFile(args.device, open(args.file, 'rb')) if args.json: print(json.dumps(file)) return print("File %s sent to %s" % (file["iden"], file["target_device_iden"]))
def test_upload_file_request_fails(requests, pb_refresh): first_response = Mock() first_response.status_code = 400 first_response.json.return_value = { "data": "upload_data", "file_url": "imageurl", "upload_url": "http://uploadhere.google.com", } second_response = Mock() second_response.status_code = 200 session = Mock() session.post.return_value = first_response requests.post.return_value = second_response requests.codes.ok = 200 pb = PushBullet("apikey") pb._session = session with open("tests/test.png", "rb") as test_file: with pytest.raises(PushbulletError): pb.upload_file(test_file, "test.png", "image/png") requests.post.assert_not_called()
def push_to_iOS(title, body, pb_key_filename): with open(pb_key_filename) as pb_key_file: pb_key = pb_key_file.read() pb = PushBullet(pb_key) pb.push_note(title, body)
def pushNote(args): p = PushBullet(args.api_key) note = p.pushNote(args.device, args.title, " ".join(args.body)) if args.json: print(json.dumps(note)) return print("Note %s sent to %s" % (note["iden"], note["target_device_iden"]))
def pushList(args): p = PushBullet(args.api_key) lst = p.pushList(args.device, args.title, args.list) if args.json: print(json.dumps(lst)) return print("List %s sent to %s" % (lst["iden"], lst["target_device_iden"]))
def pushLink(args): p = PushBullet(args.api_key) link = p.pushLink(args.device, args.title, args.url) if args.json: print(json.dumps(link)) return print("Link %s sent to %s" % (link["iden"], link["target_device_iden"]))
def plugin(srv, item): ''' expects (apikey, device_id) in adddrs ''' srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target) if not HAVE_PUSHBULLET: srv.logging.warn("pushbullet is not installed") return False try: apikey, device_id = item.addrs except: srv.logging.warn("pushbullet target is incorrectly configured") return False text = item.message title = item.get('title', srv.SCRIPTNAME) try: srv.logging.debug("Sending pushbullet notification to %s..." % (item.target)) pb = PushBullet(apikey) pb.pushNote(device_id, title, text) srv.logging.debug("Successfully sent pushbullet notification") except Exception, e: srv.logging.warning("Cannot notify pushbullet: %s" % (str(e))) return False
def __init__(self, auth_key, device_name, last_push=time.time(), device_iden=None): self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.download_link) self.last_push = last_push self.device = None if device_iden: results = [ d for d in self.pb.devices if d.device_iden == device_iden and d.active ] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:", device_name, "iden:", device.device_iden) self.device = device except: print("Error: Unable to create device") raise
def test_push_sms_plaintext_failure(): device = Mock() device.device_iden = "123" mock_response = Mock() mock_response.status_code = 500 session = Mock() session.post.return_value = mock_response pb = PushBullet("apikey") pb._session = session with pytest.raises(PushError): pb.push_sms(device, "+123456789", "This is an example text") session.post.assert_called_once_with( pb.EPHEMERALS_URL, data=json.dumps({ "type": "push", "push": { "type": "messaging_extension_reply", "package_name": "com.pushbullet.android", "source_user_iden": "123", "target_device_iden": "123", "conversation_iden": "+123456789", "message": "This is an example text", }, }), )
def pushAddress(args): p = PushBullet(args.api_key) address = p.pushAddress(args.device, args.name, " ".join(args.address)) if args.json: print(json.dumps(address)) return print("Address %s sent to %s" % (address["iden"], address["target_device_iden"]))
def send_notification(api_key, page_title, site_url): print "Sending PushBullet notification" pb_client = PushBullet(api_key) pb_client.push_link("Update on {title}!".format(title=page_title), site_url)
def __init__(self, auth_key, temp_folder, device_name, last_push=0, device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [ d for d in self.pb.devices if d.device_iden == device_iden and d.active ] self.device = results[0] if results else None if not self.device: success, device = self.pb.new_device(device_name) if success: self.device = device else: print("Error ") print(device) self.check_pushes()
class PBEventHandler: def __init__(self): self.KEY = KEY self.HIST_FILE = HIST_FILE self.pb = PushBullet(KEY) self.maxmod = float(0) self.iden = None self._sync_maxmod() self._sync_maxmod(self._get_modified()) devices = self.pb.getDevices() for device in devices: if device['nickname'] == DEVICE: self.iden = device['iden'] break def _get_modified(self): return self.pb.getPushHistory(self.maxmod) def _sync_maxmod(self, pushes = []): for push in pushes: if float(push['modified']) > self.maxmod: self.maxmod = float(push['modified']) n = float(self.maxmod) try: fn = float(open(self.HIST_FILE).read()) + 0.01 except: fn = 0 fn = max(float(n), float(fn)) open(self.HIST_FILE, "w").write(str(fn)) self.maxmod = float(fn) def _event(self, data, callback): if data['type'] == 'tickle' and data['subtype'] == 'push': pushes = self.pb.getPushHistory(self.maxmod) for push in pushes: if push['modified'] > self.maxmod: self.maxmod = push['modified'] self._sync_maxmod() if self.iden != None and\ push['target_device_iden'] != self.iden: continue try: callback(push) except: pass def run(self, callback): def __event(data): print "event: " + str(data) self._event(data, callback) self.pb.realtime(__event)
def test_encryption(): pb = PushBullet("apikey", "hunter42") original = {"cat": "meow!"} encrypted = pb._encrypt_data(original) decrpyted = pb._decrypt_data(encrypted) assert original == json.loads(decrpyted)
def addDevice(args): p = PushBullet(args.api_key) devices = p.addDevice(args.nickname) if args.json: print(json.dumps(devices)) return print("Device %s was assigned ID %s" % (devices["nickname"], devices["iden"]))
def getDevices(args): p = PushBullet(args.api_key) devices = p.getDevices() if args.json: print(json.dumps(devices)) return for device in devices: print("%s %s %s" % (device["iden"], device["manufacturer"], device["model"]))
def test_decryption(): pb = PushBullet(API_KEY, encryption_password="******") pb._encryption_key = a2b_base64( "1sW28zp7CWv5TtGjlQpDHHG4Cbr9v36fG5o4f74LsKg=") test_data = "MSfJxxY5YdjttlfUkCaKA57qU9SuCN8+ZhYg/xieI+lDnQ==" decrypted = pb._decrypt_data(test_data) assert decrypted == "meow!"
class Notify: def __init__(self, title, link): self.__api = "" self.__title = title self.__link = link self.pb = PushBullet(self.__api) def push(self, message): self.pb.push_link(self.__title, self.__link, body=str(message))
def test_encryption_invalid_version(): pb = PushBullet("apikey", "hunter42") original = {"cat": "meow!"} encrypted = pb._encrypt_data(original) encrypted = "2" + encrypted[1:] with pytest.raises(Exception): pb._decrypt_data(encrypted)
class Notifier(BaseNotifier): def __init__(self, api_key): self.client = PushBullet(api_key) def notify(self, item): site_name = item.get('site') title = f'New property in {site_name}' link = item.get('url') self.client.push_link(title, link)
def PushNotification (push): try: if push_notification == "true": pb = PushBullet(push_token) phone = pb.get_device(push_device) push = phone.push_note("SolarPower", time.strftime("%H:%M") +" "+ push) return return except: print("PushNotification: failed")
def send_push(title, body): pushbullet = PushBullet(api_key) if not devices: pushbullet.push_note(title=title, body=body) else: # load devices d = pushbullet.devices for i in devices: d[i].push_note(title=title, body=body)
class PushBulletNotify(object): def __init__(self, api_key): self.api_key = api_key self.pb = PushBullet(api_key) self.pb.reload_devices() # TODO is this needed? def send(self, title, text): for device in self.pb.devices: device.push_note(title, text)
def pushNote(args): p = PushBullet(args.api_key) note = p.pushNote(args.device, args.title, " ".join(args.body)) if args.json: print(note) return if "created" in note: print("OK") else: print("ERROR %s" % (note))
class PushBulletAlert: def __init__(self, api_key, imagedir): self.pb = PushBullet(api_key) self.imagedir = imagedir def sendAlert(self, image): imagedata = open(os.path.join(self.imagedir, image), 'rb') success, file_data = self.pb.upload_file(imagedata, 'Motion detected: ' + image) success, push = self.pb.push_file(**file_data) return success
def pushbullet_post(self, issue): """ Posts to Pushbullet API. For future reference, the push_note() function returns two values. One bool that specificies whether the push was a success or not, and a dict with additional info. """ pb = PushBullet('YOUR-API-KEY') worked, push = pb.push_note(u"Förseningar", issue) if not worked: print(push)
class PushBulletLogger(Logger): def __init__(self, level: int, api_key: str) -> None: super().__init__(level) self._pb = PushBullet(api_key) def alert(self, level: int, alert_title: str, alert_msg: str) -> None: super().alert(level, alert_title, alert_msg) try: self._pb.push_note("Cryptrade Alert: ", alert_title) except Exception: self.log(level, "PushBullet notification failed!")
class PB_Alarm(Alarm): def __init__(self, api_key): self.client = PushBullet(api_key) log.info("PB_Alarm intialized.") push = self.client.push_note("PokeAlarm activated!", "We will alert you about pokemon.") def pokemon_alert(self, pokemon): notification_text = "A wild " + pokemon['name'].title() + " has appeared!" google_maps_link = gmaps_link(pokemon["lat"], pokemon["lng"]) time_text = pkmn_time_text(pokemon['disappear_time']) push = self.client.push_link(notification_text, google_maps_link, body=time_text)
def test_get_data_ok(): mock_response = Mock() mock_response.status_code = 200 session = Mock() session.get.return_value = mock_response pb = PushBullet("apikey") pb._session = session pb._get_data("url")
def test_push_note_no_recipents(pb_push, pb_refresh): pb = PushBullet("apikey") pb.push_note("test_note title", "test_note body") pb_push.assert_called_with({ "type": "note", "title": "test_note title", "body": "test_note body", })
def pushLink(args): p = PushBullet(args.api_key) link = p.pushLink(args.device, args.title, args.url) if args.json: print(json.dumps(link)) return if args.device and args.device[0] == '#': print("Link broadcast to channel %s" % (args.device)) elif not args.device: print("Link %s sent to all devices" % (link["iden"])) else: print("Link %s sent to %s" % (link["iden"], link["target_device_iden"]))
class PushBulletSender(Sender): def __init__(self, setting): super(PushBulletSender, self).__init__(setting) self.pushbullet = PushBullet(self.config_api) if hasattr(self, 'config_channel'): self.pushbullet = self.pushbullet.get_channel(self.config_channel) def post(self, title, message, url): if url: message = '{}\n{}'.format(message, url) self.pushbullet.push_note(title, message)
def push(self): """ Push a task """ p = PushBullet(self.api) if self.type == 'text': success, push = p.push_note(self.title, self.message) elif self.type == 'list': self.message = self.message.split(',') success, push = p.push_list(self.title, self.message) elif self.type == 'link': success, push = p.push_link(self.title, self.message) else: success, push = p.push_file(file_url=self.message, file_name="cat.jpg", file_type="image/jpeg")
def pushNote(args): p = PushBullet(args.api_key) note = p.pushNote(args.device, args.title, " ".join(args.body)) if args.json: print(json.dumps(note)) return if args.device and args.device[0] == '#': print("Note broadcast to channel %s" % (args.device)) elif not args.device: print("Note %s sent to all devices" % (note["iden"])) else: print("Note %s sent to %s" % (note["iden"], note["target_device_iden"]))
def pushAddress(args): p = PushBullet(args.api_key) address = p.pushAddress(args.device, args.name, " ".join(args.address)) if args.json: print(json.dumps(address)) return if args.device and args.device[0] == '#': print("Address broadcast to channel %s" % (args.device)) elif not args.device: print("Address %s sent to all devices" % (address["iden"])) else: print("Address %s sent to %s" % (address["iden"], address["target_device_iden"]))
def pushFile(args): p = PushBullet(args.api_key) file = p.pushFile(args.device, os.path.basename(args.file), "", open(args.file, 'rb')) if args.json: print(json.dumps(file)) return if args.device and args.device[0] == '#': print("File broadcast to channel %s" % (args.device)) elif not args.device: print("File %s sent to all devices" % (file["iden"])) else: print("File %s sent to %s" % (file["iden"], file["target_device_iden"]))
def push_note(self, event): """ Pushes a note to the configured pushbullet accounts """ host = event.host title = event.title + ": " + host message = host + ": " + event.message + " at " + \ event.timestamp.strftime("%H:%M:%S %m/%d/%y") for key in self.api_keys: pb = PushBullet(key) pb.push_note(title, message)
def pushSelfie(message): try: p = PushBullet(apiKey) myPhone = p.devices[0] print("uploading") with open('/home/pi/sb/selfie.jpg', "rb") as pic: file_data = p.upload_file(pic,"selfie.jpg") file_data = str(file_data) fileURL = file_data[file_data.find("https"):file_data.find("'})")] print (fileURL) myPhone.push_file(file_url=fileURL,file_name="selfie.jpg",file_type="image/jpeg") except: #todo: gracefully handle exceptions, wouldya e = sys.exc_info()[0] print(e)
class PushBulletNotificationService(BaseNotificationService): """ Implements notification service for Pushbullet. """ def __init__(self, api_key): from pushbullet import PushBullet self.pushbullet = PushBullet(api_key) def send_message(self, message="", **kwargs): """ Send a message to a user. """ title = kwargs.get(ATTR_TITLE) self.pushbullet.push_note(title, message)
class PushbulletLogHandler(logging.Handler): def __init__(self, api_key, stack_trace=False): logging.Handler.__init__(self) self.api_key = api_key self.stack_trace = stack_trace self.pb_session = PushBullet(self.api_key) def emit(self, record): message = '{}'.format(record.getMessage()) if self.stack_trace and record.exc_info: message += '\n' message += '\n'.join(traceback.format_exception(*record.exc_info)) self.pb_session.push_note('' + str(self.level), message)
def __init__(self, auth_key, temp_folder, device_name, last_push = time.time(), device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: try: device = self.pb.new_device(device_name) print("Created new device:",device_name,"iden:",device.device_iden) self.device = device except: print("Error: Unable to create device") raise self.check_pushes()
def __init__(self, auth_key, temp_folder, device_name, last_push=0, device_iden=None): self.temp_folder = temp_folder if not os.path.exists(self.temp_folder): os.makedirs(temp_folder) self._auth_key = auth_key self.pb = PushBullet(self._auth_key) self.listener = Listener(self.pb, self.watcher) self.last_push = last_push self.device = None if device_iden: results = [d for d in self.pb.devices if d.device_iden == device_iden and d.active] self.device = results[0] if results else None if not self.device: success, device = self.pb.new_device(device_name) if success: self.device = device else: print("Error ") print(device) self.check_pushes()
def __init__(self, settings): self.client = PushBullet(settings['api_key']) log_msg = "Pushbullet Alarm intialized" if 'name' in settings: self.name = settings['name'] log_mst = log_msg + ": " + self.name log.info(log_msg) push = self.client.push_note("PokeAlarm activated!", "We will alert you about pokemon.")