Exemplo n.º 1
0
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
Exemplo n.º 2
0
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
Exemplo n.º 3
0
def send_note(title, body):
    '''Sends Pushbullet notification to all mobile devices linked to your account.
    The account details are derived from PUSHBULLET_API_KEY provided in private.py.
    Title and body text must be provided.
    '''
    if type(private.PUSHBULLET_API_KEY) != iter:
        private.PUSHBULLET_API_KEY = [private.PUSHBULLET_API_KEY]

    for key in private.PUSHBULLET_API_KEY:
        p = PushBullet(key)
        devices = p.getDevices()
        for d in devices:
            if d['icon'] == 'phone':
                p.pushNote(d['iden'], title=title, body=body)
Exemplo n.º 4
0
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"]))
Exemplo n.º 5
0
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"]))
Exemplo n.º 6
0
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))
Exemplo n.º 7
0
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))
Exemplo n.º 8
0
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"]))
Exemplo n.º 9
0
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"]))
import socket
import sys
import pushbullet
from pushbullet import PushBullet
from socket import socket, SOCK_DGRAM, AF_INET 

#getting IP address
s = socket(AF_INET, SOCK_DGRAM) 
s.connect(('google.com', 0))#using Google since it's pretty well always reachable
IP = s.getsockname()[0] #grab IP portion

#Make sure to put your api key here to work!
apiKey = "YOUR_API_KEY_HERE"

#create pushbullet obj and get list of devices
pb = PushBullet(apiKey)
devices = pb.getDevices()

#push IP to device!
pb.pushNote(devices[0]["id"], "IP Address", IP)
Exemplo n.º 11
0
        # read the analog pin
        trim_pot = readadc(hw_map[i][0], SPICLK, SPIMOSI, SPIMISO, SPICS)
        # how much has it changed since the last read?
        pot_adjust = abs(trim_pot - last_read[i])

        if ( pot_adjust > tolerance ):
               trim_pot_changed = True

        #if DEBUG:
        #        print "trim_pot_changed", trim_pot_changed

        if ( trim_pot_changed ):
                set_volume = trim_pot / 10.24           # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level
                set_volume = round(set_volume)          # round out decimal value
                set_volume = int(set_volume)            # cast volume as integer

#                print 'Volume = {volume}%' .format(volume = set_volume)


                # save the potentiometer reading for the next loop
                last_read[i] = trim_pot
                message = "rPi analog state changed to: %d" % (trim_pot)
                print message
                if trim_pot < 100:
                    p.pushNote(keys.pushbullet_device, 'Door opened.', hw_map[i][1]);
                else:
                    p.pushNote(keys.pushbullet_device, 'Door closed', hw_map[i][1])

        # hang out and do nothing for a half second
        time.sleep(1.0)
