Esempio n. 1
0
def find_slots(zipcode: str):
    result = requests.get(BASE_URL + zipcode)
    data = result.json()

    cur_week = datetime.now().isocalendar()[1]

    data = data.get("_embedded").get("lanes")[3].get("_embedded").get(
        "items")[0].get("_embedded")
    total_slots = 0
    for day in data.get("deliveryDates"):
        date = datetime.strptime(day['date'], "%Y-%m-%d")
        if date.isocalendar()[1] == cur_week:
            r = 0
            for slot in day['deliveryTimeSlots']:
                if slot['state'] != "full":
                    r += 1
            total_slots += r

    if total_slots > 0:
        notify = Notify()
        if notify.config_file_exists:
            notify.read_config()
        else:
            print(notify.register())
            notify.write_config()
        print("[" + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
              "] Notifying about " + str(total_slots) + " available slots")
        notify.send("AH Bezorg slots beschikbaar", "https://www.ah.nl")
def alert_many_users(user_num):
    #user_num += 1
    notify = Notify()
    notify.send("ALERT: Number of users exceeded " + str(user_num) + " !")


#alert_many_users(100)
Esempio n. 3
0
def run_notify(item_name, exterior, stattrak, max_price, max_float):
    notify = Notify()
    print(notify.info())

    listings = get_listings(item_name, exterior, stattrak)

    while True:
        findings = []
        for ind, item in enumerate(listings):
            a_id, d_id, l_id = get_inspect_id(item)
            float_val = get_float(a_id, d_id, l_id)
            price = get_price(item)

            if float_val <= max_float and price <= max_price:
                findings.append((price, float_val))
                page_count, item_count = index_to_page_count(ind)

        if findings:
            for price, float_val in findings:
                print(f"Found item, float: {float_val}, price: {price}€")

            notify.send("Found new items!")
            print(
                "----------------------------------------------------------------------"
            )
        sleep(30)
def Parsefeed():

    url = "placements.iitb.ac.in"

    notify = Notify()

    # ldap ID
    auth_user = ""

    # ldap Password
    auth_passwd = ""

    # Securing your HTTP request

    password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, url, auth_user, auth_passwd)
    authhandler = urllib.request.HTTPBasicAuthHandler(password_mgr)
    opener = urllib.request.build_opener(authhandler)
    urllib.request.install_opener(opener)
    old = None

    while(1):
        response = urllib.request.urlopen("http://placements.iitb.ac.in/blog/?feed=rss2").read()
        f = feedparser.parse(response)

        new = f['items'][0]['title'].encode('utf-8')
        if new != old:
            notify.send(new)
            old = new
        time.sleep(3000)
def AmazonScraper(url, desired_price):

    headers = {
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }
    success = 1
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")

    r = requests.get(url, headers=headers)
    soup = bs(r.content, 'html5lib')
    test = soup.find('span', id='priceblock_ourprice')
    if test is None:
        test = soup.find('span', id='priceblock_dealprice')

    price = int(pd((str(test))))
    print(price)

    if (price < desired_price):
        title = str(soup.find('span', id='productTitle').get_text().strip())
        message = title + " :::Price Decreased to :" + str(price)
        notify = Notify()
        notify.send(message)
        success = 0

    return success
Esempio n. 6
0
class StatusMonitor:
    def __init__(self):
        self.server_url = config['server_url']
        self.api_path = '/status-json.xsl'
        self.notification_interval = datetime.timedelta(minutes=30)
        self.poll_interval_seconds = 10
        self.popularity_threshold = 1  # Send notifications if listener count is above this
        self.last_notified = datetime.datetime.now() - datetime.timedelta(
            minutes=60)
        self.notifier = Notify()
        self.update()

    def update(self):
        self.page_response = requests.get(self.server_url + self.api_path)
        self.stats = json.loads(self.page_response.text)
        self.listeners = self.stats['icestats']['source']['listeners']

        time_since_last_notif = datetime.datetime.now() - self.last_notified
        due = time_since_last_notif > self.notification_interval
        popular = self.listeners >= self.popularity_threshold
        print('due {}, popular {}'.format(due, popular))
        if due and popular:
            # Dispatch notification
            print('sending listener count notification')
            self.notifier.send('There are {} listeners'.format(self.listeners))
            self.last_notified = datetime.datetime.now()

    def poll(self):
        while 1 == 1:
            self.update()
            print('There are currently {} people listening.'.format(
                self.listeners))
            time.sleep(self.poll_interval_seconds)
