def send_print_notification_pushbullet(_print, event_type=None):
    if not _print.printer.user.has_valid_pushbullet_token():
        return

    pb = Pushbullet(_print.printer.user.pushbullet_access_token)

    title = 'The Spaghetti Detective - Print job notification'
    link = site.build_full_url('/')
    body = get_notification_body(_print, event_type=event_type)
    file_url = None
    try:
        file_url = _print.poster_url
        if not settings.SITE_IS_PUBLIC:
            pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg')
    except:
        pass

    try:
        if file_url:
            pb.push_file(file_url=file_url,
                         file_name="Snapshot.jpg",
                         file_type="image/jpeg",
                         body=body,
                         title=title)
        else:
            pb.push_link(title, link, body)
    except (PushError, PushbulletError) as e:
        LOGGER.error(e)
Esempio n. 2
0
def pbpush(pokename, delta, expire_time, map_link, place_string):
    """ Send a PushBullet notification either privately or to a channel,
    depending on whether or not PB_CHANNEL is set in config.
    """

    try:
        from pushbullet import Pushbullet
        pb = Pushbullet(cnf['PB_API_KEY'])
    except (ImportError, Pushbullet.errors.InvalidKeyError):
        return False

    minutes, seconds = divmod(delta.total_seconds(), 60)
    time_remaining = str(int(minutes)) + 'm' + str(round(seconds)) + 's'

    try:
        title = ('A wild ' + pokename + ' will be in ' + cnf['AREA_NAME'] +
                 ' until ' + expire_time + '!')
    except KeyError:
        title = ('A wild ' + pokename + ' will be around until ' +
                 expire_time + '!')

    body = ('It will be ' + place_string + ' until ' + expire_time + ' (' +
            time_remaining + ')')

    try:
        channel = pb.channels[cnf['PB_CHANNEL']]
        channel.push_link(title, map_link, body)
    except (IndexError, KeyError):
        pb.push_link(title, map_link, body)
    else:
        return True
def send_failure_alert_pushbullet(printer, is_warning, print_paused):
    if not printer.user.has_valid_pushbullet_token():
        return

    pausing_msg = ''
    if print_paused:
        pausing_msg = 'Printer is paused.'
    elif printer.action_on_failure == Printer.PAUSE and is_warning:
        pausing_msg = 'Printer is NOT paused because The Detective is not very sure about it.'

    pb = Pushbullet(printer.user.pushbullet_access_token)
    title = 'The Spaghetti Detective - Your print {} on {} {}.'.format(
        printer.current_print.filename or '',
        printer.name,
        'smells fishy' if is_warning else 'is probably failing')
    link = site.build_full_url('/')
    body = '{}\nGo check it at: {}'.format(pausing_msg, link)

    try:
        file_url = None
        try:
            file_url = printer.pic['img_url']
            if not ipaddress.ip_address(urlparse(file_url).hostname).is_global:
                pb.upload_file(requests.get(file_url).content, 'Detected Failure.jpg')
        except:
            pass

        if file_url:
            pb.push_file(file_url=file_url, file_name="Detected Failure.jpg", file_type="image/jpeg", body=body, title=title)
        else:
            pb.push_link(title, link, body)
    except PushError as e:
        LOGGER.error(e)
    except PushbulletError as e:
        LOGGER.error(e)
def send_print_notification_pushbullet(_print):
    if not _print.printer.user.has_valid_pushbullet_token():
        return

    pb = Pushbullet(_print.printer.user.pushbullet_access_token)

    title = 'The Spaghetti Detective - Print job notification'
    link = site.build_full_url('/')
    body = f"Your print job {_print.filename} {'has been canceled' if _print.is_canceled() else 'is done'} on printer {_print.printer.name}."
    file_url = None
    try:
        file_url = _print.printer.pic['img_url']
        if not ipaddress.ip_address(urlparse(file_url).hostname).is_global:
            pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg')
    except:
        pass

    try:
        if file_url:
            pb.push_file(file_url=file_url,
                         file_name="Snapshot.jpg",
                         file_type="image/jpeg",
                         body=body,
                         title=title)
        else:
            pb.push_link(title, link, body)
    except (PushError, PushbulletError) as e:
        LOGGER.error(e)
Esempio n. 5
0
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')
Esempio n. 6
0
 def sendpbalert(q_pb, pbapikey, pbch):
     pb = Pushbullet(pbapikey)
     pbipcam_channel = pb.get_channel(pbch)
     while True:
         if q_pb.qsize() > 0:
             pbmsg = q_pb.get()
             q_pb.task_done()
             pb.push_link(pbmsg[0], pbmsg[1], channel=pbipcam_channel)
         else:
             time.sleep(.10)
