Example #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
    def connect(self):
        apiKey = "o.2uIo9r0MKCCFX8Mv3uMhp4xOXE9vgBrC"
        p = PushBullet(apiKey)
        # Get a list of devices
        devices = p.getDevices()

        msg, ct, ch = self.blueMsg()

        while True:
            botList = self.detect()
            print(botList)
            if devices[0].get("nickname") in botList:

                print("Found device with names: ", botList)
                p.pushNote(
                    devices[0]["iden"],
                    'Raspberry-Pi-Notification',
                    'Current Temperature is :' +
                    str(ct) +
                    'Degrees' +
                    '\nCurrentHumid :' +
                    str(ch) +
                    '%' +
                    '\n' +
                    msg)
                break
Example #3
0
def compare_collections():
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    db = myclient["Takealot_DB"]
    collectionA = "graphics_cards_day_{}".format(initial_day)
    collectionB = "graphics_cards_day_{}".format(next_day)
    print(collectionA, collectionB)
    apiKey = "GET YOUR OWN API KEY"
    p = PushBullet(apiKey)
    # Get a list of devices
    devices = p.getDevices()

    x = get_var_value()
    print("THIS IS THE VARSTORE VALUE: {}".format(x))
    y = x - 1
    print("THIS IS THE VARSTORE VALUE MINUS 1: {}".format(y))
    if x < 2:
        print("Nothing to compare. Program must run at least twice.")
    else:
        for item in db.get_collection(collectionA).find():
            item_name = item['item_name']
            item2 = db.get_collection(collectionB).find_one(
                {'item_name': item_name})

            result = "\n Price change is {} for item {} with original price being {} in collection A,\n and item {} with original price being {} in collection B.\n The difference is {}".format(
                item['item_price'] > item2['item_price'], item['item_name'],
                item['item_price'], item2['item_name'], item2['item_price'],
                item['item_price'] - item2['item_price'])

            p.pushNote(devices[0]["iden"], 'Scraping completed', result)
Example #4
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)

    recipient_type = "device_iden"
    try:
        apikey, device_id = item.addrs
    except:
        try:
            apikey, device_id, recipient_type = 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, recipient_type)
        srv.logging.debug("Successfully sent pushbullet notification")
    except Exception as e:
        srv.logging.warning("Cannot notify pushbullet: %s" % e)
        return False

    return True
Example #5
0
def recog():
    visitor=0
    known_encoding = face_recognition.face_encodings(known_image)[0]
    print('known image encodings done')
    previous_state = False
    current_state = False
    while True:
            
        previous_state=current_state
        current_state=GPIO.input(sensor)
        if(current_state != previous_state):
            if(current_state): new_state="HIGH"
            else: new_state="LOW"
            print("GPIO pin %s is %s" % (sensor,new_state))
            if(current_state):
                print("A photo will be taken in 3 seconds")
                time.sleep(3)
                with picamera.PiCamera() as camera:
                    camera.resolution = (340, 220)
                    time.sleep(2)
                    camera.capture('unknown.jpg')
                unknown_image = face_recognition.load_image_file("/home/pi/Desktop/unknown.jpg")
                face_locations = face_recognition.face_locations(unknown_image)
                if(len(face_locations) == 0):
                    print("no face detected")
                    os.remove('unknown.jpg')
                    continue
                    
                unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
                print("encodings calculated")
                results = face_recognition.compare_faces([known_encoding], unknown_encoding)
                print(results)
                if results == [True]:
                    GPIO.setup(14, GPIO.OUT)
                    print("person recognised,frank")
                    p = PushBullet("o.a441em4dWH3fzGm1mcURidwfuJ1gG4Jn") #secret key of pushbullet API
                    devices = p.getDevices()
                    p.pushNote(devices[0]["iden"], 'Frank is at the door', 'open the door')
                    os.remove("unknown.jpg")
                    print("message sent")
                    GPIO.cleanup()
                    break
                else:
                    while(os.path.exists("/home/pi/Desktop/known/"+str(visitor)+".jpg")):
                        visitor=visitor+1
                    os.rename("/home/pi/Desktop/unknown.jpg","/home/pi/Desktop/"+str(visitor)+".jpg")
                    shutil.move("/home/pi/Desktop/"+str(visitor)+".jpg","/home/pi/Desktop/known")
                    print("unknown person")
                    picname = str(visitor) + ".jpg"
                    visitor=visitor+1
                        #cv2.imwrite(picname,frame) 
                    p = PushBullet("o.a441em4dWH3fzGm1mcURidwfuJ1gG4Jn") #secret key of pushbullet API
                    devices = p.getDevices()
                    p.pushFile(devices[0]["iden"], picname, "unknown person", open("/home/pi/Desktop/known/"+picname, "rb"))

                    print("Sending email")
                    attach=picname #attachments to send with email
                    smail.send_mail(attach)
                    print("email sent")           
                    break