Esempio n. 7
0
async def handle_earthquake_msg(messages):
    notify = Notify(endpoint='https://notify.run/7qIErxULDNDO4jDYgAca')
    async for msg in messages:
        notify.send(f'{msg.title}')
        # update kafka table
        key = f'{msg.latitude},{msg.longitude}'
        earthquake_table[key] += 1
Esempio n. 8
0
    def flood_png(fname, png_save_dir):
        notify = Notify()

        pngname = os.path.join(png_save_dir, '%s.png' % fname)

        flood_dir = os.path.join(png_save_dir, 'flood')
        # create flooded png directory if doesn't exist
        if not os.path.isdir(flood_dir):
            print('creating flood directory', flush=True)
            os.mkdir(flood_dir)

        floodpngname = os.path.join(flood_dir, '%s_flooded.png' %
                                    fname)  # flooded .png file with full path
        print('\n##### starting flooding png')
        notify.send('Starting png flood-fill')
        print(floodpngname)

        ### check for already existing flooded .png file
        if os.path.exists(floodpngname):
            print("FLOODED PNG file %s already exists" % floodpngname)
        else:
            print('Info on PNG file \'' + pngname + '\':')
            png = Floodfill(pngname)
            print('flooded')

            im = Image.fromarray(png.png_data)
            im.save(floodpngname)

            # png.write_to_png(filename=floodpngname)
            #print('wrote')

        notify.send('complete')
Esempio n. 9
0
class Notification:
    def __init__(self, directory=None):
        self.service = Notify()
        self.message = None
        self._total_news = 0
        self._directory = directory

    def _generate_message(self):
        template = 'Your news feed is ready.\nTotal news today: {total}\nSaved in:\n{direc}'
        self.message = template.format(total=self._total_news,
                                       direc=self._directory)

    def get_total_news(self, value):
        self._total_news += value

    def set_directory(self, value):
        self._directory = str(value)

    def send_note(self):
        try:
            with open('../resources/registered.txt', 'r') as input_file:
                status = int(input_file.read())
                print(status)
                if status != 1:
                    register_notify()

        except FileNotFoundError:
            register_notify()
        print(self._total_news, self._directory)
        if self._total_news and self._directory:
            self._generate_message()
            self.service.send(self.message)
        else:
            print('Something goes wrong')
Esempio n. 10
0
def main():
    session_requests = requests.session()

    result = session_requests.get(LOGIN_URL)
    tree = html.fromstring(result.text)

    # Create payload
    payload = {
        "login": USERNAME,
        "password": PASSWORD,
    }

    # Perform login
    result = session_requests.post(LOGIN_URL,
                                   data=payload,
                                   headers=dict(referer=LOGIN_URL))

    # Scrape url
    result = session_requests.get(URL, headers=dict(referer=URL))

    soup = BeautifulSoup(result.content, 'html.parser')

    pair = True

    lines1 = []

    f_notes = open("notes.txt", "r+")
    lines2 = f_notes.readlines()

    #check for emptyness (first run)
    if len(lines2) == 0:
        for td in soup.find_all('td'):
            if pair:
                f_notes.write(td.contents[0] + " : ")
            else:
                f_notes.write(td.contents[0] + '\n')
            pair = not (pair)

    s = ''
    for td in soup.find_all('td'):
        if pair:
            s += str(td.contents[0]) + " : "
        else:
            s += td.contents[0] + '\n'
            lines1.append(s)
            s = ''
        pair = not (pair)

    added = list(set(lines1) - set(lines2))

    if len(added) != 0:
        f_notes = open("notes.txt", "a")
        notify = Notify()
        for line in added:
            f_notes.write(str(line))
            notify.send('Note : ' + line.split(':')[0])
        f_notes.close()

    f_notes.close()
Esempio n. 11
0
def send_notice():
	global check_send,check_end,check_time
	while check_end < 1:
		if check_send == 1:
			if check_time>2:
				music = pyglet.resource.media('police.wav')
				music.play()
				notify = Notify()
				notify.send('Hi there!')
 def notify(self):
     for item in self.global_notication:
         if item['id'] not in self.notificated:
             self.notificated.append(item['id'])
             text = item['ticketNumber'] \
             + ': ' \
             + item['subject']
             notify = Notify()
             notify.send(text)
Esempio n. 13
0
class AndroidNotification(NotificationService):
    def __init__(self):
        super().__init__(name="Send Android Push")
        self.notifier = Notify()

    def initialize(self):
        self.notifier.send("Impftermin Startup Test Message")

    def _send_notification(self, result):
        self.notifier.send(result.url)
        return True
