def ask( self, question: str, actions: dict, *, urgent: bool = False, image_url: str = None ) -> None: """Ask a question on Slack (with an optional image).""" self._interactive_command_actions = actions command_id = adler32(question.encode("utf-8")) attachments = [ { "fallback": "", "callback_id": "interactive_command_{0}".format(command_id), "actions": [ { "name": "{0}_{1}".format(command_id, action), "text": action, "type": "button", "value": action, } for action in actions ], } ] if image_url: attachments.append({"title": "", "image_url": image_url}) send_notification(self, "slack", question, data={"attachments": attachments})
def check_zank(): try: return zank.check_zank_loans() except: notification.send_notification("Exception in personal Automation", traceback.format_exc()) return traceback.format_exc()
def send_notify(self, content): title = self.douban.playingsong['title'] if self.has_cover: notification.send_notification(title, content, self.cover_file.name) else: notification.send_notification(title, content)
def _send_notification() -> None: """Send the notification.""" send_notification( self, "slack:@aaron", "Order a new Wolfie consumable: {0}".format(attribute), )
def forgot_password(): if request.method != 'POST': return redirect(url_for('index')) uid = request.form.get('uid', '') uid = ldap.filter.escape_filter_chars(uid) dn = f'cn={uid},ou=members,dc=flipdot,dc=org' try: ret = FlipdotUser().getuser(dn) if not ret: return render_template("error.html", message="User %s not found" % uid) mail = ret[1]['mail'][0] except FrontendError as e: return render_template("error.html", message="You triggered an error: " + str(e)) if not mail: return render_template("error.html", message="No email address found") print(f"Resetting password for {uid} {mail}") date = str(time.time()) dn_hmac = hmac.new(config.SECRET.encode(), (dn+date).encode(), hashlib.sha256).digest() dn_signed = dn + "|" + date + "|" + base64.b64encode(dn_hmac).decode().strip() msg = "Mit diesem Link kannst du dich einloggen und dein Passwort aendern:\n" \ "https://%s/login?%s\n" % (config.DOMAIN, urlencode({'token': dn_signed})) notification.send_notification(mail, "[flipdot-noti] Passwort-Reset", msg) print(msg) return render_template("error.html", message="You should have gotten a mail.")
def _send_notification() -> None: """Send a notification about the new version.""" send_notification( self, "slack:@aaron", f"New {self.args[CONF_APP_NAME]} Version: {new_version}", title="New Software 💿", )
def _send_notification(self) -> None: """Send notification to my love.""" send_notification( self, "ios_brittany_bachs_iphone", "His phone shouldn't be off wifi during the night.", title="Check on Aaron", )
def _send_bad_notification(): """Send a notification of bad AQI.""" send_notification( self, "presence:home", f"AQI is at {current_aqi}; consider closing the humidifier vent.", title="Poor AQI 😤", )
def _send_good_notification(): """Send a notification of good AQI.""" send_notification( self, "presence:home", f"AQI is at {current_aqi}; open the humidifer vent again.", title="Better AQI 😅", )
def _send_notification() -> None: """Send the notification.""" send_notification( self, ["person:Aaron", "person:Britt"], f'The security status has changed to "{new}"', title="Security Change 🔐", )
def slack_notification_2(self, event_name: str, data: dict, kwargs: dict) -> None: """Test a repeating Slack notification.""" send_notification(self, "slack:@aaron", "This is a test", when=self.datetime(), interval=15)
def send_email(payload, target_dir, pylint_output, pytest_output): """Sends an email with payload-, pylint-, and pytest content""" subject = '[{}] {} "{}"'.format(payload["repository"]["full_name"], target_dir, payload["commits"][0]["message"]) notification.send_notification('Subject: {}\n\n{}'.format( subject, str(pylint_output) + "\n" + str(pytest_output)))
def _send_notification() -> None: """Send the notification.""" send_notification( self, ["person:Aaron", "person:Britt"], "No one is home and the house isn't locked up.", title="Security Issue 🔐", data={"push": {"category": "dishwasher"}}, )
def delete(request, status_id): status = utils.get_object_by_id(Status, status_id) send_notification(status.author, 'status', status = status, category = 'DELETED' ) status.delete() return {}
def evo_weekly(output, budget): try: if output == 'console': log._print(evo.weekly_report_text(budget)) if output == 'email': notification.send_notification("EVO Weekly report", evo.weekly_report_html(budget)) except: exception_handler._handle_exception("Exception in EVO weekly report")
def _send_notification() -> None: """Send a notification about the new version.""" send_notification( self, "slack:@aaron", "New {0} Version: {1}".format(self.properties[CONF_APP_NAME], new_version), title="New Software 💿", )
def check_zank_loans(): zank = passwords.get_entry('zank') headers = { 'authority': 'www.zank.com.es', 'cache-control': 'max-age=0', 'origin': 'https://www.zank.com.es', 'upgrade-insecure-requests': '1', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36', 'sec-fetch-mode': 'navigate', 'sec-fetch-user': '******', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'sec-fetch-site': 'same-origin', 'referer': 'https://www.zank.com.es/', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'es-ES,es;q=0.9', 'cookie': '_ga=GA1.3.2060525521.1567941349; _gid=GA1.3.1510344404.1567941349; __utma=34198954.2060525521.1567941349.1567941350.1567941350.1; __utmc=34198954; __utmz=34198954.1567941350.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmt=1; _gat=1; PHPSESSID=gub6jbfh5uldtl8vh8hkul48vj; __utmb=34198954.10.9.1567941567563; _gali=_submit; __utmli=_submit', } data = { '_username': zank.username, '_password': zank.password } response_login = requests.post('https://www.zank.com.es/login_check', headers=headers, data=data) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Referer': 'https://www.zank.com.es/login', 'Connection': 'keep-alive', 'Upgrade-Insecure-Requests': '1', 'Cache-Control': 'max-age=0', 'TE': 'Trailers', } response = requests.get('https://www.zank.com.es/investor/listLoans', headers=headers, cookies=response_login.cookies) data = response.text dic_answer_loans = json.loads(data) added_loans = [] for loan in dic_answer_loans['data']: new_loan_id = str(loan['CreditoId']) stored_load = db_zank.get_lend_external_id(new_loan_id) if stored_load == None: added_loans.append(new_loan_id) db_zank.create_lend(new_loan_id) if len(added_loans) > 0: notification.send_notification("Personal Automation: "+ str(len(added_loans)) +" New loans", "There are " + str(len(added_loans)) + " new lends") return 'Sent email' else: return 'No new lends'
def person_notification_2(self, event_name: str, data: dict, kwargs: dict) -> None: """Test a single, scheduled person notification.""" send_notification( self, "person:Aaron", "This is a test", title="Yeehaw", when=datetime.now() + timedelta(seconds=30), )
def slack_notification_3(self, event_name: str, data: dict, kwargs: dict) -> None: """Test a repeating Slack notification that stops after 3 sends.""" send_notification( self, "slack", "This is a test", when=self.datetime(), interval=15, iterations=3, )
def _on_notify(self, kwargs: dict) -> None: """Schedule the next pickup notification.""" date, friendly_str = self.trash_manager.in_next_pickup_str() send_notification( self, "presence:home", friendly_str, title="Trash Reminder 🗑", when=datetime.datetime.combine(date - datetime.timedelta(days=1), datetime.time(20, 0, 0)), )
def _send_notification() -> None: """Send a notification.""" message = "The {0} has been left {1} for {2} minutes".format( self.get_state(self.entity_ids[CONF_ENTITY_ID], attribute="friendly_name"), self.properties[CONF_STATE], int(self.properties[CONF_DURATION]) / 60, ) send_notification(self, self.properties[CONF_NOTIFICATION_TARGET], message)
def _send_notification() -> None: """Send a notification.""" friendly_name = self.get_state(self.args[CONF_ENTITY_ID], attribute="friendly_name") send_notification( self, self.args[CONF_NOTIFICATION_TARGET], (f"{friendly_name} -> {self.args[CONF_STATE]} " f"({self.args[CONF_DURATION]} seconds)"), title="Entity Alert", )
def check(): global tries output = None try: output = pg.checkPG(s.login, s.password, s.link, s.look_for) if output > s.number_of_exercises and s.status: log('{} nowe zadania'.format(output)) spiner.Update(value=output) s.number_of_exercises = output ctr['_STATUS_'].Update(value='Nowe zadania! ({})'.format( s.number_of_exercises), text_color='red') przycisk.Update(button_color=('white', 'red')) if s.minimized: s.minimized = False tray.hide() ctr.un_hide() ctr.bring_to_front() if s.sound: alarmSound() if s.send_email: mailer.send_mail(s.where_to_email) if s.send_notification: notif.send_notification(s.private_key, s.device_ID, output - s.number_of_exercises) elif output == s.number_of_exercises: log('Brak nowych zadan') else: raise Exception(output) except Exception as err: log(err) if output == 'Failed to log: incorrect password': stop_checking() ctr.Element('_STATUS_').Update('Błędny login/hasło', text_color='red') winsound.PlaySound('SystemQuestion', winsound.SND_ALIAS | winsound.SND_ASYNC) tries = 0 return elif tries < 5: s.timer = Timer(10, check) tries += 1 else: ctr.Element('_STATUS_').Update('Błąd sprawdzania', text_color='red') s.timer = Timer(s.interval * 60, check) else: tries = 0 s.timer = Timer(s.interval * 60, check) finally: if s.status and not s.timer.is_alive(): #s.timer.cancel() s.timer.start()
def _handle_exception(msg="Exception in personal Automation"): """ Handles notification by looking at environment variable PA_EXCEPTIONS to decide the notification output channel. msg is the message of the exception. """ output = os.environ.get('PA_EXCEPTIONS', 'console') if output == 'console': log._print(traceback.format_exc()) if output == 'email': notification.send_notification(msg, traceback.format_exc())
def purge_varnish(url): '''Purge fires a request to provided URL with the method PURGE. PURGE is not a standard HTTP method url: URL on which a PURGE request will be fired ''' resp = requests.request("PURGE",url) if (resp.status_code/10)==20: return {"status":True,"response":"success"} else: send_notification(url, "varnish") return {"status":False, "response":resp.reason}
def post(self): action = {"createTask": "created", "updateTask": "updated", "deleteTask": "deleted"}.get(self.request.get('action')) name = self.request.get('name') ttype = self.request.get('type') priority = self.request.get('priority') status = self.request.get('status') validation = self.request.get('validation') submitterId = self.request.get('submitterId') assigneeId = self.request.get('assigneeId') effort = self.request.get('effort') projectId = self.request.get('projectId') description = self.request.get('description') notification.send_notification(self.request.get('taskId'), self.request.get('currentUUID'), action, name, ttype, priority, status, validation, submitterId, assigneeId, effort, projectId, description)
def check_reminders(): try: events = pickle.load(open("saved_protests.dat", "rb")) except: pickle.dump([], open("saved_protests.dat", "wb")) return if events: for event in events: if (notification.check_alert(event.date)): notification.send_notification(event.title, event.link) events.remove(event) pickle.dump(events, open("saved_protests.dat", "wb")) os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
def _on_lightning_detected(self, event_name: str, data: dict, kwargs: dict) -> None: """Respond to "LIGHTNING_DETECTED" events.""" with self._lock: if self._active: return send_notification( self, "presence:home", f"Lightning detected {data[CONF_DISTANCE]} miles away.", title="Lightning Detected ⚡️", ) self._active = True self.run_in(self._on_reset, self.args[CONF_LIGHTNING_WINDOW])
def init_notification(self): '''第一次桌面通知时加入图片''' old_title = self.douban.playingsong['title'] self.cover_file = tempfile.NamedTemporaryFile(suffix='.jpg', dir=self._tempdir) if not self.douban.get_pic(self.cover_file.name): return title = self.douban.playingsong['title'] if old_title != title: # 已切换至下一首歌 return self.has_cover = True content = self.douban.playingsong['artist'] + ' - ' \ + self.douban.playingsong['albumtitle'] notification.send_notification(title, content, self.cover_file.name)
def init_notification(self): '''第一次桌面通知时加入图片''' old_title = self.playingsong['title'] self.cover_file = tempfile.NamedTemporaryFile( suffix='.jpg', dir=self._tempdir) if not self.douban.get_pic(self.playingsong, self.cover_file.name): return title = self.playingsong['title'] if old_title != title: # 已切换至下一首歌 return self.has_cover = True content = self.playingsong['artist'] + ' - ' \ + self.playingsong['albumtitle'] notification.send_notification(title, content, self.cover_file.name)
def add_comment(request): form = forms.CommentForm(request.POST) if form.is_valid(): data = form.cleaned_data comment = Comment(status = form.status, body_text = data['body_text'], author = request.user ) comment.save() send_notification(form.status.author, 'comment', comment = comment ) else: raise exceptions.DataFieldMissed return {'object': comment}
def _start_notification_cycle(self) -> None: """Start the notification cycle.""" message = "The garage has been left open. Want to close it?" self.data[HANDLE_GARAGE_OPEN] = send_notification( self, ["person:Aaron", "person:Britt"], message, title="Garage Open 🚗", when=self.datetime(), interval=self.args[CONF_NOTIFICATION_INTERVAL], data={"push": { "category": "garage" }}, ) self.slack_app_home_assistant.ask( message, { "Yes": { "callback": self.security_manager.close_garage, "response_text": "You got it; closing it now.", }, "No": { "response_text": "If you really say so..." }, }, urgent=True, )
def _send_notification(): """Send the notification.""" self.data[notification_handle] = send_notification( self, "slack", f"{name} has low batteries ({value}%). Replace them ASAP!", when=self.datetime(), interval=self.args[CONF_NOTIFICATION_INTERVAL], )
def verify(request, status_id): status = utils.get_object_by_id(Status, status_id) action = request.POST.get('action', 'verify') or request.GET.get('action', 'verify') if action == 'verify': send_notification(status.author, 'status', status = status, category = 'VERIFIED' ) status.verify() elif action == 'reject': send_notification(status.author, 'status', status = status, category = 'REJECTED' ) status.reject() return {}
def updateevent(request): """ Update event venue or time and a notification is sent otherwise only it is changed =======Input=============== email event_id description date_time venue ========Output============== success message """ response = {} response['success'] = 0 if request.method == "POST": event_id = request.POST['event_id'] email = request.POST['email'] user = User.objects.get(username=email) if user.is_active and user.is_staff: event = Event.objects.get(id=event_id) old_venue = event.venue old_date_time = event.date_time if event.addedby == user: event.content.description = request.POST['description'] event.date_time = request.POST['date_time'] event.venue = request.POST['venue'] event.content.save() event.save() # sending notification in case the time or venue changed in the update. if event.date_time != old_date_time or event.venue != old_venue: users = UserEvents.objects.values_list( 'user__userprofile__mobile_id', flat=True).filter(event=event) print "list is------------------------ ", users ids = users if len(ids) > 0: notification.send_notification(event, ids) response['success'] = 1 else: response['message'] = "User did not create event" else: response['message'] = "User is not superuser" return JsonResponse(response)
def run(self): bug_url = self.task.get_title() # We only handle bug URL. When task's title is not a bug URL, stop # handling quietly. if bugURLPattern.match(bug_url) is None: return scheme, hostname, queries = self.parseBugUrl(bug_url) bug_id = queries.get('id', None) if bugIdPattern.match(bug_id) is None: # FIXME: make some sensable action instead of returning silently. return try: bugzillaService = BugzillaServiceFactory.create(scheme, hostname) except BugzillaServiceNotExist: # Stop quietly when bugzilla cannot be found. Currently, I don't # assume that user enters a wrong hostname or just an unkown # bugzilla service. return try: bug = bugzillaService.getBug(bug_id) except xmlrpclib.Fault, err: code = err.faultCode if code == 100: # invalid bug ID title = 'Invalid bug ID #%s' % bug_id elif code == 101: # bug ID not exist title = 'Bug #%s does not exist.' % bug_id elif code == 102: # Access denied title = 'Access denied to bug %s' % bug_url else: # unrecoganized error code currently title = err.faultString send_notification(bugzillaService.name, title)
def send_notify(self, content): title = self.playingsong['title'] if self.has_cover: notification.send_notification(title, content, self.cover_file.name) else: notification.send_notification(title, content)