Exemplo n.º 12
0
class Pushbullet(AgoAlert):
    """Class for push message sending for ios and android
       @info https://www.pushbullet.com """
    def __init__(self, apikey, devices):
        """Constructor"""
        AgoAlert.__init__(self)
        global client
        self.name = 'pushbullet'
        self.pushbullet = None
        self.apikey = apikey
        if len(devices)==0:
            self.devices = []
        else:
            self.devices = json.loads(devices)
        self.pbdevices = {}
        self.pushTitle = 'Agocontrol'
        if apikey and len(apikey)>0 and devices and len(devices)>0:
            self.__configured = True
            self.pushbullet = PushBullet(self.apikey)
            client.emit_event('alertcontroller', "event.device.statechanged", STATE_PUSH_CONFIGURED, "")
        else:
            self.__configured = False
            client.emit_event('alertcontroller', "event.device.statechanged", STATE_PUSH_NOT_CONFIGURED, "")

    def getConfig(self):
        configured = 0
        if self.__configured:
            configured = 1
        return {'configured':configured, 'apikey':self.apikey, 'devices':self.devices, 'provider':self.name}

    def getPushbulletDevices(self, apikey=None):
        """request pushbullet to get its devices"""
        if not self.__configured and not apikey:
            logging.error('Pushbullet: unable to get devices. Not configured and no apikey specified')
            return {}
        
        if apikey:
            self.pushbullet = PushBullet(apikey)

        devices = []
        if self.pushbullet:
            devs = self.pushbullet.getDevices()
            logging.debug('pushbullet devs=%s' % str(devs))
            for dev in devs:
                name = '%s %s (%s)' % (dev['extras']['manufacturer'], dev['extras']['model'], dev['id'])
                self.pbdevices[name] = {'name':name, 'id':dev['id']}
                devices.append(name)
        else:
            logging.error('Pushbullet: unable to get devices because not configured')
        return devices

    def setConfig(self, apikey, devices):
        """set config
           @param apikey: pushbullet apikey (available on https://www.pushbullet.com/account)
           @param devices: array of devices (id) to send notifications """
        if not apikey or len(apikey)==0 or not devices or len(devices)==0:
            logging.error('Pushbullet: all parameters are mandatory')
            return False
        if not agoclient.set_config_option('push', 'provider', 'pushbullet','alert') or not agoclient.set_config_option('pushbullet', 'apikey', apikey, 'alert') or not agoclient.set_config_option('pushbullet', 'devices', json.dumps(devices), 'alert'):
            logging.error('Pushbullet: unable to save config')
            return False
        self.apikey = apikey
        self.devices = devices
        self.pbdevices = {}
        self.pushbullet = PushBullet(self.apikey)
        self.__configured = True
        client.emit_event('alertcontroller', "event.device.statechanged", STATE_PUSH_CONFIGURED, "")
        return True

    def addPush(self, message, file=None):
        """Add push
           @param message: push notification
           @file: full file path to send"""
        if self.__configured:
            #check params
            if not message or len(message)==0:
                if not file or len(file)==0:
                    logging.error('Pushbullet: Unable to add push (at least one parameter is mandatory)')
                    return False
            elif not file or len(file)==0:
                if not message or len(message)==0:
                    logging.error('Pushbullet: Unable to add push (at least one parameter is mandatory)')
                    return False
            if message==None:
                message = ''
            if file==None:
                file = ''
            #queue push message
            self._addMessage({'message':message, 'file':file})
            return True
        else:
            logging.error('Pushover: unable to add message because not configured')
            return False

    def _send_message(self, message):
        #get devices from pushbullet if necessary
        if len(self.pbdevices)==0:
            self.getPushbulletDevices()

        #push message
        for device in self.devices:
            #get device id
            if self.pbdevices.has_key(device):
                if len(message['file'])==0:
                    #send a note
                    resp = self.pushbullet.pushNote(self.pbdevices[device]['id'], self.pushTitle, message['message'])
                    logging.info(resp)
                else:
                    #send a file
                    resp = self.pushbullet.pushFile(self.pbdevices[device]['id'], message['file'])
            else:
                logging.warning('Pushbullet: unable to push notification to device "%s" because not found' % (device))