Esempio n. 14
0
def check_for_tweets():
    twitter = Twitter(os.path.join(BASE_DIR, CONFIG_FILE))

    try:
        # Check which tweets have already been processed
        with open(os.path.join(BASE_DIR, "prev_id"), "r") as file:
            prev_id = int(file.read())
    except FileNotFoundError:
        # File 'prev_id' does not exist, set it as his most recent tweet
        tweets = twitter.get_tweets_from_user(PROJECT_SETTINGS['elonHandle'])
        prev_id = tweets[0].id

    # Load the keywords we are checking for
    with open(os.path.join(BASE_DIR, "keywords"), "r") as file:
        keys = file.read()
    keywords = keys.split("\n")

    # Load tweets
    tweets = twitter.get_tweets_from_user_since(PROJECT_SETTINGS['elonHandle'],
                                                prev_id)

    # Check the tweets for keywords
    found = set()
    max_id = prev_id
    for tweet in tweets:
        id = tweet.id
        txt = str(tweet.text).lower()
        for key in keywords:
            if key in txt:
                found.add(key)
        if id > max_id:
            max_id = id

    # Save our progress
    with open(os.path.join(BASE_DIR, "prev_id"), "w") as file:
        file.write(str(max_id))

    # Notify if necessary
    if len(found) > 0:
        msg = "Elon Tweeted about the following topics: '" + ", ".join(
            found) + "'"

        notify = Notify()
        if notify.config_file_exists:
            notify.read_config()
        else:
            print(notify.register())
            notify.write_config()

        print("[" + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +
              "] Sending notification: " + msg)

        notify.send(
            msg, "https://www.twitter.com/" + PROJECT_SETTINGS['elonHandle'])
Esempio n. 15
0
class CoronaNotification():
    def __init__(self):
        super(CoronaNotification, self).__init__()

    def sendNotification(self, updatedValue):
        with open("temp.txt") as f:
            with open("history.txt", "w") as f1:
                for line in f:
                    f1.write(line)
        try:
            self.notify = Notify()
            self.notify.send("New cases in " + updatedValue,
                             'https:\\\\www.mohfw.gov.in\\')
        except Exception as e:
            print(e)

    def fetchDataFromGovtSite(self):
        url = 'https://www.mohfw.gov.in/'
        resp = requests.get(url)
        if resp.status_code == 200:
            soup = BeautifulSoup(resp.text, 'html.parser')
            tableBody = soup.find("tbody")
            row = tableBody.findAll('td')
            index, isDataChanged, updatedValue = 0, False, ""
            historyFile = open("history.txt", 'r+')
            tempFile = open("temp.txt", 'w')
            jsonData = json.dumps({})
            while index < len(row) - 6:
                historyData = historyFile.readline()

                currentData = json.dumps({
                    "StateName":
                    str(row[index + 1].contents[0]),
                    "TotalIndian":
                    int(row[index + 2].contents[0]),
                    "TotalCured":
                    int(row[index + 3].contents[0]),
                    "TotalDeath":
                    int(row[index + 4].contents[0])
                })

                tempFile.write(currentData + '\n')

                if historyData[:len(historyData) - 1] != currentData:
                    isDataChanged = True
                    updatedValue += json.loads(currentData)["StateName"] + ', '

                index += 5
            tempFile.close()
            historyFile.close()

            if isDataChanged:
                self.sendNotification(updatedValue[:(len(updatedValue) - 2)])
