def __init__(self, spread_threshold: int, api_key: str) -> None: super(Pushbullet, self).__init__(spread_threshold) # ToDo: Raise error when api key is missing if api_key == 'DEBUG': self._pb = None else: self._pb = pb_lib.Pushbullet(api_key=api_key)
def pushb(word, word_eol, userdata): """ Hook for /pushb command in HexChat""" api_key = hexchat.get_pluginpref(CONFIG_APIKEY) if word[1] == 'CONFIG': if len(word_eol) > 2: set_config(word_eol[2]) else: hexchat.prnt( 'Pushbullet API key currently set to "{}"'.format(api_key)) return hexchat.EAT_HEXCHAT if not api_key: hexchat.prnt('\037\00304Pushbullet API key not specified.', ' Use /pushb CONFIG <api_key> to set one.') return hexchat.EAT_HEXCHAT try: pb = pushbullet.Pushbullet(api_key) except pushbullet.errors.InvalidKeyError: hexchat.prnt('\037\00304Invalid API key!') return hexchat.EAT_HEXCHAT push(word, word_eol) return hexchat.EAT_HEXCHAT
def pushbullet(self) -> pb.Pushbullet: if self.__pushbullet is None: # pushbullet.Pushbullet sends a request on initialization, # so delay it self.__pushbullet = pb.Pushbullet(self._token) assert isinstance(self.__pushbullet, pb.Pushbullet) return self.__pushbullet
def test_decryption(): pb = pushbullet.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!"
def push_note(config, title, note): log.info('pushing to {} + {} with {} {}'.format(config.pushbullet_api, config.pushbullet_device, title, note)) # quick hack to give an object that pushbullet.py expects device = Device() device.device_iden = config.pushbullet_device pb = pushbullet.Pushbullet(config.pushbullet_api) pb.push_note(title, note, device=device)
def __init__(self, config): super(PBLogHandler, self).__init__() if (config.pushbullet_api is None or config.pushbullet_device is None): self.pb = None return pb_api = pushbullet.Pushbullet(config.pushbullet_api) pb_devices = pb_api.devices pb_device = next( filter(lambda x: x.device_iden == config.pushbullet_device, pb_devices)) self.pb = pb_device
def send(job): TOKEN = config.get('pushbullet', 'access-token', None) if not TOKEN: logger.warning("No access token set.") return logger.info("Notifing via pushbullet: " + job.name) pb = pushbullet.Pushbullet(TOKEN) pb.push_note("Seedpipe: Download Complete", job.name)
def pushbullet(cls, title=None, message=None, api=None, debugx=True): if not api: api = cls.pushbullet_api if not api: api = cls.conf.get_config('pushbullet', 'api') if not title: title = cls.title if not title: title = cls.conf.get_config('pushbullet', 'title') if not message: message = cls.message if not message: message = cls.conf.get_config('pushbullet', 'message') if not api: if os.getenv('DEBUG') == '1': print( make_colors("[Pushbullet]", 'lightwhite', 'lightred') + " " + make_colors('API not Found', 'lightred', 'lightwhite')) return False if cls.active_pushbullet or cls.conf.get_config( 'service', 'pushbullet', value=0) == 1 or cls.active_pushbullet or cls.conf.get_config( 'service', 'pushbullet', value=0) == "1" or os.getenv( 'TRACEBACK_PUSHBULLET') == '1': try: pb = PB.Pushbullet(api) pb.push_note(title, message) return True except: if os.getenv('DEBUG') == '1': print( make_colors("ERROR [PUSHBULLET]:", 'lightwhite', 'lightred', 'blink')) print( make_colors(traceback.format_exc(), 'lightred', 'lightwhite')) if os.getenv('DEBUG') == '1': print( make_colors("[Pushbullet]", 'lightwhite', 'lightred') + " " + make_colors('sending error', 'lightred', 'lightwhite')) return False else: print( make_colors("[PUSHBULLET]", 'lightwhite', 'lightred') + " " + make_colors( 'warning: Pushbullet is set True but not active, please change config file to true or 1 or set TRACEBACK_PUSHBULLET=1 to activate !', 'lightred', 'lightyellow')) return False
def __init__(self, options): self.logger = logging.getLogger("ODP") self.options = options if self.options.debug: self.logger.setLevel(logging.DEBUG) self.logger.debug("Command line options: %s" % self.options) else: self.logger.setLevel(logging.INFO) # Set a timestamp for our time cursor \ self.time_cursor = time.time() # Load our config if self.options.envconf: self.config = json.loads(os.getenv("ODP_CONFIG")) else: with open(self.options.config, 'r') as config_file: self.config = json.load(config_file) self.logger.debug("Loaded config: %s" % self.config) # Validate the config contains some minimally useful things if "odp_device_name" not in self.config: self.config["odp_device_name"] = DEFAULT_DEVICE_NAME # Create our PushBullet object and find our device within it self.pb = pushbullet.Pushbullet(self.config["api_key"]) try: self.pb_device = self.pb.get_device(self.config["odp_device_name"]) except pushbullet.errors.InvalidKeyError: self.pb_device = self.pb.new_device(self.config["odp_device_name"]) self.logger.debug("Our device: %s" % self.pb_device) # Check if we're doing a one-shot action, or going into server mode if self.options.show_devices: self.logger.info("Pushbullet devices:") for device in self.pb.devices: print(" %s: %s" % (device.nickname, device.device_iden)) sys.exit(0) # Create our listener self.pb_listener = pushbullet.Listener(account=self.pb, on_push=self.newEvent) # Run the listener try: self.pb_listener.run_forever() except KeyboardInterrupt: self.pb_listener.close()
def connect(api_key, password): """ Return the account and the listener object we'll use to fetch pushes, etc. We'll pass it to the `on_push` handler afterwards. """ pb_account = pushbullet.Pushbullet(api_key, encryption_password=password) listener = pushbullet.Listener(account=pb_account, on_push=functools.partial( on_push, pb_account), on_error=on_error, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) return listener
def send_notification(self, message): api_keys = tuple(k.strip() for k in self.config['api_keys'].split(', ')) for key in api_keys: device = None if ':' in key: device, key = key.split(':') pb = pushbullet.Pushbullet(key) if device: try: device = pb.get_device(device) except pushbullet.errors.InvalidKeyError: self.logger.error( "failed to get pushbullet device: {0}".format(device)) pb.push_note(self.config['identifier'], message, device=device)
def start_messaging_Pushbullet(token=None, filepath_token="~/.pushbullet"): if token is None: filepath_token = os.path.expanduser(os.path.expandvars(filepath_token)) if os.path.isfile(filepath_token): file_token_contents =\ [line.rstrip("\n") for line in open(filepath_token)] token = [line for line in file_token_contents if line] if token: token = token[0] else: print("no Pushbullet token specified or found in {filepath}". format(filepath=filepath_token)) sys.exit() global pb pb = pushbullet.Pushbullet(token)
def pushNotify(pushbulletAPItoken, msg): try: pbInstance = pushbullet.Pushbullet(pushbulletAPItoken) pbInstance.push_note("New whisper: ", msg) printLine("S", "Ok") printLine('C', "Waiting for delay...") except pushbullet.errors.InvalidKeyError: printLine('E', "Error: Invalid api key. Please check your access token") printLine('E', "Exit...") exitApp() except pushbullet.errors.PushError as error: printLine('E', "Error: " + str(error)) return except Exception, e: printLine('E', "Error sending notification: " + str(e)) return
def button_confirm(self): if self.env['api.key'].search([], limit=1).status == 'on': for order in self: if order.state not in ['draft', 'sent']: continue order._add_supplier_to_product() # Deal with double validation process if order.company_id.po_double_validation == 'one_step' \ or (order.company_id.po_double_validation == 'two_step' \ and order.amount_total < self.env.user.company_id.currency_id.compute( order.company_id.po_double_validation_amount, order.currency_id)) \ or order.user_has_groups('purchase.group_purchase_manager'): order.button_approve() else: order.write({'state': 'to approve'}) # --------- Push SMS Notification -------- po = str(self.name) amount_total = str(self.amount_total) vendor = str(self.partner_id.name).title() mobile = str(self.partner_id.mobile) currency_id = str(self.currency_id.name) date_order = str(dateutil.parser.parse(self.date_order).date()) sms = 'Chào bạn ' + vendor + ', đơn hàng ' + po + ' đã xác nhận.' + ' Giá trị đơn hàng: ' + amount_total + ' ' + currency_id + '. Ngày đặt hàng: ' + date_order # pb.push_sms(device, mobile, sms) pb = pushbullet.Pushbullet(self.env['api.key'].search( [], limit=1).api_key) device = pb.devices[0] pb.push_sms(device, mobile, sms) return True else: for order in self: if order.state not in ['draft', 'sent']: continue order._add_supplier_to_product() # Deal with double validation process if order.company_id.po_double_validation == 'one_step' \ or (order.company_id.po_double_validation == 'two_step' \ and order.amount_total < self.env.user.company_id.currency_id.compute( order.company_id.po_double_validation_amount, order.currency_id)) \ or order.user_has_groups('purchase.group_purchase_manager'): order.button_approve() else: order.write({'state': 'to approve'}) return True
def api_note(self, title, body, channel=None): """ send a note through pushbullet @Ytitle@w = the title of the note @Ybody@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: self.api('send.error')('pushbullet apikey not set') return False if not pushbullet: if not self.import_pushbullet(): return False pbc = pushbullet.Pushbullet(apikey) rval = {} found = False nchannel = channel or self.api('setting.gets')('channel') if nchannel: for i in pbc.channels: if str(i.channel_tag) == nchannel: found = True rval = i.push_note(title, body) break if not found: self.api('send.error')('There was no channel %s' % nchannel) return False else: rval = pbc.push_note(title, body) pbc._session.close() # pylint: disable=protected-access if 'error' in rval: self.api('send.error')('Pushbullet send failed with %s' % rval) return False self.api('send.msg')('pb returned %s' % rval) return True
def __init__( self, configFile, statusFile ): self.configFile = configFile self.statusFile = statusFile try: self.pb = pushbullet.Pushbullet( self.configFile.getValue( convmgrnotification.__pushbulletAPIKey_Key__ ) ) except: self.pb = None self.maxNotifyPeriod = self.configFile.getValue( convmgrnotification.__maxNotifyPeriod_Key__ ) if not self.maxNotifyPeriod: self.maxNotifyPeriod = convmgrnotification.__defaultMaxNotifyPeriod__ lastNotifyTime = self.statusFile.getData( convmgrnotification.__lastNotifyTime_Key__ ) if lastNotifyTime: self.lastNotifyTime = datetime.datetime.strptime( lastNotifyTime, convmgrnotification.__datetimeFormat__ ) else: self.lastNotifyTime = datetime.datetime.now( )
def connect(self): self.pushbullet = pushbullet.Pushbullet(*self.config.getAuth()) self.id = (self.__NAME__, self.uid) self.listener = pushbullet.Listener( self.pushbullet, lambda event: (self._pushFetch() if event["type"] == "tickle" else None)) self.device = ( [d for d in self.pushbullet.devices if d.nickname == "NotiHub"] + [None])[0] if not self.device: try: self.device = self.pushbullet.new_device("NotiHub") print("Created new device: NotiHub (id: %s)" % self.device.device_iden) except: print("Error: Unable to create device") raise self.last_push = 0 self.listen()
def send(self, **kwargs): if not self.access_token: log.error("You must specify an access_token when initializing this class") return False # send notification try: pb = pushbullet.Pushbullet(self.access_token) if self.device is not None: for i in pb.devices: if i.device_iden == self.device or i.nickname == self.device: i.push_note(self.sender, kwargs['message']) else: pb.push_note(self.sender, kwargs['message']) return True except Exception:r log.exception("Error sending notification via Pushbullet")
def cmd_channels(self, _): """ list the channels """ tmsg = [] apikey = self.api('%s.apikey' % self.sname)() if not apikey: self.api('send.error')('pushbullet apikey not set') return False if not pushbullet: if not self.import_pushbullet(): return False pbc = pushbullet.Pushbullet(apikey) for i in pbc.channels: tmsg.append(str(i.channel_tag)) return True, tmsg
def __init__(self): """ Configures logging, reads configuration and tries to enable pushbullet """ # configure logging logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) self.logger = logging.getLogger("chaturbate") self.logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%Y-%m-%d %H:%M:%S") console_handler.setFormatter(formatter) self.logger.addHandler(console_handler) # read configuration self.config_parser = ConfigParser.ConfigParser() self.config_parser.read("config.ini") # is pushbullet is enabled on the config if self.config_parser.get('PushBullet', 'enable') == 'true': # try to import it and connect try: import pushbullet self.push_bullet = pushbullet.Pushbullet( self.config_parser.get('PushBullet', 'access_token')) except (ImportError, pushbullet.InvalidKeyError): self.push_bullet = None # create a requests object that has sessions self.req = requests.Session() self.username = self.config_parser.get('User', 'username') self.password = self.config_parser.get('User', 'password')
import pushbullet apiKey = "XXXXXX" #withheld from Git repository pb = pushbullet.Pushbullet(apiKey) push = pb.push_note( "Vehicle occupant in danger!", "An occupant you left behind is being subjected to dangerous conditions.")
def __init__(self, config): self.config = config self.pushbullet = pushbullet.Pushbullet(config['token'])
def __init__(self, device_name): api_key = __salt__["config.get"]("pushbullet.api_key") or __salt__[ "config.get"]("pushbullet:api_key") self.pb = pushbullet.Pushbullet(api_key) self.target = self._find_device_by_name(device_name)
def test_auth_fail(): with pytest.raises(pushbullet.InvalidKeyError): pushbullet.Pushbullet("faultykey")
def test_auth_success(): pb = pushbullet.Pushbullet(API_KEY) assert pb.user_info["name"] == os.environ.get("PUSHBULLET_NAME", "Pushbullet Tester")
def test_auth_success(): pb = pushbullet.Pushbullet(API_KEY) assert pb.user_info["name"] == "Pushbullet Tester"
#!/usr/bin/env python import time import subprocess import pushbullet import keys time.sleep(3) ip = subprocess.check_output(["hostname -I"], shell=True) try: pb = pushbullet.Pushbullet(keys.PUSH) push = pb.push_sms(pb.devices[0], keys.PHONE, "EVE is online at http://" + ip) print("sending...") except Exception, e: print("send failled...") print(e)
def main_pushbullet(arguments): device_name = 'Bandit' account = pushbullet.Pushbullet(arguments.api_key) device = next( (device for device in account.devices if device.nickname == device_name), None) if device is None: device = account.new_device(device_name) if not os.path.isdir(arguments.report_directory): os.makedirs(arguments.report_directory) print('[*] created report directory: ' + arguments.report_directory) work_queue = queue.Queue() listener = pushbullet_listener.PushbulletDeviceListener( account, device=device, on_push=work_queue.put) listener.start() print('[*] started listener for pushbullet links shared with: ' + device_name) while True: try: work_item = work_queue.get() except KeyboardInterrupt: break scan_uid = None if work_item.get('type') == 'link': scan_target = work_item.get('url') elif work_item.get('type') == 'note': try: work_item['body'] = json.loads(work_item['body']) except ValueError: continue scan_target = work_item['body'].get('url') scan_uid = work_item['body'].get('uid') if scan_target is None: continue requesting_device = next( (device for device in account.devices if device.device_iden == work_item.get('source_device_iden')), None) if requesting_device is None: print("[*] received request to scan: {0}".format(scan_target)) else: print("[*] received request to scan: {0} from {1}".format( scan_target, (requesting_device.nickname or requesting_device.device_iden))) if scan_uid is None: scan_uid = utilities.generate_scan_uid(scan_target) try: scanner = _run_scan(arguments, scan_target) report = scanner.get_report() except Exception: account.push_note( 'Bandit Scan Error', "An error occurred while scanning: {0}".format(scan_target), device=requesting_device) traceback.print_exc() continue report.data['_jj']['name'] = work_item.get('title') report.data['_jj']['uid'] = scan_uid report.data['_jj']['url'] = scan_target metrics_totals = report.data['metrics']['_totals'] summary = "high:{0} medium:{1} low:{2}".format( metrics_totals['SEVERITY.HIGH'], metrics_totals['SEVERITY.MEDIUM'], metrics_totals['SEVERITY.LOW']) report_text = "Title: {0}\nUID: {1}\nSummary: {2}".format( work_item['title'], scan_uid, summary) # put the response note in a timer thread so any external actions have a # head start before the user is notified that the job completed thread = threading.Timer(60, account.push_note, ('Bandit Report Summary', report_text), {'device': requesting_device}) thread.start() report_directory = os.path.join(arguments.report_directory, scan_uid) os.mkdir(report_directory) with open(os.path.join(report_directory, 'stderr.txt'), 'wb') as file_h: file_h.write(scanner.stderr) with open(os.path.join(report_directory, 'stdout.txt'), 'wb') as file_h: file_h.write(scanner.stdout) report.to_json_file(os.path.join(report_directory, 'report.json')) report.to_pdf_file(os.path.join(report_directory, 'report.pdf')) listener.close()
parser.add_argument('message', metavar=('Message'), type=str, help='Message you want to push to the device(s).') # Argument processing args = parser.parse_args() access_token = args.access_token subject = args.subject message = args.message # Check if a destination device has been supplied device = "all" if "|" in access_token: access_token, device = access_token.split("|") # Try to login with AcessToken try: pb = pushbullet.Pushbullet(access_token) except (pushbullet.InvalidKeyError) as exc: l("Error: Can't connect to Pushbullet with AccessToken [%s]: %s" % (access_token, str(exc))) sys.exit(1) # Select the right device if specified if not device == "all": found_device = findDevice(pb.devices, device) if not found_device: l("Error: Device [%s] not found." % device) sys.exit(1) else: device = found_device try: pb = pb.get_device(found_device)
import pushbullet from axel import config pushbullet_client = None sender = None if not pushbullet_client and config['pushbullet_key']: pushbullet_client = pushbullet.Pushbullet(config['pushbullet_key']) if config['pushbullet_channel']: for channel in pushbullet_client.channels: if channel.name == config['pushbullet_channel']: sender = channel if not sender: raise RuntimeError('Could not find specified Pushbullet channel') else: sender = pushbullet_client prev_message = None def pb_notify(message): global prev_message # Prevent spamming runaway messages if prev_message == message: return if sender: sender.push_note('Axel', message) prev_message = message