Esempio n. 7
0
 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())
Esempio n. 8
0
def push_link(token, title, url):
    try:
        # test delay code
        # time.sleep(60)
        if token == '':
            return False

        driver_push = Pushbullet(token)
        driver_push.push_link(title, url)
    except:
        print('push Error--')
        return False

    return True
Esempio n. 9
0
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"])
Esempio n. 10
0
def send(cfg, action):
    if (len(cfg["pushbullet_app_token"]) > 0):
        print "Sending to pushbullet..."
        pb = Pushbullet(cfg["pushbullet_app_token"])
        push = pb.push_link(
            cfg["pushover_title"] + " " +
            ("Button" if action == 1 else "Sensor"),
            "http://www.2seven.co.uk/doorbell")

        # Listen for any error messages or other responses
        return push
Esempio n. 11
0
def send_push(new_bikes, new_finds):
    """
    Uses pushbullet to send a notification that new bikes were scraped.

    Args:
        new_bikes (list): List of new_bikes objects
    """
    print "Pushing"
    pb = Pushbullet(PUSHBULLET_KEY)
    push_sent = False
    # Don't do individual pushes if there's a large number of new posts
    if len(new_bikes) <= 10:
        for bike in new_bikes:
            # Only push high priority bikes
            if bike['priority'] == bikeutils.Priority.HighPriority:
                pb.push_link(bike["title"], bike["url"])
                push_sent = True
    if not push_sent:
        pb.push_link("%d bike(s) added to sheet" % len(new_bikes), SHEET_URL)

    # Push any new posts in the ebay finds thread
    if new_finds:
        pb.push_link("%d new posts in the ebay/craigslist finds thread"
                     % new_finds,
                     "https://www.lfgss.com/conversations/127097/newest/")
Esempio n. 12
0
    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'])
Esempio n. 13
0
    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
    def call_pushbullet(
        self,
        access_token: str,
        title: str,
        body: str,
        link: str,
        file_url: str,
    ) -> None:
        pb = Pushbullet(access_token)
        try:
            if not settings.SITE_IS_PUBLIC:
                pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg')
        except:
            pass

        if file_url:
            pb.push_file(file_url=file_url,
                         file_name="Snapshot.jpg",
                         file_type="image/jpeg",
                         body=body,
                         title=title)
        else:
            pb.push_link(title, link, body)
Esempio n. 15
0
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)
Esempio n. 16
0
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)
Esempio n. 17
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
Esempio n. 18
0
    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
Esempio n. 19
0
import settings
from pushbullet import Pushbullet
pb = Pushbullet(settings.pushBulletApiKey)
print(pb.devices)

address = " 25 E 85th St, 10028 New York, NY"
# push = pb.push_address("home", address)

to_buy = ["milk", "bread", "cider"]
# push = pb.push_list("Shopping list", to_buy)

push = pb.push_link("Cool site", "https://github.com")

pushes = pb.get_pushes()

for p in pushes:
    print(p)
Esempio n. 20
0
def handler(event, context):

    # GitHub event, signature and payload
    gh_event = event['headers']['X-GitHub-Event']
    gh_signature = event['headers'].get('X-Hub-Signature')
    gh_body = event['body']
    gh_payload = json.loads(gh_body)

    # If we don't have a signature abort!
    if gh_signature is None:
        response = {
            "statusCode": 403,
            "body": json.dumps({"error": "'X-Hub-Signature' was not sent"})
        }
        return response

    # No secret means we can't authenticate, abort!
    if gh_secret is None:
        response = {
            "statusCode": 500,
            "body":
            json.dumps({"error": "env variable 'github_secret' not set"})
        }
        return response

    # Split our signature and digest method
    digest, gh_signature = gh_signature.split('=')

    # Verify our signature and deny if it fails!
    if not funcs.verify_signature(gh_secret, gh_body, gh_signature, digest):
        response = {
            "statusCode": 403,
            "body": json.dumps({"error": "Signature mismatch"})
        }
        return response

    # Check our event is defined, otherwise we just wont do anything
    if gh_event in config['github']['events']:
        # Get our current event into a more sensible context
        event = config['github']['events'][gh_event]

        # If our event doesn't have 'always' set to true send a notification
        # Otherwise, if the sender of the event is in the ignore list don't notify
        if event['pushbullet'].get('always', False) is True or gh_payload[
                'sender']['login'] not in config['github']['ignore']:
            pb_payload = event['pushbullet']

            title = pb_payload['title'].format(**gh_payload)
            body = pb_payload['body'].format(**gh_payload)
            link = pb_payload['link'].format(**gh_payload)

            # Generate our pushbullet instance
            pb = Pushbullet(pb_key)

            # Shot notification
            notification = pb.push_link(title, link, body)

            response = {
                "statusCode":
                200,
                "body":
                json.dumps({
                    "status": "OK",
                    "notification": "pushed",
                    "pb_id": notification['iden']
                })
            }
            return response
        else:
            response = {
                "statusCode":
                200,
                "body":
                json.dumps({
                    "status": "OK",
                    "notification": "skipped",
                    "reason": "user in ignore list"
                })
            }
            return response
    else:
        response = {
            "statusCode":
            200,
            "body":
            json.dumps({
                "status": "OK",
                "notification": "skipped",
                "reason": "no entry configured for event"
            })
        }
        return response

    response = {
        "statusCode": 200,
        "body": json.dumps({
            "status": "OK",
            "event": gh_event
        })
    }
    return response