Esempio n. 16
0
def keamanan_notif():
    try:
        connection = pymysql.connect(host='localhost',
                                     user='******',
                                     password='******',
                                     db='absensi',
                                     unix_socket="/var/run/mysqld/mysqld.sock",
                                     port=3306,
                                     charset='utf8mb4',
                                     cursorclass=pymysql.cursors.DictCursor)
        with connection.cursor() as cursor:
            # Create a new record
            ceksql = "SELECT COUNT(nama) AS ceknama FROM `face_keamanan` WHERE DATE(`waktu`) = DATE(CURDATE()) AND aktif_notif='1' LIMIT 1"
            cursor.execute(ceksql)
            checking = cursor.fetchone()
            print(checking.get('ceknama'))

            ceknama = "SELECT nama,waktu FROM `face_keamanan` WHERE DATE(`waktu`) = DATE(CURDATE()) AND aktif_notif='1' LIMIT 1"
            cursor.execute(ceknama)
            checkingnama = cursor.fetchone()
            checkingjeneng = checkingnama.get('nama')
            checkingwaktu = checkingnama.get('waktu')
            waktu = '%s' % checkingwaktu

            if checking.get('ceknama') >= 1:
                ceksqli = "SELECT `divisi`,`no_hp` FROM `employee` WHERE nama_pegawai=%s"
                cursor.execute(ceksqli, (checkingjeneng))
                checkingi = cursor.fetchone()

                divisi = checkingi.get('divisi')
                no_hp = checkingi.get('no_hp')

                notify = Notify()
                notify.send('%s Memasuki Ruangan Terlarang' % checkingjeneng)
                text = '%s , dari Divisi %s dengan nomor hp %s Memasuki Ruangan Terlarang' % (
                    checkingjeneng, divisi, no_hp)
                id_tele = '205017793'
                poto = open(
                    'hasil_keamanan/' + checkingjeneng + waktu + ".jpg", 'rb')
                send_message_kemananan(text, id_tele, poto)

                sql = "UPDATE `face_keamanan` SET `aktif_notif`=0 WHERE nama=%s"
                cursor.execute(sql, (checkingjeneng))
        # connection is not autocommit by default. So you must commit to save
        # your changes.
        connection.commit()
        return True

    finally:
        connection.close()
Esempio n. 17
0
class notificator():
    def __init__(self):
        self.notify = Notify()
        print(self.notify.info())
        self.project_name = os.getcwd().split('\\')[
            -1]  # Using the name of the parent folder
        self.computer_name = os.environ['COMPUTERNAME']

    # This function takes the CSP, classifier, number of channels, and folder with the file to run's
    #location, as well as the degrees of freedom required for the classifier
    def send_msg(self, msg):
        msg_to_send = '[{} - {}]\n' + msg
        msg_to_send = msg_to_send.format(self.computer_name, self.project_name)
        self.notify.send(msg_to_send)
def send_to_notify_run(new_items, endpoint):
    """
    Composes messages to send to notify run and sends them to the notify run channel.
    Sends a message for each new item in the new_items dict.
    """
    print("New magic boxes found! Check notify run channel!")
    notify = Notify(endpoint=endpoint)
    for item in new_items.values():
        name = item[0][1]
        loc = item[0][2]
        message = ("Magic Box @ " + str(name) + " " + loc + "!\n" +
                   str(item[0][3]) + " beschikbaar van " + str(item[0][0]))
        try:
            notify.send(message)
        except Exception as e:
            print(e)
            time.sleep(5)
            send_to_notify_run(newItems)
Esempio n. 19
0
def main():
    last_time = ''
    while (True):

        trackNumber = '959781695147'
        # print('getting track: ' + trackNumber)

        result = get_post_by_track(trackNumber)

        current_date = result[1]
        if (last_time != current_date):
            print(result[0], ':', result[1], result[2])
            notify = Notify()
            notify.send(result[2])
        # else:
        #     print('no changes')
        last_time = current_date
        sleep(60 * 10)
def Parsefeed():

    ICON_PATH = os.getcwd() + "/64x64.png"
    url = "placements.iitb.ac.in"

    if MOBILE_NOTIFICATION:
        notify = Notify()

    #ldap ID
    auth_user = ""

    #ldap Password
    auth_passwd = ""

    #Securing your HTTP request

    password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, url, auth_user, auth_passwd)
    authhandler = urllib.request.HTTPBasicAuthHandler(password_mgr)
    opener = urllib.request.build_opener(authhandler)
    urllib.request.install_opener(opener)
    notify2.init('Placement Blog Notify')
    old = None

    while (1):
        response = urllib.request.urlopen(
            "http://placements.iitb.ac.in/blog/?feed=rss2").read()
        f = feedparser.parse(response)

        new = f['items'][0]['title'].encode('utf-8')
        if new != old:
            n = notify2.Notification(f['items'][0]['title'].encode('utf-8'),
                                     f['items'][0]['summary'].encode('utf-8'),
                                     icon=ICON_PATH)

            n.set_urgency(notify2.URGENCY_NORMAL)
            n.show()

            if MOBILE_NOTIFICATION:
                notify.send(new)

            old = new
            n.set_timeout(15000)
        time.sleep(3000)