Example #6
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
Example #7
0
def pushBullet(title, message):
    try:
        from pushbullet.pushbullet import PushBullet
        apiKey = "o.mKznlsIJB18uq6qArGrl2AOPU2KbISsR"
        p = PushBullet(apiKey)
        devices = p.getDevices()
        p.pushNote(devices[0]["iden"], title, message)
    except Exception, e:
        logger.exception(e)
Example #8
0
    def sendNotif(self, header, body):
        if self.apiKey == "":
            fichier = open("api.txt", "r")
            self.apiKey = fichier.read()[:-1]  # attention retour a la ligne
            fichier.close()

        p = PushBullet(self.apiKey)
        devices = p.getDevices()
        for i in range(len(devices)):
            p.pushNote(devices[i]["iden"], header, body)
Example #9
0
def sendNotif():
    pb = PushBullet("o.sqTG7BlAEOoQDpccJ2n3nFwZ4BRy2637")

    devices = pb.getDevices()

    title = "Recolteur d'eau"
    text = "Le reservoir est vide!"

    for device in devices:
        if device['pushable']:
            note = pb.pushNote(device["iden"], title, text)
Example #10
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"]))
Example #11
0
 def sendNotify(self, msg):
     # pushBullet notify call for registerd devices
     apiKey = "o.2uIo9r0MKCCFX8Mv3uMhp4xOXE9vgBrC"
     p = PushBullet(apiKey)
     devices = p.getDevices()
     p.pushNote(devices[0]["iden"], 'Raspberry-Pi-Notification', msg)
Example #12
0
def notifyuser():
    p = PushBullet(apiKey)
    devices = p.getDevices()
    print(devices)
    p.pushNote(devices[0]["iden"], 'Smart Home Manager', 'Intruder Detected')
Example #13
0
def notify_neighbor(name):
    p = PushBullet(apiKey)
    devices = p.getDevices()
    print(devices)
    response="Intruder Detected in {}'s Home. Please check.".format(name)
    p.pushNote(devices[0]["iden"], 'Smart Home Manager', response)
Example #14
0
def notifyuser_place(msg):
    p = PushBullet(apiKey)
    devices = p.getDevices()
    print(devices)
    p.pushNote(devices[0]["iden"], 'Smart Home Manager', 'Intruder Detected in {}'.format(msg))
Example #15
0
from pushbullet.pushbullet import PushBullet

api_key = ''

pb = PushBullet(api_key)


# Get a list of devices
devices = pb.getDevices()
print(devices)

# test values
albumURI = "1231232141sdasd"
deviceID = "123214123212"

# Send a note
note_title = 'Played ' + albumURI
note_body = 'Song played on ' + deviceID
pb.pushNote(devices[1]["iden"], note_title, note_body)
                                "available_capacity_dose1"] > 0:
                        n, v = h["name"] + " " + str(
                            h["pincode"]), s["vaccine"]
                        if v in availability_data:
                            if n not in availability_data[v]:
                                availability_data[v].append(n)
                        else:
                            availability_data[v] = [n]


def convert_to_string(d):
    res = ""
    for key in d:
        s = ", ".join(d[key])
        res = res + key + " available at " + s + "\n"
    return res


now = datetime.datetime.now()

if len(availability_data) > 0:
    s = convert_to_string(availability_data)
    for d in push_to_devices:
        p.pushNote(d, "VACCINE MIL GYAAAAA", s)
        print(str(now) + " Found vaccines ")
        print(s)
else:
    print(str(now) + " No vaccines available")
    # for d in push_to_devices:
    # p.pushNote(d, "No vaccine :(((", "kismat kharab hai boss")