Exemplo n.º 13
0
class Pushbullet(AgoAlert):
    """Class for push message sending for ios and android
       @info https://www.pushbullet.com """
    def __init__(self, apikey, devices):
        """Constructor"""
        AgoAlert.__init__(self)
        global client
        self.name = 'pushbullet'
        self.pushbullet = None
        self.apikey = apikey
        if len(devices)==0:
            self.devices = []
        else:
            self.devices = json.loads(devices)
        self.pbdevices = {}
        self.pushTitle = 'Agocontrol'
        if apikey and len(apikey)>0 and devices and len(devices)>0:
            self.__configured = True
            self.pushbullet = PushBullet(self.apikey)
            client.emitEvent('alertcontroller', "event.device.statechanged", STATE_PUSH_CONFIGURED, "")
        else:
            self.__configured = False
            client.emitEvent('alertcontroller', "event.device.statechanged", STATE_PUSH_NOT_CONFIGURED, "")

    def getConfig(self):
        configured = 0
        if self.__configured:
            configured = 1
        return {'configured':configured, 'apikey':self.apikey, 'devices':self.devices, 'provider':self.name}

    def getPushbulletDevices(self, apikey=None):
        """request pushbullet to get its devices"""
        if not self.__configured and not apikey:
            logging.error('Pushbullet: unable to get devices. Not configured and no apikey specified')
            return {}
        
        if apikey:
            self.pushbullet = PushBullet(apikey)

        devices = []
        if self.pushbullet:
            devs = self.pushbullet.getDevices()
            logging.debug('pushbullet devs=%s' % str(devs))
            for dev in devs:
                name = '%s %s (%s)' % (dev['extras']['manufacturer'], dev['extras']['model'], dev['id'])
                self.pbdevices[name] = {'name':name, 'id':dev['id']}
                devices.append(name)
        else:
            logging.error('Pushbullet: unable to get devices because not configured')
        return devices

    def setConfig(self, apikey, devices):
        """set config
           @param apikey: pushbullet apikey (available on https://www.pushbullet.com/account)
           @param devices: array of devices (id) to send notifications """
        if not apikey or len(apikey)==0 or not devices or len(devices)==0:
            logging.error('Pushbullet: all parameters are mandatory')
            return False
        if not agoclient.setConfigOption('push', 'provider', 'pushbullet','alert') or not agoclient.setConfigOption('pushbullet', 'apikey', apikey, 'alert') or not agoclient.setConfigOption('pushbullet', 'devices', json.dumps(devices), 'alert'):
            logging.error('Pushbullet: unable to save config')
            return False
        self.apikey = apikey
        self.devices = devices
        self.pbdevices = {}
        self.pushbullet = PushBullet(self.apikey)
        self.__configured = True
        client.emitEvent('alertcontroller', "event.device.statechanged", STATE_PUSH_CONFIGURED, "")
        return True

    def addPush(self, message, file):
        """Add push
           @param message: push notification
           @file: full file path to send"""
        if self.__configured:
            #check params
            if not message or len(message)==0:
                if not file or len(file)==0:
                    logging.error('Pushbullet: Unable to add push (at least one parameter is mandatory)')
                    return False
            elif not file or len(file)==0:
                if not message or len(message)==0:
                    logging.error('Pushbullet: Unable to add push (at least one parameter is mandatory)')
                    return False
            if message==None:
                message = ''
            if file==None:
                file = ''
            #queue push message
            self._addMessage({'message':message, 'file':file})
            return True
        else:
            logging.error('Pushover: unable to add message because not configured')
            return False

    def _sendMessage(self, message):
        #get devices from pushbullet if necessary
        if len(self.pbdevices)==0:
            self.getPushbulletDevices()

        #push message
        for device in self.devices:
            #get device id
            if self.pbdevices.has_key(device):
                if len(message['file'])==0:
                    #send a note
                    resp = self.pushbullet.pushNote(self.pbdevices[device]['id'], self.pushTitle, message['message'])
                    logging.info(resp)
                else:
                    #send a file
                    resp = self.pushbullet.pushFile(self.pbdevices[device]['id'], message['file'])
            else:
                logging.warning('Pushbullet: unable to push notification to device "%s" because not found' % (device))
Exemplo n.º 14
0
time_counter = 0
while True:
    delivery_text = defaultdict(list)
    time_counter += 1
    subreddit = r.get_subreddit(subreddit_names)
    for submission in subreddit.get_hot(limit=30):
        text = submission.selftext.encode('utf-8').strip().replace('\n',' ')
        title = submission.title.encode('utf-8').strip().replace('\n',' ')
        url = submission.url.encode('utf-8').strip().replace('\n',' ')
        post_time = submission.created
        if submission.id not in already_delivered.keys():
            delivery_text[submission.id].append([subreddit_names,title,text,url,post_time])
            already_delivered[submission.id].append(title)
            already_delivered[submission.id].append(text)
            already_delivered[submission.id].append(url)
            already_delivered[submission.id].append(post_time)
    for each_post in delivery_text.keys():
        if 'jokes' in subreddit_names.lower():
            print delivery_text[each_post][0][1],delivery_text[each_post][0][2]
            p.pushNote(devices[0]["iden"],'JOKES',delivery_text[each_post][0][1] + '|' + delivery_text[each_post][0][2])
        else:
            print delivery_text[each_post][0][1],delivery_text[each_post][0][3]
            p.pushNote(devices[0]["iden"],delivery_text[each_post][0][0] + ' : ' + delivery_text[each_post][0][1], 'Read More - ' + delivery_text[each_post][0][3])
        time.sleep(60)
    if time_counter % 10 == 0:
        with open('/home/ubuntu/reddit-delivery/data/'+str(time.time())+'.txt','wb') as tf:
            writer = csv.writer(tf, delimiter = '\t')
            for item in already_delivered.keys():
                writer.writerow(already_delivered[item])
        already_delivered = defaultdict(list)
    time.sleep(1800)