def main():

    from keras.models import load_model
    from keras.models import model_from_json
    import json

    from notify_run import Notify
    
   
    
    filename="0.jpg"
   
    #filename="0.jpg"
    # load json and create model
    json_file = open('Final.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model=load_model("Mz-model.h5")
    #loaded_model.load_model("Mz-model.h5")
    print("Loaded model from disk")

    import numpy as np
    from keras.preprocessing import image
    import matplotlib.pyplot as plt

    img_pred = image.load_img('/Users/manthanmkulakarni/Desktop/JU-Nanda/images/'+filename, target_size = (64, 64))
    plt.imshow(img_pred)
    img_pred = image.img_to_array(img_pred)

    img_pred = np.expand_dims(img_pred, axis = 0)
    rslt = loaded_model.predict(img_pred)

    #ind = train_set.class_indices

    if (rslt[0][0] == 1):
        prediction = "No dieseases"
    else:
        prediction = "Common Rust Found"
        notify = Notify()
        notify.send('Common Rust FOUND !!!\n Follow the preventive measures')
    print(prediction)
Esempio n. 22
0
    def send_alert(self, flag, price):
        '''Sends notification & adjusts limits by 0.5%'''

        notify = Notify()

        if flag == 'High':
            notify.send('Instrument {} > {}$'.format(self.ticker,
                                                     self.upper_limit))
            self.adjust_limits_up()
        elif flag == 'Low':
            notify.send('Instrument {} < {}$'.format(self.ticker,
                                                     self.lower_limit))
            self.adjust_limits_down()

        print('{} alert sent for {} at {}$ ({}).'.format(
            flag, self.ticker, price,
            dt.now().strftime('%H:%m')))
        print("New low: {}, new high {}".format(round(self.lower_limit, 3),
                                                round(self.upper_limit), 3))
Esempio n. 23
0
def send_alert(joined_class=None,
               exit_class=None,
               link=None,
               custom_msg=None,
               class_name=None):
    notify = Notify()
    if joined_class:
        msg = f"Joined class succesfully\nClass: {class_name}"
        notify.send(msg)
    if exit_class:
        msg = f"Exited class succesfully\nClass: {class_name}"
        notify.send(msg)
    if joined_class is False:
        msg = f"Failed to join class\nClass: {class_name}. Click to join"
        notify.send(msg, link)
    if exit_class is False:
        msg = f"Failed to exit class\nClass: {class_name}"
        notify.send(msg)
    if custom_msg:
        notify.send(custom_msg)
Esempio n. 24
0
class Notifier(object):
    def __init__(self, remote_notifications=False):
        self._local_notifier = LocalNotify()
        if remote_notifications:
            self._remote_notifier = RemoteNotify()
            logger.info(
                "Registering a new Remote Push Notification (RPN) endpoint")
            remote_notify_info = self._remote_notifier.register()
            self._display_remote_notify_info(str(remote_notify_info))
        else:
            self._remote_notifier = None

    @classmethod
    def _display_remote_notify_info(cls, remote_notify_info):
        if os.name == 'nt':
            # Windows cmd/powershell does not display QR code properly - stripping it off
            remote_notify_info = remote_notify_info[:remote_notify_info.index(
                "Or scan this QR code")]

        logger.info(
            """\n\n****************** REMOTE PUSH NOTIFICATIONS ********************\n
            %s
            \nNOTE: iOS and Safari NOT supported
            \n*****************************************************************\n""",
            remote_notify_info
        )

    def notify(self, title, message, link):
        if self._remote_notifier:
            self._send_remote_notification(title, message, link)
        else:
            self._send_local_notification(title, message)

    def _send_local_notification(self, title, message):
        self._local_notifier.title = title
        self._local_notifier.message = message
        self._local_notifier.send()

    def _send_remote_notification(self, title, message, link):
        self._remote_notifier.send(
            "{title} - {message}".format(title=title, message=message), link)
Esempio n. 25
0
 def updateTemp(self, value):
     smallValue = self.labe4["text"].strip('C')
     largeValue = self.labe5["text"].strip('C')
     self.temperatureText.set(str(value).strip() + 'C')
     if (self.labe4["text"] != "Not Set"
             and self.labe5["text"] != "Not Set"):
         delta = 0.05 * (float(largeValue) - float(smallValue))
         if (float(value) > float(largeValue)
                 or float(value) < float(smallValue)):
             self.labe1.config(bg="Red")
             notify = Notify()
             notify.send(
                 "Warning! The temperature is outside of the Parameters. Fix immediately."
             )
         elif (float(value) > (float(largeValue) - delta) or float(value) <
               (float(smallValue) + delta)):
             self.labe1.config(bg="Yellow")
         else:
             self.labe1.config(bg="Green")
     else:
         self.labe1.config(bg="White")
Esempio n. 26
0
class NotificationService:
    """ Send notifications and handles retrieving service urls """

    LOGGER = logging.getLogger(__name__)

    def __init__(self, endpoint_url: str):
        self.notify = Notify(endpoint=endpoint_url)
        self.user_configuration = UserConfiguration()

    def send(self, notification: str):
        """ Send a notification to the service endpoint """
        self.LOGGER.debug(f'Sending Notification: {notification}')
        self.notify.send(notification)
        self.user_configuration.insert_notification_history(notification)

    @staticmethod
    def get_new_subscription_url():
        """ Retrieve a new subscrption url from the remote service """
        service_url = Notify().register().endpoint
        NotificationService.LOGGER.debug(f'Retrieved new service URL: {service_url}')
        return service_url
def recognizePerson(x, y, w, h, image, grayImage):
    cv.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 2)
    ID, confidence = recognizer.predict(grayImage[y:y + h, x:x + w])
    confidence = "%.2f" % confidence
    if float(confidence) < 60:
        profile = getPersonProfile(ID)
        if profile != None:
            cv.putText(image,
                       str(profile[1]) + " - " + str(confidence) + "%",
                       (x, y + h), cv.FONT_HERSHEY_PLAIN, 1.5, (255, 255, 255),
                       2)
            cv.putText(image, str(profile[2]), (x, y + h + 30),
                       cv.FONT_HERSHEY_PLAIN, 1.5, (255, 255, 255), 2)
    else:
        print(confidence)
        notify = Notify()
        notify.send(
            "Perimeter compromised... Sending Team Alpha for preliminary action..."
        )

    return image