Example #17
0
for name in glob.glob('csv/*.csv'):
    with open(name, 'rb') as f:
        next(f)  #skip header line
        reader = csv.reader(f)
        for row in reader:
            agent = row[0]
            portalName = row[1]
            portalLink = row[4]
            #convert to datetime object for day calculation
            portalBorn = dt.datetime.strptime(row[5], '%m/%d/%y').date()
            #subtract days and remove time method
            daysOld = (date - portalBorn).days

            #check to see if agent already has 150
            if daysOld >= 150:
                push = pb.pushNote(phone, agent,
                                   "Already has Onyx Guardian" + '\n' + meh)
                break
            #check to see if date is over 140
            elif daysOld >= 140 <= 149:
                #convert int to string for push
                stringDate = str(daysOld)
                push = pb.pushNote(
                    phone, agent + " | " + portalName, portalLink + '\n' +
                    "Onyx Alert! | Days Old: " + stringDate + " " + sweat)
            #check if portal is about to hit platinum
            elif daysOld >= 80 <= 89:
                stringDate = str(daysOld)
                push = pb.pushNote(
                    phone, agent + " | " + portalName, portalLink + '\n' +
                    "Plat Alert! | Days Old: " + stringDate + " " + fear)
Example #18
0
rate_list_temp = []

for i in rate_list:
	if len(i) < 7:
		rate_list_temp.append(i)

if len(rate_list_temp) > 0:
	printrates2 = "\n".join(rate_list_temp)
else:
	printrates2 = "Need New Line"

print(printrates2)

apiKey = "API_KEY"
p = PushBullet(apiKey)
p.pushNote('EMAIL', 'Simsbury Bank 30 Year Rate', printrates2, recipient_type='email')

# import sys
# print(sys.executable)

### OLD DYNAMIC CODE
# if len(rate96) < 7:
# 	if len(rate149) < 7:
# 		printrates = str(rate96 + "\n" + rate149)
# 	else:
# 		printrates = str(rate96)
# else:
# 	if len(rate149) < 7:
# 		printrates = str(rate149)
# 	else:
# 		printrates = "Need New Line"
Example #19
0
from pushbullet.pushbullet import PushBullet

apyKey = "APYKEY"

p = PushBullet(apyKey) 

fileHandle = open ( "resultados.txt", "r")
lineList = fileHandle.readlines()
fileHandle.close()

p.pushNote("*****@*****.**", lineList[-1], "", recipient_type='email')

print lineList[-1]
Example #20
0
# set up a web scraping session
sess = dryscrape.Session(base_url = 'https://www.royalmail.com')

# we don't need images
sess.set_attribute('auto_load_images', False)

while True:
    # visit the tracking page and lookup the tracking number
    sess.visit('/track-your-item')
    q = sess.at_xpath('//*[@name="tracking_number"]')
    q.set(trackingNumber)
    q.form().submit()

    # extract the tracking status
    try:
        x = sess.at_xpath('//*[@class="status result-row padding20lr first"]')
        status = x.text()
    except AttributeError:
        x = sess.at_xpath('//*[@class="status result-row padding20lr first last"]')
        status = x.text()
    
    if (status != prevStatus):
        # push the status to PushBullet
        # if you would like to push to more than one device then just copy the line below and change the device ID
        p.pushNote(deviceId, 'RoyalMail Tracking', status)
        
        prevStatus = status
    
    # wait for 'refreshRate' minutes before checking again
    time.sleep(refreshRate * 60)
for INP_DATE in date_str:
    URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict?district_id={}&date={}".format(
        DIST_ID, INP_DATE)
    response = requests.get(URL, headers=browser_header)
    if (response.ok) and ('centers' in json.loads(response.text)):
        resp_json = json.loads(response.text)['centers']
        if (resp_json is not None):
            for mydistrictcenters in resp_json:
                if (((mydistrictcenters['pincode'] == 370205)
                     or (mydistrictcenters['pincode'] == 370201))):
                    for availablesessions in mydistrictcenters['sessions']:
                        logger.info(" : Records Fetched")
                        if ((availablesessions['min_age_limit'] == 18) and
                            (availablesessions['available_capacity'] == 0)):
                            currentavailability = False
                        else:
                            currentavailability = True
        else:
            logger.info(" : No rows in the data Extracted from the API")

if (shelf['previousavailability'] != currentavailability):
    shelf['previousavailability'] = currentavailability
    if (currentavailability == True):
        text = 'Vaccine Available'
        body = 'GO GO GO!!!'
    else:
        text = 'Vaccine Unavailable'
        body = 'Go back to sleep'
    p.pushNote(p.getDevices()[0]["iden"], text, body)
shelf.close()
Example #22
0
            k=k+1
            continue
        else:
            remaining=value
            pricelist.append(remaining*float(gdaxdata['bids'][k][0]))
            weightlist.append(remaining)
            #print("remaining value", value-remaining)
            #print(pricelist)
            #print(weightlist)
            break

    gdaxavg=sum(pricelist)/sum(weightlist)

    print(sum(weightlist), 'of bitcoin will be sold for avg price of', gdaxavg)

    arbitrage=gdaxavg-bitmavg
    #print(arbitrage)

    string1=str(arbitrage)

    #get api key from env
    
    apiKey = API_KEY
    p = PushBullet(apiKey)
    # Get a list of devices
    devices = p.getDevices()
    devices

    p.pushNote(devices[0]["iden"], 'Buy at bitmarket/sell at gdax: ' + string1, "")