Esempio n. 21
0
def new_deals_alert(better_deals):
    pb = Pushbullet(settings.PUSHBULLET_API)
    for deal in better_deals:
        pb.push_link(deal['product-name'] + ' - ' + deal['price'] + ' - ' + deal['retailer'] +
                     ' - ' + deal['title'], deal['link'])
Esempio n. 22
0
def price_change(item, old_price):
    print "Price change! " + item["title"] + " Old price: " + old_price + " New price: " + item["price"] + " URL: " + item["url"]
    if PB_ACTIVE:
        pb = Pushbullet(API_KEY)
        pb.push_link("Price changed from " + str(old_price) + ":- to " + str(item["price"]) + ":- | " + item["title"], item["url"])
Esempio n. 23
0
def pushbullet(bot, trigger):
    if trigger.nick == 'NICK_GOES_HERE' or trigger.nick == 'NICK_GOES_HERE':
        url = trigger.group(2)
        pb = Pushbullet('API_KEY_GOES_HERE')
        pb.push_link(url, url)
 def notify(self, title, text, url=None):
     pb = Pushbullet(self.pushbullet_apikey)
     _ = pb.push_link(text, url)
Esempio n. 25
0
class ServicePushbullet(ServicesMgr):
    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 read_data(self, **kwargs):
        """
            get the data from the service
            as the pushbullet service does not have any date
            in its API linked to the note,
            add the triggered date to the dict data
            thus the service will be triggered when data will be found

            :param kwargs: contain keyword args : trigger_id at least
            :type kwargs: dict

            :rtype: list
        """
        trigger_id = kwargs["trigger_id"]
        data = list()
        cache.set("th_pushbullet_" + str(trigger_id), data)

    def save_data(self, trigger_id, **data):
        """
            let's save the data
            :param trigger_id: trigger ID from which to save data
            :param data: the data to check to be used and save
            :type trigger_id: int
            :type data:  dict
            :return: the status of the save statement
            :rtype: boolean
        """
        kwargs = {}

        title, content = super(ServicePushbullet, self).save_data(trigger_id, data, **kwargs)

        if self.token:
            trigger = Pushbullet.objects.get(trigger_id=trigger_id)
            if trigger.type == "note":
                status = self.pushb.push_note(title=title, body=content)
            elif trigger.type == "link":
                status = self.pushb.push_link(title=title, body=content, url=data.get("link"))
                sentence = str("pushbullet {} created").format(title)
                logger.debug(sentence)
            else:
                # no valid type of pushbullet specified
                logger.critical("no valid type of pushbullet specified")
                status = False
        else:
            logger.critical("no token or link provided for " "trigger ID {} ".format(trigger_id))
            status = False
        return status
Esempio n. 26
0
def pushbullet(bot, trigger):
    if trigger.nick == 'NICK_GOES_HERE' or trigger.nick == 'NICK_GOES_HERE':
        url = trigger.group(2)
        pb = Pushbullet('API_KEY_GOES_HERE')
        pb.push_link(url,url)
