def send_notification(node, event, **meta): cfg = node.config() # construct notification text try: if event == 'montage': subject, msg = build_montage_notification(node, **meta) elif event == 'montage_start': subject, msg = build_montage_start_notification(node, **meta) elif event == 'error': subject, msg = build_error_notification(node, **meta) elif event == 'make_safe': subject, msg = build_make_safe_notification(node, **meta) elif event == 'kill_beam': subject, msg = build_kill_beam_notification(node, **meta) except Exception as e: subject = 'Error: %s' % e msg = 'event: %s, %s' % (event, meta) if not cfg.get('notification', {}).get('enable', False): logger.debug("built notification for %s", event) logger.debug("notification subject: %s", subject) logger.debug("notification message: %s", msg) return # send notification ncfg = cfg['notification'] if 'to_email' in ncfg and len(ncfg['to_email']): notifier.notify(msg, subject=subject, to_email=ncfg['to_email']) if ('slack_channel' in ncfg and hasattr(notifier, 'channel_message')): token = ncfg.get('slack_token', os.environ.get('SLACK_TOKEN', None)) if token is not None: notifier.channel_message(msg, ncfg['slack_channel'], token)
def process_stuff(code, date): all_slots = [] time.sleep(random.randint(1, 30)) all_slots = get_slots_by_pincode(code, date) if all_slots: print(all_slots) for centre in all_slots: ## Filter only covaxin and if slots are available if centre[2] in preferred_vaccine and centre[3] > min_available: line = "Hospital:{}\nDate:{}\nSlots:{}\nVaccine:{}\nPostedTime:{}".format( centre[0], centre[1], centre[3], centre[2], today_obj.strftime("%d-%m-%Y-%H-%M")) entry = "{}|{}|{}|{}|{}".format( today_obj.strftime("%d-%m-%Y-%H-%M"), centre[0], centre[1], centre[3], centre[2]) print( "==========================VACCINES FOUND======================================" ) print(line) print( "===============================================================================" ) notifier.notify(line) with open(outfile, "a") as out: out.write(entry + "\n") make_calls() send_whatsapp(line) send_sms(line)
def notify_homework_updates(updates): new_items = [] deleted_items = [] for update in updates: if update.type == ChangeType.NEW: new_items.append(update.ref) elif update.type == ChangeType.DELETED: deleted_items.append(update.ref) cards = [] PREFIX = "**Van de vakken:** " SUFFIX = "\n\n_Zie https://somtoday.nl/ voor meer info_" if len(new_items) <= 4: for item in new_items: cards.append( notifier.NotificationCard( "**Nieuw:** __{}__".format(item.topic), html_to_markdown(item.description), create_homework_fields(item))) else: cards.append( notifier.NotificationCard( "{}x nieuw huiswerk!".format(len(new_items)), PREFIX + ', '.join(homework_subjects(new_items)) + SUFFIX, None)) if len(deleted_items) <= 4: for item in deleted_items: cards.append( notifier.NotificationCard( "**Verwijderd:** __{}__".format(item.topic), html_to_markdown(item.description), create_homework_fields(item))) else: cards.append( notifier.NotificationCard( "{}x verwijderd huiswerk!".format(len(deleted_items)), PREFIX + ', '.join(homework_subjects(new_items)) + SUFFIX, None)) title_parts = [] if len(new_items) > 0: title_parts.append("{}x nieuw".format(len(new_items))) if len(deleted_items) > 0: title_parts.append("{}x verwijderd".format(len(deleted_items))) short_title = "Huiswerk: " + ", ".join(title_parts) subject_names = [ notifier.remove_discord_emoji(s) for s in homework_subjects(get_update_refs(updates)) ] short_description = "Van: " + ", ".join(subject_names) + "." notifier.notify( notifier.Notification("Er zijn veranderingen aan het huiswerk!", cards, short_title, short_description), "Somtoday-Homework")
def device_auth(): code_data = get_device_code() if not code_data: logger.error('Failed device auth.') sys.exit(1) logger.info(f"Verification URL: {code_data['verification_url']}") logger.info(f"User Code: {code_data['user_code']}") notify("Open {verification_url} in your browser and enter this code: " "{user_code}".format(**code_data), timeout=60) webbrowser.open(code_data['verification_url']) start = time.time() while time.time() - start < code_data['expires_in']: token_data = get_device_token(code_data['device_code']) if not token_data: logger.debug('Waiting for user to authorize app.') time.sleep(int(code_data['interval'])) else: notify('App authorized successfully.') logger.info('Device auth successful.') break else: logger.error('Timed out during auth.') return token_data
def main(): while 1: entrylist = scraper.scrape_all() for entry in entrylist: if validator.is_unique(entry): database_connector.store(entry) notifier.notify(entry)
def handle(s3_event, context): consumer = _get_consumer() for event in s3_event['Records']: s3_path = event_parser.extract_s3_path(event) logger.info(f"Extracted path {s3_path}") notifier.notify(consumer, s3_path)
def send_status_notification(): stats = get_statistics() if stats: message = 'Total: %s | Null Containing: %s | Last Update: %s' % (stats.inserted_rows, stats.null_containing_rows, stats.updated_at.strftime('%H:%M')) notify('Collector Statistics', message)
def manageReponse(statusCode, message, notify=True): response = { "statusCode": statusCode, "body": message } if notify: notifier.notify(statusCode, message) return response
def send_status_notification(): stats = get_statistics() if stats: message = 'Total: %s | Null Containing: %s | Last Update: %s' % ( stats.inserted_rows, stats.null_containing_rows, stats.updated_at.strftime('%H:%M')) notify('Collector Statistics', message)
def main(): if sys.argv[1] == 'LDA': checkLDA(sys.argv[2],int(sys.argv[3])) else: runTest(sys.argv[1], int(sys.argv[2])) with open('finish.txt','w') as finish: finish.write('finish') from notifier import notify notify()
def notify(events): message = "" message += "\n%d events\n" % len(events) message += pformat(Counter(row['Action'] for row in events)) message += "\n" message += pformat(events) subject = "[DOCKER_EVNETS] %d docker events\n" % len(events) print("Sending e-mail %s", subject) notifier.notify(message, subject)
def manageResponse(statusCode, message, notify=True): response = { "statusCode": statusCode, "body": json.dumps(message), "isBase64Encoded": False } if notify: notifier.notify(statusCode, message) return response
def main(): parser = argparse.ArgumentParser() parser.add_argument('-l', '--load', default=1.0, type=float, help="load threshold for notification") parser.add_argument('-t', '--polltime', default=1.0, type=float, help="time between load checks") parser.add_argument('-m', '--message', default="", type=str, help="message to include in notification") parser.add_argument('-s', '--subject', default="Load threshold hit", type=str, help="subject to include in notification") parser.add_argument('-e', '--email', default="", type=str, help="send notification to this email") parser.add_argument('-v', '--verbose', default=False, action='store_true', help="enable verbose output") args = parser.parse_args() if args.verbose: print("Arguments: %s" % args) if args.email == "": raise Exception("Missing email: %s" % args.email) l = os.getloadavg()[0] while l > args.load: if args.verbose: print("Current load: %s" % l) time.sleep(args.polltime) l = os.getloadavg()[0] msg = 'Load fell below threshold %s' % args.load if args.message != '': msg += '\n' + args.message if args.verbose: print("Sending notification[to %s]: %s, %s" % (args.email, args.subject, msg)) notifier.notify(msg, args.subject, args.email)
def notify(self): """ Checks the current date and calculates the week difference from start date of the class. Sends out Mac notification with the corresponding week topic :return: """ current_date = datetime.now().date() # subtracts week_between result by 1 to get index for _weeks week_index = self.weeks_between(self._start, current_date) - 1 week_num_string = "Week {}".format(self._weeks[week_index]['number']) week_topic = self._weeks[week_index]['topic'] # Mac Notification notifier.notify(self._code, week_num_string, week_topic)
def scrobble(self, verb, data): if trakt.scrobble(verb, **data): logger.info(f'Scrobble {verb} successful.') if verb != 'pause': notify(f"Scrobble {verb} successful for " f"{data['media_info']['title']}.") if self.watched_cache: self.clear_watched_cache() elif verb == 'stop' and data['progress'] > 80: logger.warning('Scrobble unsuccessful. Will try again later.') self.watched_cache.append(data) write_json(self.watched_cache, WATCHED_CACHE_PATH) else: logger.warning('Scrobble unsuccessful.')
def minipinga(data: Dict, context: Any) -> None: subs_ref = db.collection("subscriptions") for sub in subs_ref.stream(): sub_dict = sub.to_dict() indication_text_value = check_update(sub_dict) if indication_text_value: content_url = sub_dict.get("content_url", sub_dict["url"]) print( f"{sub_dict['title']} may be updated at {indication_text_value}" ) notifier.notify( f"{sub_dict['title']} が {indication_text_value} に更新されている可能性があります {content_url}" ) save(sub.id, indication_text_value)
def builder_log(): """Mostra il risultato dell'elaborazione""" form = BuilderLog() lc = session.get('log', '') x = request if form.validate_on_submit(): if 'apri' in request.form: fn, _ = os.path.splitext(session['module']) webbrowser.open('../html/' + fn + ".html" ) else: return redirect(url_for('generator')) notify(nobj, 'Scritta pagina ' + session.get('module', '')) return render_template('builder_log.html', titolo="Log elaborazione", form=form, logcontent=lc)
def notify_grade_updates(updates): new_items = [] deleted_items = [] for update in updates: if update.type == ChangeType.NEW: new_items.append(update.ref) elif update.type == ChangeType.DELETED: deleted_items.append(update.ref) cards = [] PREFIX = "**Cijfers:** " SUFFIX = "\n\n_Zie https://somtoday.nl/ voor meer info_" if len(new_items) <= 10: for item in new_items: cards.append( notifier.NotificationCard( "**__{}__** voor {}!".format( item.grade, get_subject_name(item.subject)), html_to_markdown(item.description), create_grade_fields(item))) else: cards.append( notifier.NotificationCard( "{} nieuwe cijfers!".format(len(new_items)), PREFIX + ", ".join(format_grade_list(new_items)) + SUFFIX, None)) if len(new_items) == 1: new_grade = new_items[0] short_title = "{} gehaald voor {} ({}x)!".format( new_grade.grade, notifier.remove_discord_emoji(get_subject_name(new_grade.subject)), new_grade.weight) short_description = new_grade.description else: short_title = "{} nieuwe cijfers!".format(len(new_items)) short = len(new_items) > 2 short_description = ", ".join(format_grade_list( new_items, True, short)) + "." notifier.notify( notifier.Notification("Er zijn nieuwe cijfers!", cards, short_title, short_description), "Somtoday-Grades")
def process_stuff(code, date): all_slots = [] time.sleep(random.randint(1, 40)) all_slots = get_slots_by_pincode(code, date) if all_slots: print(all_slots) for centre in all_slots: ## Filter only covaxin and if slots are available if centre[2] in preferred_vaccine and centre[3] > 0: entry = (centre[0], centre[1], centre[3]) line = "Hospital:{}\nDate:{}\nSlots:{}".format( centre[0], centre[1], centre[3]) with open(filename, 'a') as outfile: outfile.write(line + "\n") send_whatsapp(line) notifier.notify(line) print(line)
def secure_cancel_order(order_id): req_data = {'txid': order_id} function = 'CancelOrder' cmpt = 1 status_of_function = NOT_DONE while (status_of_function != DONE): try: logger.info(function + ' :try number ' + str(cmpt) + ' for ' + str(function)) result = krakken_connection.query_private('CancelOrder', req_data) if (len(result.get('error')) > 0): #{'error': [], 'result': {'count': 1}} error_type = result.get('error')[0] if ((error_type == 'EOrder:Invalid order') or ('EOrder:Unknown order' in error_type)): logger.warn( function + ' :Order ' + str(order_id) + ' not found (EOrder:Invalid order), but it seems to be ok ' ) status_of_function = DONE else: logger.warn(function + ' :Cant handle error ' + str(result) + 'cancel order will be re-processed') else: status_of_function = DONE if (cmpt > 10 and cmpt % 10 == 0): logger.info(function + ' :' + str(cmpt) + ' fail ! notifying ...') notifier.notify( 'Need You', str(cmpt) + ' fail on cancel order\n ! cant handle error' + str(result)) except Exception as e: logger.info( function + ' : private faced an error. Resetting exchange & retrying the request' ) logger.info(function + ' : Exception was :' + str(e)) logger.info(function + ' : Resetting & waiting :' + str(e)) reset() cmpt = cmpt + 1 logger.info(function + ' OK for ' + str(function)) return DONE
def on_processblocks(api, data=None): if data['type'] != 'pm': return data['block'].decrypt() metadata = data['block'].bmetadata signer = bytesconverter.bytes_to_str(data['block'].signer) user = contactmanager.ContactManager(signer, saveUser=False) name = user.get_info("name") if name != 'anonymous' and name != None: signer = name.title() else: signer = signer[:5] if data['block'].decrypted: notifier.notify(title="Onionr Mail - New Message", message="From: %s\n\nSubject: %s" % (signer, metadata['subject']))
def get_access_token(): global token_data if not token_data: logger.info("Access token not found in config. " "Initiating device authentication.") token_data = device_auth() write_json(token_data, TRAKT_TOKEN_PATH) elif token_data['created_at'] + token_data['expires_in'] - \ time.time() < 86400: logger.info("Access token about to expire. Refreshing.") token_data = refresh_token(token_data) write_json(token_data, TRAKT_TOKEN_PATH) if not token_data: logger.error("Unable to get access token. " f"Try deleting {TRAKT_TOKEN_PATH!s} and retry.") notify("Failed to authorize application.") sys.exit(1) return token_data['access_token']
def colorize(id, token): tic = time() prototxt = "./neuralnet/deploy.prototxt" caffemodel = "./neuralnet/release.caffemodel" input_path = "./storage/input/" output_path = "./storage/output/" img_in = input_path + id + ".png" img_out = output_path + id + ".png" caffe.set_mode_cpu() net = caffe.Net(prototxt, caffemodel, caffe.TEST) (H_in, W_in) = net.blobs['data_l'].data.shape[2:] (H_out, W_out) = net.blobs['class8_ab'].data.shape[2:] pts_in_hull = np.load('./neuralnet/resource.npy') net.params['class8_ab'][0].data[:, :, 0, 0] = pts_in_hull.transpose((1, 0)) img_rgb = caffe.io.load_image(img_in) img_lab = color.rgb2lab(img_rgb) img_l = img_lab[:, :, 0] (H_orig, W_orig) = img_rgb.shape[:2] img_rs = caffe.io.resize_image(img_rgb, (H_in, W_in)) img_lab_rs = color.rgb2lab(img_rs) img_l_rs = img_lab_rs[:, :, 0] net.blobs['data_l'].data[0, 0, :, :] = img_l_rs - 50 net.forward() ab_dec = net.blobs['class8_ab'].data[0, :, :, :].transpose((1, 2, 0)) ab_dec_us = sni.zoom(ab_dec, (1. * H_orig / H_out, 1. * W_orig / W_out, 1)) img_lab_out = np.concatenate((img_l[:, :, np.newaxis], ab_dec_us), axis=2) img_rgb_out = (255 * np.clip(color.lab2rgb(img_lab_out), 0, 1)).astype('uint8') plt.imsave(img_out, img_rgb_out) toc = time() print(toc - tic) notifier.notify(id, token)
def test_notify(self,factory): ext1=mock.Mock() ext2=mock.Mock() #two extensions ext1.notify.return_value=1 ext2.notify.return_value=2 #fake instance mgr=extension.ExtensionManager("TEST") #this is super dirty, but! well.... mgr.extensions=[extension.Extension("name1","","",ext1),extension.Extension("namer2","","",ext2)] factory.return_value=mgr #titles to notify titles=['title1','title2'] #notify notifier.notify(titles) #make sure all the pluggins were notified ext1.notify.assert_called_once_with(titles) ext2.notify.assert_called_once_with(titles)
def email(): ###Data Processing##################### data = json.loads(request.data) user = db.getNameFromID(data["userID"]) fromAcc = data["fromAcc"] toAcc = data["toAcc"] subject = data["subject"] content = data["content"] db.debug() #print("%%%%%%%%%%%%%%%%%%%%%%%%%",data) fromEmail = db.getEmail(fromAcc) toEmail = db.getEmail(toAcc) #print("EMAILLLLLLLLLLLLLLLLLLING") notifier.notify(fromEmail,toEmail,subject,content) #sendEmail(fromEmail,toEmail,subject,content) ###################################### return "OK"
def calendar_subscribe_view(request, calendar_id): cal = Calendar.objects.get(id=calendar_id) cal.subscribers.add(request.user) today = datetime.today() events = Event.objects.filter(calendar=cal, begin_date__gte = today) notifs = [] for event in events: try: guest = EventGuest.objects.get(user=request.user, event=event) except ObjectDoesNotExist: guest = EventGuest(user=request.user, event=event) finally: guest.save() action = EventAction(user=event.owned_by, event=event, type='c', date=today) notifs.append(action) notif_users = dict() notif_users[request.user.id] = notifs notifier.notify(notif_users, False) cal.save() return HttpResponseRedirect('/calendar/%s' % calendar_id)
def main(): parser = argparse.ArgumentParser() parser.add_argument( '-l', '--load', default=1.0, type=float, help="load threshold for notification") parser.add_argument( '-t', '--polltime', default=1.0, type=float, help="time between load checks") parser.add_argument( '-m', '--message', default="", type=str, help="message to include in notification") parser.add_argument( '-s', '--subject', default="Load threshold hit", type=str, help="subject to include in notification") parser.add_argument( '-e', '--email', default="", type=str, help="send notification to this email") parser.add_argument( '-v', '--verbose', default=False, action='store_true', help="enable verbose output") args = parser.parse_args() if args.verbose: print("Arguments: %s" % args) if args.email == "": raise Exception("Missing email: %s" % args.email) l = os.getloadavg()[0] while l > args.load: if args.verbose: print("Current load: %s" % l) time.sleep(args.polltime) l = os.getloadavg()[0] msg = 'Load fell below threshold %s' % args.load if args.message != '': msg += '\n' + args.message if args.verbose: print( "Sending notification[to %s]: %s, %s" % (args.email, args.subject, msg)) notifier.notify(msg, args.subject, args.email)
def callback(ch, method, properties, body): id = body[0:40] print " [x] Received %r" % (id,) notify_url = config.get('global', 'on_finish_image_post') try: im_proc = ImageProc(id, body[40:], config) except IOError: print "TODO: IOError: Meter esto en un log" notify(notify_url, id, False) return False for size in sizes: print " [x] Generating size %s" % (size.name) im = None for action in size.config['actions'].split(','): # Try to run the action as ImageProc method im = getattr(im_proc, action)(size, image=im) image_notify_url = size.config.get('on_finish_post', None) if image_notify_url: notify(image_notify_url, id, True, size.name) im_proc.save(size, im, id) print " [x] Finished %s at %s" % (id, datetime.datetime.now()) if notify_url: notify(notify_url, id, True)
def get_trakt_id(title, item_type): required_type = 'show' if item_type == 'episode' else 'movie' logger.debug('Searching cache.') trakt_id = trakt_cache[required_type].get(title) if trakt_id: return trakt_id logger.debug('Searching trakt.') results = search(title, [required_type]) if results is None: # Connection error return 0 # Dont store in cache elif results == [] or results[0]['score'] < 5: # Weak or no match logger.warning('Trakt search yielded no results.') notify('Trakt search yielded no results for ' + title) trakt_id = -1 else: trakt_id = results[0][required_type]['ids']['trakt'] trakt_cache[required_type][title] = trakt_id logger.debug(f'Trakt ID: {trakt_id}') write_json(trakt_cache, TRAKT_CACHE_PATH) return trakt_id
def fetch(self, retry_count=0): try: response = requests.get(self.source) except requests.ConnectionError as exc: logging.error('Cannot connect - Connection error %s' % exc.message) if retry_count >= 0: return self.fetch(retry_count=retry_count - 1) else: try: response.raise_for_status() except requests.HTTPError: if retry_count >= 0: return self.fetch(retry_count=retry_count - 1) else: return notifier.notify( 'Bad Response: HTTP %s' % response.status_code, response.content) else: self.update(response.json())
} #internship_loc = input("Where are you searching for an internship? ") # this is where I was able to enter the area to search for internship #url = 'https://www.monster.com/jobs/search/?q=Software-Developer-Intern&where='+internship_loc #monster job site url = 'https://www.monster.com/jobs/search/?q=Software-Developer-Intern&where=New-Jersey' page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') results = soup.find(id='ResultsContainer') internships = results.find_all('section', class_='card-content') for internship in internships: title = internship.find('h2', class_='title') company = internship.find('div', class_='company') location = internship.find('div', class_='location') tag = internship.find('a') if None in (title, company, location, tag): continue link = tag.get('href') #print(title.text.strip()) #print(company.text.strip()) #print(location.text.strip()) notify(title.text.strip(), company.text.strip(), location.text.strip(), link.strip()) #print()
def ping_servers(): for server_info in servers: server = MinecraftServer.lookup(server_info.ip) status = None try: status = server.status() except: server_info.is_online = False if status is not None: player_count = status.players.online max_players = status.players.max ping = int(round(status.latency)) player_info = "{}/{}".format(player_count, max_players) player_names = None if status.players.sample is not None: player_names = [s.name for s in status.players.sample] if player_names is not None and len(player_names) == 0: player_names = None server_version = status.version.name notification_fields = { "IP": server_info.ip, "Status": "Online", "Online": player_info, "Ping": str(ping) + "ms", "Versie": server_version } if player_names is not None: notification_fields["Spelers"] = ", ".join(player_names) if not server_info.is_online and player_count > 0: if player_count == 1: if player_names is not None: title = "{} is online met {}".format( server_info.name, ", ".join(player_names)) else: title = "{} is online met {} speler!".format( server_info.name, player_count) else: title = "{} is online met {} spelers!".format( server_info.name, player_count) short_desc = "{}ms - {} - {}".format( ping, server_info.ip, server_version) if player_names is not None: short_desc += " - " + ",".join(player_names) notifier.notify(notifier.Notification(title, [notifier.NotificationCard( "Info", "", notification_fields)], title, short_desc), "Minecraft") if player_count != server_info.player_count and server_info.is_online: diff = player_count - server_info.player_count if diff != 0: short_desc = "{} - {}ms - {}".format(player_info, ping, server_info.ip, server_version) if player_names is not None: short_desc += " - " + ",".join(player_names) title = None if player_count == 0: title = "Niemand meer online op {} :(".format( server_info.name) elif diff > 0: if diff == 1: title = "{} speler is {} gejoined!".format( abs(diff), server_info.name) else: title = "{} spelers zijn {} gejoined!".format( abs(diff), server_info.name) elif diff < 0: if diff == -1: title = "{} speler is {} geleaved!".format( abs(diff), server_info.name) else: title = "{} spelers zijn {} geleaved!".format( abs(diff), server_info.name) notifier.notify(notifier.Notification(title, [notifier.NotificationCard( "Info", "", notification_fields)], title, short_desc), "Minecraft") server_info.is_online = True server_info.player_count = player_count
import os import sys import time from client import create_client from notifier import notify PROJECT_ID = os.environ.get('PROJECT_ID') INSTANCES = os.environ.get('INSTANCES') if PROJECT_ID is None or INSTANCES is None: print( 'Please provide a PROJECT_ID and a comma-separated list of INSTANCES') sys.exit(1) notify('run') client = create_client() for instance in INSTANCES.split(','): client.post('/cloud/project/%s/instance/%s/snapshot' % (PROJECT_ID, instance), snapshotName=instance + '-' + time.strftime('%Y%m%d-%H%M%S')) print('Scheduled snapshot of instance %s' % instance) notify('complete') print('Finished scheduling the snapshots creation')
def notify_updates(updates): cancelled_updates = [] new_updates = [] changed_updates = [] for update in updates: if update.type == ChangeType.CANCELLED: cancelled_updates.append(update) elif update.type == ChangeType.NEW: new_updates.append(update) elif update.type == ChangeType.CHANGED: if notify_changes: changed_updates.append(update) else: print("Ignored changed appointment.") cards = [] if len(cancelled_updates) <= 3: for update in cancelled_updates: cards.append(cancelled_appointment_card(update.old_appointment)) else: cards.append( notifier.NotificationCard( "Er zijn {} vervallen lessen:".format(len(cancelled_updates)), "**Van de vakken:** " + format_subject_list( [u.old_appointment.subjects for u in cancelled_updates]) + "\n\n_Zie " + website + " voor meer info_", None)) if len(new_updates) <= 3: for update in new_updates: cards.append(new_appointment_card(update.new_appointment)) else: cards.append( notifier.NotificationCard( "Er zijn {} toegevoegde lessen:".format(len(new_updates)), "**Van de vakken:** " + format_subject_list( [u.new_appointment.subjects for u in new_updates]) + "\n\n_Zie " + website + " voor meer info_", None)) if len(changed_updates) <= 3: for update in changed_updates: cards.append( changed_appointment_card(update.old_appointment, update.new_appointment)) else: cards.append( notifier.NotificationCard( "Er zijn {} lessen zijn aangepast:".format( len(changed_updates)), "**Van de vakken:** " + format_subject_list( [u.new_appointment.subjects for u in changed_updates]) + "\n\n_Zie " + website + " voor meer info_", None)) if len(cards) == 0: return title_parts = [] cancel_desc = "" new_desc = "" change_desc = "" DESC_SEPERATOR = ". " if len(cancelled_updates) > 0: title_parts.append("{}x uitval".format(len(cancelled_updates))) cancel_desc = "➖ " + ", ".join( get_subject_abbrev_from_updates( cancelled_updates)) + DESC_SEPERATOR if len(new_updates) > 0: title_parts.append("{}x toegevoegd".format(len(new_updates))) new_desc = "➕ " + ", ".join( get_subject_abbrev_from_updates(new_updates)) + DESC_SEPERATOR if len(changed_updates) > 0: title_parts.append("{}x aangepast".format(len(changed_updates))) change_desc = "❔ " + ", ".join( get_subject_abbrev_from_updates(changed_updates)) + DESC_SEPERATOR part_len = math.floor( (64.0 - len(DESC_SEPERATOR) - 2.0) / len(title_parts)) cancel_desc = textwrap.shorten(cancel_desc, width=part_len, placeholder="..") new_desc = textwrap.shorten(new_desc, width=part_len, placeholder="..") change_desc = textwrap.shorten(change_desc, width=part_len, placeholder="..") short_title = "Rooster: " + ", ".join(title_parts) short_desc = cancel_desc + new_desc + change_desc update_notification = notifier.Notification( "Er zijn {} roosterwijzigingen".format(len(updates)), cards, short_title, short_desc) notifier.notify(update_notification, "Zermelo")
from analyzer import analyze from notifier import notify from downloader import download if __name__ == "__main__": CSV_URL = "https://firms.modaps.eosdis.nasa.gov/data/active_fire/viirs/csv/VNP14IMGTDL_NRT_South_America_24h.csv" data = download(CSV_URL) filtered_data = analyze(data) for data in filtered_data: notify(data, '*****@*****.**')
def update_notifier(): notify(False)
def update_notifier_true(): notify(True)
ui.error('Failed to get updates from %s\n' % api.name) ui.error(traceback.format_exc()) continue updates = [u for u in updates if u[0] not in seen] for notif in notifs: notifications.setdefault(notif, []).extend(updates) for u in updates: if u[0] not in notseen: notseen.append(u[0]) if not options.dry_run: util.addseen(seenpath, [u for u in notseen]) for name, updates in notifications.iteritems(): if not updates: continue notifierfn = notifiers.get(name) if not notifierfn: continue try: notifier = notifierfn(ui) except util.MissingConfigError, e: ui.info('missing configuration entry: %s\n' % str(e)) continue data = '\n'.join(('%s: %s (%s)' % (name, label, url)) for (sid, label, url) in updates) data = (data + '\n').encode('utf-8') ui.info(data) if not options.dry_run: notifier.notify(updates)