else:
    pass
Example #23
0
def sendPushBulletEmail(apiKey, message, email):
    p = PushBullet(apiKey)
    p.pushNote(email, 'EMERGENCY', message, recipient_type='email')
Example #24
0
def sendPushBulletNotification(apiKey, message):
    p = PushBullet(apiKey)
    devices = p.getDevices()
    p.pushNote(devices[0]["iden"], 'EMERGENCY', message)
Example #25
0
    ecou = timer + delai
    sw_state = switch.get_state()
    #print "boucle1"
    while sw_state == 1 :
	#print "boucle2"
	sleep(0.5)
	sw_state = switch.get_state()
        delta = encoder.get_delta()
        timer = time.time()
        if delta!=0:
            count = delta + count
            ecou = timer + delai
            envoi = 0
            #print "rotate %d" % count

        if envoi == 0 :
            if timer > ecou :
                #print "temps ecoule"
                #print "os.system(curl -H "Content-Type: application/json" --request POST --data '{"command": "pause"}' --header 'X-ApiKey: apikey' --verbose http://127.0.0.1:5000/api/job)"
                #os.system("curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"pause\"}\' --header \'X-ApiKey: apikey\' --verbose http://127.0.0.1:5000/api/job")
		p.pushNote(devices[0]["iden"], 'Probleme de filament', ' ')
                print "curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"pause\"}\' --header \'X-Api-Key: %s\' --verbose http://127.0.0.1/api/job" %Xapikey
		os.system ("curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"pause\"}\' --header \'X-Api-Key: %s\' --verbose http://127.0.0.1/api/job" %Xapikey)
		sleep(0.5)
		print "curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"home\", \"axes\": [\"x\", \"y\"]}\' --header \'X-Api-Key: %s\' --verbose http://127.0.0.1/api/printer/printhead" %Xapikey
		os.system ("curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"home\", \"axes\": [\"x\", \"y\"]}\' --header \'X-Api-Key: %s\' --verbose http://127.0.0.1/api/printer/printhead" %Xapikey)
		sleep(0.5)
		print "curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"M109 S50\"}\' --header \'X-Api-Key: %s\' --verbose http://127.0.0.1/api/printer/command"  %Xapikey
		os.system ("curl -H \"Content-Type: application/json\" --request POST --data \'{\"command\": \"M104 S10\"}\' --header \'X-Api-Key: %s\' --verbose http://127.0.0.1/api/printer/command"  %Xapikey)
                envoi = 1
Example #26
0
sess = dryscrape.Session(base_url='https://www.royalmail.com')

# we don't need images
sess.set_attribute('auto_load_images', False)

while True:
    # visit the tracking page and lookup the tracking number
    sess.visit('/track-your-item')
    q = sess.at_xpath('//*[@name="tracking_number"]')
    q.set(trackingNumber)
    q.form().submit()

    # extract the tracking status
    try:
        x = sess.at_xpath('//*[@class="status result-row padding20lr first"]')
        status = x.text()
    except AttributeError:
        x = sess.at_xpath(
            '//*[@class="status result-row padding20lr first last"]')
        status = x.text()

    if (status != prevStatus):
        # push the status to PushBullet
        # if you would like to push to more than one device then just copy the line below and change the device ID
        p.pushNote(deviceId, 'RoyalMail Tracking', status)

        prevStatus = status

    # wait for 'refreshRate' minutes before checking again
    time.sleep(refreshRate * 60)