Esempio n. 27
0
    def pbpush(self):
        """ Send a PushBullet notification either privately or to a channel,
        depending on whether or not PB_CHANNEL is set in config.
        """

        try:
            pb = Pushbullet(config.PB_API_KEY)
        except Exception:
            self.log.exception('Failed to create a PushBullet object.')
            return False

        description = self.description
        try:
            if self.score < .45:
                description = 'weak'
            elif self.score < .35:
                description = 'bad'
        except TypeError:
            pass

        area = config.AREA_NAME
        try:
            expiry = 'until {}'.format(self.expire_time)
            minutes, seconds = divmod(self.tth, 60)
            remaining = 'for {:.0f}m{:.0f}s'.format(minutes, seconds)
        except AttributeError:
            expiry = 'until between {} and {}'.format(self.min_expire_time,
                                                      self.max_expire_time)
            minutes, seconds = divmod(self.earliest_tth, 60)
            min_remaining = '{:.0f}m{:.0f}s'.format(minutes, seconds)
            minutes, seconds = divmod(self.latest_tth, 60)
            max_remaining = '{:.0f}m{:.0f}s'.format(minutes, seconds)
            remaining = 'for between {} and {}'.format(min_remaining,
                                                       max_remaining)

        title = 'A {} {} will be in {} {}!'.format(description, self.name,
                                                   area, expiry)

        body = 'It will be {} {}.\n\n'.format(self.place, remaining)
        try:
            body += ('Attack: {}\n'
                     'Defense: {}\n'
                     'Stamina: {}\n'
                     'Move 1: {}\n'
                     'Move 2: {}\n\n').format(self.attack, self.defense,
                                              self.stamina, self.move1,
                                              self.move2)
        except AttributeError:
            pass

        try:
            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)
        except Exception:
            self.log.exception(
                'Failed to send a PushBullet notification about {}.',
                self.name)
            return False
        else:
            self.log.info('Sent a PushBullet notification about {}.',
                          self.name)
            return True
Esempio n. 28
0
servers = []
s = speedtest.Speedtest()
s.get_servers(servers)
s.get_best_server()
s.download()
s.upload()

share_url = s.results.share()[:-4]

if s.results.download < download_min or s.results.upload < upload_min or s.results.ping > ping_max or test_run:
    pb = Pushbullet(api_key=access_token)
    push = pb.push_link(
        "Internet Speed Warning", share_url,
        "date:\t{:%Y-%m-%d}\n".format(datetime.datetime.now()) +
        "time:\t{:%H-%M}\n".format(datetime.datetime.now()) +
        "down:\t%d Mb/s\n" % (s.results.download / 1000000) +
        "up:\t\t%d Mb/s\n" % (s.results.upload / 1000000) +
        "ping:\t%d ms\n" % s.results.ping)

results_dict = s.results.dict()