Esempio n. 28
0
    def wavToScl(wavname, scalname, scalgzname, mp3name):

        notify = Notify()

        #print('\nstarting wav -> scal transformation')
        notify.send('Starting wav -> scal transformation')

        ### check for already existing .scal file
        if os.path.exists(scalname) or os.path.exists(scalgzname):
            #print("SCAL file or gz %s already exists" % scalname)
            notify.send("SCAL file or gz %s already exists" % scalname)

        else:
            ################################################################
            ### create the scal file
            print("Creating SCAL file from \"" + wavname + "\".")
            scal = Scalogram(wavname)
            scal.write_to_file(filename=scalname)
            print("   ", scal)
            print('scalfile created')  # log

            notify.send('complete')

            ################################################################
            ### compress .wav file once converted to .scal file
            #print('compressing wav file %s' % wavname)
            #print('compressing wav file %s' % wavname) # log
            os.system('ffmpeg -i %s %s' % (wavname, mp3name))
Esempio n. 29
0
def push_notification(pnmsg):
    notify = Notify()
    notify.send(pnmsg)

    print("HEY jatin, PUSH NOTIFICATION HAS BEEN SENT SUCCESSFULLY.")

    print("Check again after an hour.")

    def cricscore():
        url = "https://www.espn.in/cricket/series/19312/game/1187013/india-vs-bangladesh-1st-t20i-bangladesh-in-india-2019-20"
        headers = {
            "User-Agent":
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'
        }
        r = requests.get(url)
        while r.status_code is 200:
            page = requests.get(url)
            soup = BeautifulSoup(page.content, 'html.parser')
            push_notification(soup.title)
        sleep(100)

    cricscore()
Esempio n. 30
0
def compare_price(db, scraped):
    db = json.loads(db[1])
    db_price = float(
        list(db['price'].values())[0].replace('CDN$', '').replace(',', ''))
    scraped_price = float(
        list(scraped['price'].values())[0].replace('CDN$',
                                                   '').replace(',', ''))

    if db_price > scraped_price and scraped_price != 0:
        print('PRICE DROP: ' + str(db_price) + ' --> ' + str(scraped_price))
        if (db_price - scraped_price) > 25:
            if float(db['rating'].replace('/5', '')) > 4:
                notify = Notify()
                notify.send(
                    str(' '.join(db['name'].split()[:4])) + ' PRICE DROP: ' +
                    str(db_price) + ' --> ' + str(scraped_price))
        return db_price, scraped_price
    elif db_price < scraped_price:
        print('PRICE RAISE: ' + str(db_price) + ' --> ' + str(scraped_price))
        return db_price, scraped_price
    else:
        return 0, 0