Example #27
0
    def sendPushNotification(self):
        apiKey = "o.BpgNSJ77CGxsWEz2CUJWkDI0oI8hYGoq"
        p = PushBullet(apiKey)
        # Getting a list of devices
        devices = p.getDevices()

        # Specifying relative path
        path1 = os.path.realpath(__file__)
        path2 = os.path.basename(__file__)
        rel_path = path1.replace(path2, "")

        # Loading config.json file
        with open(rel_path + 'config.json', 'r') as f:
            config_dict = json.load(f)

        i = 1
        while i < 10:
            deviceList = self.scanDevices()
            print(deviceList)
            if devices[0].get("nickname") in deviceList:
                print("Device found. Sending notification...")
                print(self.humid)
                print(self.temp)
                # Check if the readings are out of range
                # Send pushbullet notification based on readings status
                if self.humid < config_dict['min-humidity']:
                    if self.temp < config_dict['min-temperature']:
                        range1 = config_dict['min-humidity'] - self.humid
                        range2 = config_dict['min-temperature'] - self.temp
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees lower than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% lower than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    elif self.temp > config_dict['max-temperature']:
                        range1 = config_dict['min-humidity'] - self.humid
                        range2 = self.temp - config_dict['max-temperature']
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees higher than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% lower than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    else:
                        range = config_dict['min-humidity'] - self.humid
                        comment = 'The humidity is ' + str(round(range, 2))
                        comment = comment + '% lower than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                elif self.humid > config_dict['max-humidity']:
                    if self.temp < config_dict['min-temperature']:
                        range1 = self.humid - config_dict['max-humidity']
                        range2 = config_dict['min-temperature'] - self.temp
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees lower than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% higher than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    elif self.temp > config_dict['max-temperature']:
                        range1 = self.humid - config_dict['max-humidity']
                        range2 = self.temp - config_dict['max-temperature']
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees higher than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% higher than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    else:
                        range = self.humid - config_dict['max-humidity']
                        comment = 'The humidity is ' + str(round(range, 2))
                        comment = comment + '% higher than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                elif self.temp < config_dict['min-temperature']:
                    if self.humid < config_dict['min-humidity']:
                        range1 = config_dict['min-humidity'] - self.humid
                        range2 = config_dict['min-temperature'] - self.temp
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees lower than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% lower than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    elif self.humid > config_dict['max-humidity']:
                        range1 = self.humid - config_dict['max-humidity']
                        range2 = config_dict['min-temperature'] - self.temp
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees lower than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% higher than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    else:
                        range = config_dict['min-temperature'] - self.temp
                        comment = 'The temperature is ' + str(round(range, 2))
                        comment = comment + ' degrees lower than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                elif self.temp > config_dict['max-temperature']:
                    if self.humid < config_dict['min-humidity']:
                        range1 = config_dict['min-humidity'] - self.humid
                        range2 = self.temp - config_dict['max-temperature']
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees higher than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% lower than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    elif self.humid > config_dict['max-humidity']:
                        range1 = self.humid - config_dict['max-humidity']
                        range2 = self.temp - config_dict['max-temperature']
                        comment = 'The temperature is ' + str(round(range2, 2))
                        comment = comment + ' degrees higher than the limit '
                        comment = comment + 'and the humidity is '
                        comment = comment + str(round(range1, 2))
                        comment = comment + '% higher than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                    else:
                        range = self.temp - config_dict['max-temperature']
                        comment = 'The temperature is ' + str(round(range, 2))
                        comment = comment + ' degrees higher than the limit'
                        p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                else:
                    comment = 'The temperature is ' + str(round(
                        self.temp, 2)) + ' degrees'
                    comment = comment + ' and the humidity is ' + str(
                        round(self.humid, 2))
                    comment = comment + '%'
                    p.pushNote(devices[0]["iden"], 'Bluetooth', comment)

                i = 10
            # If the device is not found
            else:
                print("Device not found")
                i = i + 1
Example #28
0
    soup = BeautifulSoup(page.content, 'html.parser')
    base=soup.findAll('td', {'class':'data-col1 Ta(start) Pstart(10px) Miw(180px)'})
    yhoo=[]
    for i in base:
        yhoo.append(i.get_text())
    strYHOO=" ,".join(str(x) for x in yhoo[0:15])


    #crypto trends to find

    with urllib.request.urlopen("https://api.coinmarketcap.com/v2/ticker/") as url:
        cmc = json.loads(url.read().decode())
    names=[]
    change=[]
    for i in cmc['data']:
        names.append(cmc['data'][i]['symbol'])
        change.append(cmc['data'][i]['quotes']['USD']['percent_change_24h'])
    change, names = zip(*sorted(zip(change, names)))
    cmcstr=' ,'.join([str(a) + ': '+ str(b) + '%' for a,b in zip(names[-5:],change[-5:])])

    apiKey = API_KEY
    p = PushBullet(apiKey)
    # Get a list of devices
    devices = p.getDevices()
    devices

    p.pushNote(devices[0]["iden"], 'Daily news ', "***TREND TWT POLSKA:" + strPLT + "\n***TREND TWT GLOBAL: " + strGT + "\n***G US SEARCH: " + strGog + "\n***TOP TICKERS YAHOO: " + strYHOO + "\n***CMC TOP: " + cmcstr)
    print('yes')
else:
    print('not')