with open('stats.csv', 'a') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([
        results_dict['timestamp'], results_dict['download'],
        results_dict['upload'], results_dict['ping'],
        results_dict['bytes_sent'], results_dict['bytes_received'],
        results_dict['share'][:-4], results_dict['server']['url'],
        results_dict['server']['lat'], results_dict['server']['lon'],
        results_dict['server']['name'], results_dict['server']['country'],
Esempio n. 29
0
def pushMessage(title, url):
    pb = Pushbullet(pbAPIKey)  #, proxy=proxyDict)
    push = pb.push_link(title, url)
Esempio n. 30
0
        return
    elif wanted_pokemon != None and not pokename in wanted_pokemon:
        return
    elif wanted_pokemon == None and unwanted_pokemon != None and pokename in unwanted_pokemon:
        return
    # notify
    print "[+] Notifier found pokemon:", pokename

    #http://maps.google.com/maps/place/<place_lat>,<place_long>/@<map_center_lat>,<map_center_long>,<zoom_level>z
    latLon = '{},{}'.format(repr(pokemon["lat"]), repr(pokemon["lng"]))
    google_maps_link = 'http://maps.google.com/maps/place/{}/@{},{}z'.format(latLon, latLon, 20)

<<<<<<< HEAD
    notification_text = "Pokemon Found " + _str(pokemon["name"]) + "!"
    disappear_time = str(datetime.fromtimestamp(pokemon["disappear_time"]).strftime("%I:%M%p").lstrip('0'))+")"
    location_text = "Location : " + google_maps_link + ". " + _str(pokemon["name"]) + " Available till " + disappear_time + "."
    push = my_channel.push_link( _str(pokemon["name"] + " found, Available until " +disappear_time ) , google_maps_link )
    #push = pushbullet_client.push_link(notification_text, google_maps_link, body=location_text)
=======
    notification_text = "Pokemon Finder found " + _str(pokemon["name"]) + "!"
    disappear_time = str(datetime.fromtimestamp(pokemon["disappear_time"]).strftime("%I:%M%p").lstrip('0'))+")"
    location_text = "Locate on Google Maps : " + google_maps_link + ". " + _str(pokemon["name"]) + " will be available until " + disappear_time + "."

    push = pushbullet_client.push_link(notification_text, google_maps_link, body=location_text)
    push = my_channel.push_link( _str(pokemon["name"] + " found, Available until " +disappear_time ) , google_maps_link )
>>>>>>> origin/master



init()
Esempio n. 31
0
def handler(event, context):

    # Discourse event, signature and payload
    discourse_event     = event['headers']['X-Discourse-Event']
    discourse_signature = event['headers'].get('X-Discourse-Event-Signature')
    discourse_body      = event['body']
    discourse_payload   = json.loads(discourse_body)

    # If we don't have a signature abort!
    if discourse_signature is None:
        response = {
            "statusCode": 403,
            "body": json.dumps({"error": "'X-Discourse-Event-Signature' was not sent"})
        }
        return response

    # No secret means we can't authenticate, abort!
    if discourse_secret is None:
        response = {
            "statusCode": 500,
            "body": json.dumps({"error": "env variable 'discourse_secret' not set"})
        }
        return response

    # Split our signature and digest method
    digest, discourse_signature = discourse_signature.split('=')

    # Verify our signature and deny if it fails!
    if not funcs.verify_signature(discourse_secret, discourse_body, discourse_signature, digest):
        response = {
            "statusCode": 403,
            "body": json.dumps({"error": "Signature mismatch"})
        }
        return response

    # Check our event is defined, otherwise we just wont do anything
    if discourse_event in config['discourse']['events']:
        # Get our current event into a more sensible context
        event = config['discourse']['events'][discourse_event]

        pb_payload = event['pushbullet']

        title = pb_payload['title'].format(**discourse_payload)
        body  = pb_payload['body'].format(**discourse_payload)
        link  = pb_payload['link'].format(**discourse_payload)

        # Generate our pushbullet instance
        pb = Pushbullet(pb_key)

        # Shot notification
        notification = pb.push_link(title, link, body)

        response = {
            "statusCode": 200,
            "body": json.dumps({"status": "OK", "notification": "pushed", "pb_id": notification['iden']})
        }
        return response
    else:
        response = {
            "statusCode": 200,
            "body": json.dumps({"status": "OK", "notification": "skipped", "reason": "no entry configured for event"})
        }
        return response
	def check_old(self):
		if self.url in old_posts.read().split(","):
			return False
		else:
			return True

def get_catalog():
	articles = []
	# Gets the all the articles as a link and puts them in a list
	for tbody in catalog.find_all("tbody"):
		if tbody.get("class")[0] == "body":
			for tr in tbody.find_all("tr"):
				# The index thing is for that the url has some uneccesery stuff in it at the end
				articles.append("http://www.sweclockers.com%s" % tr.a.get("href")[:len(tr.a.get("href"))-13])
			break

	else:
		quit()

	return articles

with open("old_posts.txt", "r+") as old_posts:
	# Forever loop that checks the keywords and if true sends a pushbullet
	for article_url in get_catalog():
		article = sweclockers(article_url)
		print(article.url)
		if article.check_keyword() and article.check_old():
			print("Pushing %s" % article.headline())
			push = pb.push_link(article.headline(), article.url)
			article.make_old()
Esempio n. 33
0
class ServicePushbullet(ServicesMgr):
    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 read_data(self, **kwargs):
        """
            get the data from the service
            as the pushbullet service does not have any date
            in its API linked to the note,
            add the triggered date to the dict data
            thus the service will be triggered when data will be found

            :param kwargs: contain keyword args : trigger_id at least
            :type kwargs: dict

            :rtype: list
        """
        trigger_id = kwargs['trigger_id']
        data = list()
        cache.set('th_pushbullet_' + str(trigger_id), data)

    def save_data(self, trigger_id, **data):
        """
            let's save the data
            :param trigger_id: trigger ID from which to save data
            :param data: the data to check to be used and save
            :type trigger_id: int
            :type data:  dict
            :return: the status of the save statement
            :rtype: boolean
        """
        kwargs = {}

        title, content = super(ServicePushbullet,
                               self).save_data(trigger_id, data, **kwargs)

        if self.token:
            trigger = Pushbullet.objects.get(trigger_id=trigger_id)
            if trigger.type == 'note':
                status = self.pushb.push_note(title=title, body=content)
            elif trigger.type == 'link':
                status = self.pushb.push_link(title=title,
                                              body=content,
                                              url=data.get('link'))
                sentence = str('pushbullet {} created').format(title)
                logger.debug(sentence)
            else:
                # no valid type of pushbullet specified
                logger.critical("no valid type of pushbullet specified")
                status = False
        else:
            logger.critical("no token or link provided for "
                            "trigger ID {} ".format(trigger_id))
            status = False
        return status
Esempio n. 34
0
		else:
			album_formats = "FLAC, MP3"
		# Album Tracks
		album_tracks = curr_album.find("span", "circle").text
		# Album Size
		album_size = curr_album.find("span","col-small text-right").text
		# Album Date
		album_date = curr_album.find("span","col-medium").text
		
		# Creating the album and adding it to the list
		album = Album(artist_name, album_name, album_link, album_year, album_genres, album_formats, album_tracks, album_size, album_date)
		albums.append(album)
		i += 1
	return albums
	
old_albums = []
new_albums = []

config = configparser.ConfigParser()
config.read('settings.ini')
# Using Pushbullet
pb = Pushbullet(config['settings']['PUSHBULLET_API_KEY'])
while 1:
	albums = getAlbums()
	if old_albums:
		i = 0
		while old_albums[0].album_name != albums[i].album_name:
			push = pb.push_link(albums[i].artist_name + " - " + albums[i].album_name + " - " + albums[i].album_genres + " (" + albums[i].album_year + ") " + albums[i].album_formats, "http://mp3boo.cc" + albums[i].album_link)
			i += 1
	old_albums = albums
	time.sleep(float(config['settings']['TIMEOUT_DURATION']))
Esempio n. 35
0
def push_link(Title, Link):
    global apiKey
    pb = Pushbullet(apiKey)
    push = pb.push_link(Title, Link)
Esempio n. 36
0
def handler(event, context):

    # MailerLite signature and payload
    mailerlite_signature = event['headers'].get('X-MailerLite-Signature')
    mailerlite_body = event['body']
    mailerlite_payload = json.loads(mailerlite_body)

    # If we don't have a signature abort!
    if mailerlite_signature is None:
        response = {
            "statusCode": 403,
            "body":
            json.dumps({"error": "'X-MailerLite-Signature' was not sent"})
        }
        return response

    # No secret means we can't authenticate, abort!
    if mailerlite_secret is None:
        response = {
            "statusCode":
            500,
            "body":
            json.dumps({"error": "env variable 'mailerlite_secret' not set"})
        }
        return response

    # Split our signature and digest method
    digest, mailerlite_signature = mailerlite_signature.split('=')

    # Verify our signature and deny if it fails!
    if not funcs.verify_signature(mailerlite_secret, mailerlite_body,
                                  mailerlite_signature, digest):
        response = {
            "statusCode": 403,
            "body": json.dumps({"error": "Signature mismatch"})
        }
        return response

    # MailerLite can bulk send webhooks, so wrap it in a for
    for event in mailerlite_body['events']:
        mailerlite_event = event['type']
        # Check our event is defined, otherwise we just wont do anything
        if mailerlite_event in config['mailerlite']['events']:

            pb_payload = config['mailerlite']['events'][mailerlite_event][
                'pushbullet']

            title = pb_payload['title'].format(**mailerlite_payload)
            body = pb_payload['body'].format(**mailerlite_payload)
            link = pb_payload['link'].format(**mailerlite_payload)

            # Generate our pushbullet instance
            pb = Pushbullet(pb_key)

            # Shot notification
            notification = pb.push_link(title, link, body)

            response = {
                "statusCode":
                200,
                "body":
                json.dumps({
                    "status": "OK",
                    "notification": "pushed",
                    "pb_id": notification['iden']
                })
            }
            return response
        else:
            resposne = {
                "statusCode":
                200,
                "body":
                json.dumps({
                    "status": "OK",
                    "notification": "skipped",
                    "reason": "no entry configured for event"
                })
            }
            return response
Esempio n. 37
0
    def pbpush(self):
        """ Send a PushBullet notification either privately or to a channel,
        depending on whether or not PB_CHANNEL is set in config.
        """

        try:
            pb = Pushbullet(config.PB_API_KEY)
        except Exception:
            self.logger.exception('Failed to create a PushBullet object.')
            return False

        description = self.description
        try:
            if self.score < .45:
                description = 'weak'
            elif self.score < .35:
                description = 'bad'
        except TypeError:
            pass

        area = config.AREA_NAME
        if self.delta:
            expiry = 'until {}'.format(self.expire_time)

            minutes, seconds = divmod(self.delta.total_seconds(), 60)
            remaining = 'for {m}m{s:.0f}s'.format(m=int(minutes), s=seconds)
        else:
            expiry = 'until between {t1} and {t2}'.format(
                t1=self.min_expire_time, t2=self.max_expire_time)

            minutes, seconds = divmod(self.min_delta.total_seconds(), 60)
            min_remaining = '{m}m{s:.0f}s'.format(m=int(minutes), s=seconds)
            minutes, seconds = divmod(self.max_delta.total_seconds(), 60)
            max_remaining = '{m}m{s:.0f}s'.format(m=int(minutes), s=seconds)

            remaining = 'for between {r1} and {r2}'.format(r1=min_remaining,
                                                           r2=max_remaining)

        title = ('A {d} {n} will be in {a} {e}!').format(d=description,
                                                         n=self.name,
                                                         a=area,
                                                         e=expiry)

        body = ('It will be {p} {r}.\n\n'
                'Attack: {iv[0]}\n'
                'Defense: {iv[1]}\n'
                'Stamina: {iv[2]}\n'
                'Move 1: {m[0]}\n'
                'Move 2: {m[1]}\n\n').format(p=self.place,
                                             r=remaining,
                                             iv=self.iv,
                                             m=self.moves)

        try:
            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)
        except Exception:
            self.logger.exception(
                'Failed to send a PushBullet notification about {}.'.format(
                    self.name))
            return False
        else:
            self.logger.info('Sent a PushBullet notification about {}.'.format(
                self.name))
            return True
Esempio n. 38
0
    c_tmp = con_tmp.cursor()
    c_tmp.execute("create table tmp (url text, episode text, manga_name text);")
    for row in c.execute('select url,name from WatchList;'):
        try:
            print row
            request = urllib2.Request(row[0],None,headers)
            response = urllib2.urlopen(request)
            page = response.read()
            episode = search_episode(page)
            for e in episode:
                #save to tmp table
                c_tmp.execute("insert into tmp values(?,?,?)",(e[0].decode('utf8'),e[1].decode('utf8'), row[1]))
        except URLError as e:
            print e.reason
    #check if pushed
    c_tmp.execute("select * from tmp")
    while True:
        episode_tmp = c_tmp.fetchone()
        if episode_tmp != None:
            c.execute("select url from Episode where url=? limit 1;",(episode_tmp[0],))
            if c.fetchone() == None:
                #new episode spotted
                full_url = "m.seemh.com"+episode_tmp[0]
                if not args.update: 
                    push = pb.push_link("New episode from m.seemh.com!",full_url)
                c.execute("insert into episode values (?,?)",(episode_tmp[0],episode_tmp[1]))
        else:
            break
    con.commit()
    con.close()
Esempio n. 39
0
import praw
from pushbullet import Pushbullet
import time

token = 'o.5UJF58DGMRWCkEctD0NFw4mz6AaWTFzb'

pb = Pushbullet(token)

reddit = praw.Reddit(client_id='sy5zBbkC8uUcHQ',
                     client_secret='xDAe23dqN5ZhJZlYjg82WBgSFfw',
                     user_agent='PRAW autobot for notifications')

subreddit = reddit.subreddit('lego_raffles')

last_check = time.time()

print(subreddit.display_name)

while True:
    for post in subreddit.new():
        if post.created_utc > last_check - 60 * 10:
            pb.push_link(post.title, post.permalink)
            print('Pushing', post.title)
        else:
            continue

    last_check = time.time()
    print('Passed check')
    time.sleep(60 * 10)
Esempio n. 40
0
class ServicePushbullet(ServicesMgr):
    """
        Service Pushbullet
    """
    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 read_data(self, **kwargs):
        """
            get the data from the service
            as the pushbullet service does not have any date
            in its API linked to the note,
            add the triggered date to the dict data
            thus the service will be triggered when data will be found

            :param kwargs: contain keyword args : trigger_id at least
            :type kwargs: dict

            :rtype: list
        """
        trigger_id = kwargs.get('trigger_id')
        trigger = Pushbullet.objects.get(trigger_id=trigger_id)
        date_triggered = kwargs.get('date_triggered')
        data = list()
        pushes = self.pushb.get_pushes()
        for p in pushes:
            title = 'From Pushbullet'
            created = arrow.get(p.get('created'))
            if created > date_triggered and p.get('type') == trigger.type and\
                (p.get('sender_email') == p.get('receiver_email') or
                 p.get('sender_email') is None):
                title = title + ' Channel' if p.get('channel_iden') and \
                                              p.get('title') is None else title
                # if sender_email and receiver_email are the same ;
                # that means that "I" made a note or something
                # if sender_email is None, then "an API" does the post

                body = p.get('body')
                data.append({'title': title, 'content': body})

        cache.set('th_pushbullet_' + str(trigger_id), data)
        return data

    def save_data(self, trigger_id, **data):
        """
            let's save the data
            :param trigger_id: trigger ID from which to save data
            :param data: the data to check to be used and save
            :type trigger_id: int
            :type data:  dict
            :return: the status of the save statement
            :rtype: boolean
        """
        title, content = super(ServicePushbullet, self).save_data(trigger_id,
                                                                  **data)

        if self.token:
            trigger = Pushbullet.objects.get(trigger_id=trigger_id)
            if trigger.type == 'note':
                status = self.pushb.push_note(title=title, body=content)
            elif trigger.type == 'link':
                status = self.pushb.push_link(title=title, body=content,
                                              url=data.get('link'))
                sentence = str('pushbullet {} created').format(title)
                logger.debug(sentence)
            else:
                # no valid type of pushbullet specified
                msg = "no valid type of pushbullet specified"
                logger.critical(msg)
                update_result(trigger_id, msg=msg)
                status = False
        else:
            msg = "no token or link provided for trigger " \
                  "ID {} ".format(trigger_id)
            logger.critical(msg)
            update_result(trigger_id, msg=msg)
            status = False
        return status
with open(fpath, 'rb') as f:
    sona = pickle.load(f)

# load previous session and studies
key = sona.session['p_sessionToken']
studies = sona.studies

# get new session and studies, return new studies in [name, id] list
newStudies = [[item['exp_name'], item['experiment_id']] for item in sona.get_new_studies()]

if newStudies:
    # create pushbullet object and get channel
    pb = Pushbullet(api_key)
    channel = pb.get_channel(ch_tag)

    # create full url path
    url = sona.domain + idpath
    
    for item in newStudies:
        name = item[0] + ' ' + get_free_timeslot_string(item[1])
        if sona.get_study_eligibility(item[1]): # if eligible
            # private push
            push = pb.push_link(name, url + str(item[1]))

        # channel push
        push = channel.push_link(name, url + str(item[1]))
    
# save pickle if session renewed or studies changed
if key != sona.session['p_sessionToken'] or studies != sona.studies:
    save_pickle()
Esempio n. 42
0
class ServicePushbullet(ServicesMgr):
    """
        Service Pushbullet
    """
    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_KEY['client_id']
        self.consumer_secret = settings.TH_PUSHBULLET_KEY['client_secret']
        self.scope = 'everything'
        self.service = 'ServicePushbullet'
        self.oauth = 'oauth2'
        if token:
            self.token = token
            self.pushb = Pushb(token)

    def read_data(self, **kwargs):
        """
            get the data from the service
            as the pushbullet service does not have any date
            in its API linked to the note,
            add the triggered date to the dict data
            thus the service will be triggered when data will be found

            :param kwargs: contain keyword args : trigger_id at least
            :type kwargs: dict

            :rtype: list
        """
        trigger_id = kwargs.get('trigger_id')
        trigger = Pushbullet.objects.get(trigger_id=trigger_id)
        date_triggered = kwargs.get('date_triggered')
        data = list()
        pushes = self.pushb.get_pushes()
        for p in pushes:
            title = 'From Pushbullet'
            created = arrow.get(p.get('created'))
            if created > date_triggered and p.get('type') == trigger.type and\
               (p.get('sender_email') == p.get('receiver_email') or p.get('sender_email') is None):
                title = title + ' Channel' if p.get('channel_iden') and p.get('title') is None else title
                # if sender_email and receiver_email are the same ;
                # that means that "I" made a note or something
                # if sender_email is None, then "an API" does the post

                body = p.get('body')
                data.append({'title': title, 'content': body})
                # digester
                self.send_digest_event(trigger_id, title, '')

        cache.set('th_pushbullet_' + str(trigger_id), data)
        return data

    def save_data(self, trigger_id, **data):
        """
            let's save the data
            :param trigger_id: trigger ID from which to save data
            :param data: the data to check to be used and save
            :type trigger_id: int
            :type data:  dict
            :return: the status of the save statement
            :rtype: boolean
        """
        title, content = super(ServicePushbullet, self).save_data(trigger_id, **data)
        if self.token:
            trigger = Pushbullet.objects.get(trigger_id=trigger_id)
            if trigger.type == 'note':
                status = self.pushb.push_note(title=title, body=content)
            elif trigger.type == 'link':
                status = self.pushb.push_link(title=title, body=content, url=data.get('link'))
                sentence = str('pushbullet {} created').format(title)
                logger.debug(sentence)
            else:
                # no valid type of pushbullet specified
                msg = "no valid type of pushbullet specified"
                logger.critical(msg)
                update_result(trigger_id, msg=msg, status=False)
                status = False
        else:
            msg = "no token or link provided for trigger ID {} ".format(trigger_id)
            logger.critical(msg)
            update_result(trigger_id, msg=msg, status=False)
            status = False
        return status
Esempio n. 43
0
def push_bullet_notify(message, link):
    pb = Pushbullet(config.get("notification", "pushbullet_token"))
    try:
        pb.push_link(message, link)
    except Exception as ex:
        print ex.message
 def notify(self, title, text, url=None):
     pb = Pushbullet(self.pushbullet_apikey)
     push = pb.push_link(text, url)
Esempio n. 45
0
def send_notification(link):
    pb = Pushbullet(os.environ['PUSHBULLET_KEY'])
    push = pb.push_link("Todays News", link)