Python send alert
50 Python code examples are found related to "
send alert".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: notifications.py From TheSpaghettiDetective with GNU Affero General Public License v3.0 | 6 votes |
def send_failure_alert_sms(printer, is_warning, print_paused): if not settings.TWILIO_ENABLED: LOGGER.warn("Twilio settings are missing. Ignored send requests") return if not printer.user.sms_eligible(): return to_number = printer.user.phone_country_code + printer.user.phone_number pausing_msg = '' if print_paused: pausing_msg = 'Printer is paused. ' elif printer.action_on_failure == Printer.PAUSE and is_warning: pausing_msg = 'Printer is NOT paused. ' msg = 'The Spaghetti Detective - Your print {} on {} {}. {}Go check it at: {}'.format( printer.current_print.filename or '', printer.name, 'smells fishy' if is_warning else 'is probably failing', pausing_msg, site.build_full_url('/')) send_sms(msg, to_number)
Example 2
Source File: internal.py From esdc-ce with Apache License 2.0 | 6 votes |
def send_alert(self, host, msg, priority=ZabbixBase.NOT_CLASSIFIED, include_signature=True): """Send alert by pushing data into custom alert items""" priority = int(priority) if not (self.NOT_CLASSIFIED <= priority <= self.DISASTER): raise ValueError('Invalid priority') item = self.CUSTOM_ALERT_ITEM if priority == self.NOT_CLASSIFIED: self.log(WARNING, 'Alert with "not classified" priority may not send any notification') else: item += str(priority) if include_signature: msg += ' \n--\n' + self.settings.SITE_SIGNATURE self.log(INFO, 'Sending zabbix alert to host "%s" and item "%s" with message "%s"', host, item, msg) return self._send_data(host, item, msg) # noinspection PyProtectedMember
Example 3
Source File: server.py From alertR with GNU Affero General Public License v3.0 | 6 votes |
def sendAlertSensorAlertsOff(self) -> bool: """ function that sends a sensor alert of to a alert client :return: """ sensorAlertsOffMessage = self._buildSensorAlertsOffMessage() # initiate transaction with client and acquire lock if not self._initiateTransaction("sensoralertsoff", len(sensorAlertsOffMessage), acquireLock=True): return False returnValue = self._sendAlertSensorAlertsOff(sensorAlertsOffMessage) self._releaseLock() return returnValue
Example 4
Source File: airflowfile.py From data-testing-with-airflow with Apache License 2.0 | 6 votes |
def send_slack_alert(context=None): """Send slack alert on failure to alert the team""" payload_vars = { 'url': 'your_slack_hook_url_here', 'run_id': str(context['run_id']), 'task': str(context['task']), 'dag_name': str(context['dag'].dag_id) } error_message = "{dag_name} Failure! Task failed: {task} Check log at: {run_id}".format(**payload_vars) payload_vars['json'] = """payload={{"channel":"ChuckNorris","text":"{0}"}}""".format(error_message) slack_cmd = """curl -x proxy:port \ -X POST \ --data-urlencode '{json}' \ {url}""".format(**payload_vars) slack_alert = BashOperator( task_id='slack_alert', dag=dag, bash_command=slack_cmd, ) slack_alert.execute(context)
Example 5
Source File: daily_alert.py From backtrader-cn with GNU General Public License v3.0 | 6 votes |
def send_daily_alert(): date = dt.datetime.now().strftime('%Y-%m-%d') msg = get_market_signal_by_date(date) # send notification via wechat wx_client = WeChatClient({ 'APP_ID': conf.WECHAT_APP_ID, 'APP_SECRET': conf.WECHAT_APP_SECRET, }) try: response = wx_client.send_all_text_message( json.dumps(msg, ensure_ascii=False)) logger.debug(response) except Exception as e: logger.error(e, exc_info=True)
Example 6
Source File: admin.py From pyconapac-2016 with MIT License | 6 votes |
def send_bankpayment_alert_email(modeladmin, request, queryset): messages = [] subject = u"PyCon APAC 2016 입금확인부탁드립니다. Please Check PyCon APAC 2016 payment" body = u""" 안녕하세요. PyCon APAC 준비위원회입니다. 현재 입금여부를 확인하였으나 입금이 되지 않았습니다. 혹시나 다른 이름으로 입금하신분은 support@pycon.kr 로 메일 부탁드립니다. 입금시한은 구매로부터 일주일입니다. 감사합니다. """ from_email = "pycon@pycon.kr" for obj in queryset: email = obj.email message = (subject, body, from_email, [email]) messages.append(message) send_mass_mail(messages, fail_silently=False)
Example 7
Source File: vibration.py From rpi-appliance-monitor with MIT License | 6 votes |
def send_alert(message): if len(message) > 1: logging.info(message) if len(pushover_user_key) > 0 and len(pushover_app_key) > 0: pushover(pushover_user_key, pushover_app_key, message, pushover_device, pushover_sound) if len(pushbullet_api_key) > 0: pushbullet(pushbullet_api_key, message) if len(pushbullet_api_key2) > 0: pushbullet(pushbullet_api_key2, message) if len(twitter_api_key) > 0: tweet(message) if len(slack_api_token) > 0: slack(message) if len (slack_webhook_url) > 0: slack_webhook(message) if len(iftt_maker_channel_key) > 0: iftt(message) if len(mqtt_topic) > 0: mqtt(message) if len(email_recipient) > 0: email(message) if len(telegram_api_token) > 0 and len(telegram_user_id) > 0: telegram(message)
Example 8
Source File: events.py From codo-cmdb with GNU General Public License v3.0 | 6 votes |
def send_alert(self): """ Aws Event发送告警 :return: """ events_list = self.get_instance_events() if not events_list: return False for event in events_list: acount_name = event.get('account_name') region = event.get('region') event_id = event.get('event_id') event_status = event.get('event_status') event_desc = event.get('event_desc') instance_id = event.get('instance_id') event_start_time = event.get('event_start_time') html_content = '[AwsEvents告警]\n\n名称:{acount_name}\n区域:{region}\n实例ID:{instance_id}\n事件状态:{event_status}\n事件ID:{event_id}\n开始时间(UTC):{event_start_time}\n\n事件描述:\n{event_desc}'.format( acount_name=acount_name, region=region, instance_id=instance_id, event_start_time=event_start_time, event_id=event_id, event_status=event_status, event_desc=event_desc) print(html_content) if 'Completed' not in html_content: self.send_mail(html_content)
Example 9
Source File: emailer.py From airflow-scheduler-failover-controller with Apache License 2.0 | 6 votes |
def send_alert(self, current_host, retry_count, latest_status_message, latest_start_message): self.logger.debug("Sending Email with Args - current_host: {current_host}, retry_count: {retry_count}, latest_status_message: {latest_status_message}, latest_start_message: {latest_start_message}".format(**locals())) if self.alert_to_email: try: self.email_backend( self.alert_to_email, self.email_subject, self.EMAIL_BODY.format(current_host, retry_count, latest_status_message, latest_start_message), files=None, dryrun=False ) self.logger.info('Alert Email has been sent') except Exception as e: self.logger.critical('Failed to Send Email: ' + str(e) + 'error') else: self.logger.critical("Couldn't send email since the alert_to_email config is not set")
Example 10
Source File: api.py From python-alerta-client with Apache License 2.0 | 6 votes |
def send_alert(self, resource, event, **kwargs): data = { 'id': kwargs.get('id'), 'resource': resource, 'event': event, 'environment': kwargs.get('environment'), 'severity': kwargs.get('severity'), 'correlate': kwargs.get('correlate', None) or list(), 'service': kwargs.get('service', None) or list(), 'group': kwargs.get('group'), 'value': kwargs.get('value'), 'text': kwargs.get('text'), 'tags': kwargs.get('tags', None) or list(), 'attributes': kwargs.get('attributes', None) or dict(), 'origin': kwargs.get('origin'), 'type': kwargs.get('type'), 'createTime': datetime.utcnow(), 'timeout': kwargs.get('timeout'), 'rawData': kwargs.get('raw_data'), 'customer': kwargs.get('customer') } r = self.http.post('/alert', data) alert = Alert.parse(r['alert']) if 'alert' in r else None return r.get('id', '-'), alert, r.get('message', None)
Example 11
Source File: main.py From Providence with BSD 3-Clause "New" or "Revised" License | 6 votes |
def send_alert(self, repo_patch, repo_commit, subject, offending_line): # Example method for sending alert whenever a rule is matched. url = repo_commit.url; filename = 'NOFILE' if repo_patch != None: filename = repo_patch.filename subject = self.EMAIL_ALERT_SUBJECT + " " + subject + ' in ' + repo_commit.identifier # skip if the alert is duplicate if url + filename + subject + offending_line == Plugin.last_alert: return # remember the current alert Plugin.last_alert = url + filename + subject + offending_line message = '<a href="' + url + '">' + url + '</a>'+\ '<br/><br/>OFFENDING LINE<br/>' + self.simple_html_encode(offending_line) +\ '<br/><br/>FILE NAME<br/>' + filename # email alert alert = Alert(message='', message_html=message, subject=subject, level=Alert.HIGH) email_recipients = [self.EMAIL_ALERT_RECIPIENTS] EmailAlert().send(alert, to_email=email_recipients)
Example 12
Source File: base.py From Providence with BSD 3-Clause "New" or "Revised" License | 6 votes |
def send_alert_email(self, from_email, to_email, subject, alert_message, repo_commit): # me == my email address # you == recipient's email address # Create the body of the message (a plain-text and an HTML version). url_html = "" if repo_commit and repo_commit.sha: #XXX: modify below to use config vars, #XXX: github.com/%s/%s/commit % (config.get('repos','github','owner'),...) url_html = "<A HREF='https://github.com/Pardot/pardot/commit/" + repo_commit.sha + "'>" + repo_commit.sha + "</A><br>" html = """ <html> <head></head> <body> """ + url_html + """ <pre><code>""" + cgi.escape(alert_message) + """ </pre></code> </body> </html> """ EmailAlert().send(Alert(subject=subject, message=body, message_html=html), to_email=to_email)
Example 13
Source File: alerts.py From netgrph with GNU Affero General Public License v3.0 | 5 votes |
def sendEmailAlert(group, nList, vlan=False): """Send group Network Alert from matched list""" if nglib.verbose: print("Emailing {0} New Network List Alert:\n {1}".format(group, str(nList))) emailAddress = nglib.config['NetAlertGroups'][group] fromAddress = nglib.config['NetAlert']['from'] mailServer = nglib.config['NetAlert']['mailServer'] subject = nglib.config['NetAlert']['subject'] if vlan: subject = nglib.config['NetAlert']['vlansubject'] nTable = "" for n in nList: nTable = nTable + "\n" + str(n) nTable = "<br />".join(nTable.split("\n")) contents = '<font face="Courier New, Courier, monospace">' + nTable + '</font>' msg = MIMEText(contents, 'html') msg['Subject'] = subject msg['From'] = fromAddress msg['To'] = emailAddress s = smtplib.SMTP(mailServer) s.sendmail(fromAddress, [emailAddress], msg.as_string()) s.quit() if nglib.verbose: print(emailAddress, fromAddress, subject, contents) # END
Example 14
Source File: core_file_processor.py From docker-stellar-core with Apache License 2.0 | 5 votes |
def send_alert(self, epoch_time, trace, logs): template_vars = { "hostname": self.hostname, "binary": self.config.get('Config', 'bin'), "formatted_time": format_time(epoch_time), "trace": trace, "logs": logs } sender = self.config.get('Config', 'from') recipient = self.config.get('Config', 'to') subject = 'stellar-core crash on %(hostname)s' % template_vars template = textwrap.dedent(""" <p>${binary} on ${hostname} crashed at ${formatted_time} with the following back traces:</p> <pre><code> ${trace} </code></pre> <h2>Extracted logs</h2> <pre><code> ${logs} </code></pre> """) body = Template(template).substitute(template_vars) logging.info("Sending core alert from %s to %s", sender, recipient) self.send_email(sender, recipient, subject, body)
Example 15
Source File: notifications.py From TheSpaghettiDetective with GNU Affero General Public License v3.0 | 5 votes |
def send_failure_alert_telegram(printer, rotated_jpg_url, is_warning, print_paused): if not printer.user.telegram_chat_id: return try: photo = requests.get(rotated_jpg_url).content except: photo = None action = '' button_list = ['more_info'] if print_paused: action = 'The print is paused.' button_list = ['cancel', 'resume', 'do_not_ask', 'more_info'] elif printer.action_on_failure == Printer.PAUSE and is_warning: action = 'Printer is NOT paused because The Detective is not very sure about it.' button_list = ['cancel', 'more_info'] notification_text = f"""Hi {printer.user.first_name or ''}, _The Spaghetti Detective_ spotted some suspicious activity on your printer *{printer.name}*. {action}""" try: send_telegram_notification(printer, notification_text, photo, buttons=button_list) except requests.ConnectionError as e: LOGGER.error(e)
Example 16
Source File: tasks.py From honeycomb with MIT License | 5 votes |
def send_alert_to_subscribed_integrations(alert): """Send Alert to relevant integrations.""" valid_configured_integrations = get_valid_configured_integrations(alert) for configured_integration in valid_configured_integrations: threading.Thread(target=create_integration_alert_and_call_send, args=(alert, configured_integration)).start()
Example 17
Source File: tasks.py From honeycomb with MIT License | 5 votes |
def create_integration_alert_and_call_send(alert, configured_integration): """Create an IntegrationAlert object and send it to Integration.""" integration_alert = IntegrationAlert( alert=alert, configured_integration=configured_integration, status=IntegrationAlertStatuses.PENDING.name, retries=configured_integration.integration.max_send_retries ) send_alert_to_configured_integration(integration_alert)
Example 18
Source File: send_all_england_alerts.py From openprescribing with MIT License | 5 votes |
def send_alert(bookmark, date): """Send alert for bookmark for given date.""" try: message = bookmark_utils.make_all_england_email(bookmark, tag=date) email_message = EmailMessage.objects.create_from_message(message) email_message.send() logger.info("Sent alert to %s about %s", email_message.to, bookmark.name) except bookmark_utils.BadAlertImageError as e: logger.exception(e)
Example 19
Source File: notifications.py From TheSpaghettiDetective with GNU Affero General Public License v3.0 | 5 votes |
def send_failure_alert_pushbullet(printer, rotated_jpg_url, is_warning, print_paused): if not printer.user.has_valid_pushbullet_token(): return pausing_msg = '' if print_paused: pausing_msg = 'Printer is paused.' elif printer.action_on_failure == Printer.PAUSE and is_warning: pausing_msg = 'Printer is NOT paused because The Detective is not very sure about it.' pb = Pushbullet(printer.user.pushbullet_access_token) title = 'The Spaghetti Detective - Failure alert!' msg = 'Your print {} on {} {}.'.format( printer.current_print.filename or '', printer.name, 'smells fishy' if is_warning else 'is probably failing') link = site.build_full_url('/') body = '{}\n{}\nGo check it at: {}'.format(msg, pausing_msg, link) try: file_url = None try: file_url = rotated_jpg_url if not ipaddress.ip_address(urlparse(file_url).hostname).is_global: pb.upload_file(requests.get(file_url).content, 'Detected Failure.jpg') except: pass if file_url: pb.push_file(file_url=file_url, file_name="Detected Failure.jpg", file_type="image/jpeg", body=body, title=title) else: pb.push_link(title, link, body) except (PushError, PushbulletError) as e: LOGGER.error(e)
Example 20
Source File: falldetect2.5.py From Fall-Detection with MIT License | 5 votes |
def send_alert(): global target_email sender = 'fallingdetection17@gmail.com' receiver = [target_email] message = """From: From Falling Detection <fallingdetection17@gmail.com> To: <czyapply@gmail.com> Subject: Fall Alert Accidental fall happens. Please help. """ try: session = smtplib.SMTP('smtp.gmail.com:587') session.ehlo() session.starttls() session.ehlo() session.login(sender,'czywrjzyj17') session.sendmail(sender,receiver,message) session.quit() print "Successfully sent email" except smtplib.SMTPException: print "Error: unable to send email" # Do analysis
Example 21
Source File: notifications.py From TheSpaghettiDetective with GNU Affero General Public License v3.0 | 5 votes |
def send_failure_alert_email(printer, rotated_jpg_url, is_warning, print_paused): if not settings.EMAIL_HOST: LOGGER.warn("Email settings are missing. Ignored send requests") return subject = 'Your print {} on {} {}.'.format( printer.current_print.filename or '', printer.name, 'smells fishy' if is_warning else 'is probably failing') ctx = { 'printer': printer, 'print_paused': print_paused, 'is_warning': is_warning, 'view_link': site.build_full_url('/printers/'), 'cancel_link': site.build_full_url('/prints/{}/cancel/'.format(printer.current_print_id)), 'resume_link': site.build_full_url('/prints/{}/resume/'.format(printer.current_print_id)), } send_email( user=printer.user, subject=subject, mailing_list='alert', template_path='email/failure_alert.html', ctx=ctx, img_url=rotated_jpg_url, )
Example 22
Source File: notifications.py From TheSpaghettiDetective with GNU Affero General Public License v3.0 | 5 votes |
def send_failure_alert(printer, is_warning=True, print_paused=False): LOGGER.info(f'Printer {printer.user.id} {"smells fishy" if is_warning else "is probably failing"}. Sending Alerts') if not printer.current_print: LOGGER.warn(f'Trying to alert on printer without current print. printer_id: {printer.id}') return (_, rotated_jpg_url) = save_print_snapshot( printer.current_print, last_pic_of_print(printer.current_print, 'tagged'), unrotated_jpg_path=None, rotated_jpg_path=f'snapshots/{printer.id}/{printer.current_print.id}/{str(timezone.now().timestamp())}_rotated.jpg') # Calls wrapped in individual try/except because anyone of them could fail, and we still want the flow to continue try: if printer.user.alert_by_email: send_failure_alert_email(printer, rotated_jpg_url, is_warning, print_paused) except: sentryClient.captureException() try: send_failure_alert_pushbullet(printer, rotated_jpg_url, is_warning, print_paused) except: sentryClient.captureException() try: send_failure_alert_telegram(printer, rotated_jpg_url, is_warning, print_paused) except: sentryClient.captureException() try: if printer.user.is_pro and printer.user.alert_by_sms: send_failure_alert_sms(printer, is_warning, print_paused) except: sentryClient.captureException() try: if printer.user.is_pro: send_failure_alert_slack(printer, rotated_jpg_url, is_warning, print_paused) except: sentryClient.captureException()
Example 23
Source File: alexa_communication.py From python-alexa-voice-service with MIT License | 5 votes |
def send_event_alert_name(self, name, token): """ API specific function that sends a event within the Alerts namespace. The response is not read in this function. :param name: name of event within the Alerts namesapce :param token: token for alert :return: the stream_id associated with the request """ header = { 'namespace': 'Alerts', 'name': name } payload = {'token': token} stream_id = self.send_event(header, payload=payload) return stream_id
Example 24
Source File: actions.py From golem with MIT License | 5 votes |
def send_text_to_alert(text): """Send text to an alert Parameters: text : value """ with _step("Send '{}' to alert".format(text)): get_browser().switch_to.alert.send_keys(text)
Example 25
Source File: smtp.py From alertR with GNU Affero General Public License v3.0 | 5 votes |
def sendCommunicationAlert(self, connectionRetries): if self.communicationAlertSent: return True subject = "[AlertR] (%s) Communication problems detected" \ % socket.gethostname() message = "Communication problems detected between the host '%s' " \ % socket.gethostname() \ + "and the server. The host '%s' was not able to establish " \ % socket.gethostname() \ + "a connection after %d retries." \ % connectionRetries emailHeader = "From: %s\r\nTo: %s\r\nSubject: %s\r\n" \ % (self.fromAddr, self.toAddr, subject) # sending eMail alert to configured smtp server logging.info("[%s]: Sending eMail alert to %s." % (self.fileName, self.toAddr)) try: smtpServer = smtplib.SMTP(self.host, self.port) smtpServer.sendmail(self.fromAddr, self.toAddr, emailHeader + message) smtpServer.quit() except Exception as e: logging.exception("[%s]: Unable to send eMail alert. " % self.fileName) return False # set flag that a communication alert was sent before exiting self.communicationAlertSent = True return True # this function sends an email in case of # a communication failure was cleared
Example 26
Source File: core.py From alertR with GNU Affero General Public License v3.0 | 5 votes |
def forceSendAlert(self) -> Optional[SensorAlert]: raise NotImplementedError("Function not implemented yet.") # This function decides if an update for this sensor should be sent # to the server. It is checked regularly and can be used to force an update # of the state and data of this sensor to be sent to the server. # # Returns an object of class StateChange if a sensor alert should be sent # or None.
Example 27
Source File: smtp.py From alertR with GNU Affero General Public License v3.0 | 5 votes |
def sendCommunicationAlertClear(self): if not self.communicationAlertSent: return True subject = "[AlertR] (%s) Communication problems solved" \ % socket.gethostname() message = "The communication problems between the host '%s' " \ % socket.gethostname() \ + "and the server were solved." emailHeader = "From: %s\r\nTo: %s\r\nSubject: %s\r\n" \ % (self.fromAddr, self.toAddr, subject) # sending eMail alert to configured smtp server logging.info("[%s]: Sending eMail alert to %s." % (self.fileName, self.toAddr)) try: smtpServer = smtplib.SMTP(self.host, self.port) smtpServer.sendmail(self.fromAddr, self.toAddr, emailHeader + message) smtpServer.quit() except Exception as e: logging.exception("[%s]: Unable to send eMail alert. " % self.fileName) return False # clear flag that a communication alert was sent before exiting self.communicationAlertSent = False return True
Example 28
Source File: models.py From cabot-alert-slack with MIT License | 5 votes |
def send_alert(self, service, users, duty_officers): alert = True slack_aliases = [] users = list(users) + list(duty_officers) slack_aliases = [u.slack_alias for u in SlackAlertUserData.objects.filter(user__user__in=users)] if service.overall_status == service.WARNING_STATUS: alert = False # Don't alert at all for WARNING if service.overall_status == service.ERROR_STATUS: if service.old_overall_status in (service.ERROR_STATUS, service.ERROR_STATUS): alert = False # Don't alert repeatedly for ERROR if service.overall_status == service.PASSING_STATUS: color = 'good' if service.old_overall_status == service.WARNING_STATUS: alert = False # Don't alert for recovery from WARNING status else: color = 'danger' c = Context({ 'service': service, 'users': slack_aliases, 'host': settings.WWW_HTTP_HOST, 'scheme': settings.WWW_SCHEME, 'alert': alert, }) message = Template(slack_template).render(c) self._send_slack_alert(message, service, color=color, sender='Cabot')
Example 29
Source File: monitor.py From loggrove with MIT License | 5 votes |
def send_alert(): ''' 发送报警 ''' while True: if ALERTING_QUEUE.empty() is False: webhook, content = ALERTING_QUEUE.get() try: payload = { 'msgtype': 'text', 'text': { 'content': content }, 'at': { 'isAtAll': True } } requests.post( webhook, data=json.dumps(payload), headers={'content-type': 'application/json'} ) except Exception as e: logging.error('send_alert error, %s' % (str(e))) else: logging.info('send_alert successful') else: time.sleep(5)
Example 30
Source File: nltk_core.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def send_alert(alert_type,alert_msg,extra_data_dict): """ For Sending Alerts to other modules based on fail or success """ alert_data = {"alert_type":alert_type,"alert_msg":alert_msg} if(len(extra_data_dict) > 0): alert_data.update(extra_data_dict) #return results return alert_data
Example 31
Source File: filtering.py From bot with MIT License | 5 votes |
def check_send_alert(self, member: Member) -> bool: """When there is less than 3 days after last alert, return `False`, otherwise `True`.""" if last_alert := await self.name_alerts.get(member.id): last_alert = datetime.utcfromtimestamp(last_alert) if datetime.utcnow() - timedelta(days=DAYS_BETWEEN_ALERTS) < last_alert: log.trace(f"Last alert was too recent for {member}'s nickname.") return False
Example 32
Source File: tasks.py From telemetry-analysis-service with Mozilla Public License 2.0 | 5 votes |
def send_run_alert_mails(): """ A Celery task that sends an email to the owner when a Spark job run has failed and records a datetime when it was sent. """ with transaction.atomic(): failed_run_alerts = ( SparkJobRunAlert.objects.select_for_update() .filter( reason_code__in=Cluster.FAILED_STATE_CHANGE_REASON_LIST, mail_sent_date__isnull=True, ) .prefetch_related("run__spark_job__created_by") ) failed_jobs = [] for alert in failed_run_alerts: with transaction.atomic(): failed_jobs.append(alert.run.spark_job.identifier) message = mail_builder.build_message( "atmo/jobs/mails/failed_run_alert.mail", {"alert": alert, "settings": settings}, ) message.send() alert.mail_sent_date = timezone.now() alert.save() return failed_jobs
Example 33
Source File: notify.py From AIT-Core with MIT License | 5 votes |
def send_text_alert(msg, recipients=None): '''''' if not recipients: recipients = ait.config.get('notifications.text.recipients', []) _send_email(msg, recipients)
Example 34
Source File: notify.py From AIT-Core with MIT License | 5 votes |
def send_email_alert(msg, recipients=None): '''''' if not recipients: recipients = ait.config.get('notifications.email.recipients', []) _send_email(msg, recipients)
Example 35
Source File: CloudTrailRemediation.py From aws-security-automation with Apache License 2.0 | 5 votes |
def sendAlert(data): """Placeholder for alert functionality. This could be Amazon SNS, SMS, Email or adding to a ticket tracking system like Jira or Remedy. You can also use a separate target using CloudWatch Event for alerts. Args: data (dict): All extracted event info. Returns: TYPE: String """ print "No alert" return 0
Example 36
Source File: utilities.py From opencraft with GNU Affero General Public License v3.0 | 5 votes |
def send_urgent_alert_on_permanent_deployment_failure(sender, **kwargs): """ Send an urgent alert to an e-mail when the deployment fails in a way that blocks the user. This is more urgent than the usual failure e-mails, and it's meant to go for instance to PagerDuty. This alert will only happen after ALL deployment attempts have been consumed, and ONLY if the deployment was triggered by the user (i.e. if the admins mass-redeploy 100 instances and 3 of them fail, this isn't critical and it doesn't trigger this e-mail).. """ instance = kwargs['instance'] appserver = kwargs['appserver'] # Only sending critical alerts for failures in registered clients' instances, not in test/sandboxes if not instance.betatestapplication_set.exists(): return if appserver is None and instance.provisioning_failure_notification_emails: logger.warning( "Sending urgent alert e-mail to %s after instance %s didn't provision", instance.provisioning_failure_notification_emails, instance, ) send_mail( 'Deployment failed at instance: {}'.format(instance), "The deployment of a new appserver failed and needs manual intervention. " "You can find the logs in the web interface.", settings.DEFAULT_FROM_EMAIL, instance.provisioning_failure_notification_emails, fail_silently=False, )
Example 37
Source File: email_alert.py From GitMAD with GNU General Public License v3.0 | 5 votes |
def send_alert(self, full_path, num_results, email_body): """Construct email message and send.""" message = MIMEMultipart() e_from = self.e_from e_to = self.e_to self.e_pw = self.e_pw[2:-1] password = base64.b64decode(self.e_pw) password = str(password, 'utf-8') f_name = os.path.basename(full_path) f_query = f_name.split("--")[2].replace('-','.').replace(".zip","") f_time = f_name.split("--")[1].replace("-",":") message['From'] = e_from message['To'] = e_to message['Subject'] = "There are " + str(num_results) + " results for query " + f_query + " at " + f_time body = 'Results for query: ' + f_query + '\n\n' tbl = PrettyTable(header_style='upper', padding_width=10, field_names=["Repo Author", "Repo Name", "Repo File", "Line - first 64 chars"]) for item in email_body: file_match = os.path.basename(item["Path"]) tbl.add_row([item["Repo Author"], item["Repo Name"], file_match, item["Line"].strip()[:68]]) body += str(tbl) message.attach(MIMEText(body, 'plain')) attachment = open(full_path, "rb") payload = MIMEBase('application', 'octet-stream') payload.set_payload((attachment).read()) encoders.encode_base64(payload) payload.add_header('Content-Disposition', "attachment; filename= %s" % f_name) message.attach(payload) send = smtplib.SMTP(self.e_domain, self.e_port) send.starttls() send.login(e_from, password) text = message.as_string() send.sendmail(e_from, e_to, text) send.quit()
Example 38
Source File: webelement.py From knitter with GNU General Public License v3.0 | 5 votes |
def AlertSendKeys(self, value): logger.step_normal("AlertSendKeys [%s]" % value) try: Browser.RunningBrowser.switch_to.alert.send_keys(value) Browser.RunningBrowser.switch_to.default_content() except Exception as e: logger.step_normal(e) logger.step_warning(str(sys.exc_info()))
Example 39
Source File: mail.py From Kairos with GNU General Public License v3.0 | 5 votes |
def send_alert_to_webhooks(data, webhooks, search_criteria='', batch_size=0, headers=None, headers_by_request=None): result = False try: batches = [] batch = [] for url in data: if len(batch) >= batch_size > 0: batches.append(batch) batch = [] symbol = data[url][0] alert = data[url][1] date = data[url][2] screenshots = data[url][3] screenshot = '' for chart in screenshots: if screenshot == '': screenshot = screenshots[chart] if len(search_criteria) == 0: batch.append({'date': date, 'symbol': symbol, 'alert': alert, 'chart_url': url, 'screenshot_url': screenshot, 'screenshots': screenshots}) else: for search_criterium in search_criteria: if str(alert).find(str(search_criterium)) >= 0: batch.append({'date': date, 'symbol': symbol, 'alert': alert, 'chart_url': url, 'screenshot_url': screenshot, 'screenshots': screenshots}) break # append the final batch if len(batch) > 0: batches.append(batch) # send batches to webhooks if len(batches) > 0: send_webhooks(webhooks, batches, headers, headers_by_request) except Exception as e: log.exception(e) return result
Example 40
Source File: admin.py From healthchecks with BSD 3-Clause "New" or "Revised" License | 5 votes |
def send_alert(self, request, qs): for check in qs: for channel in check.channel_set.all(): channel.notify(check) self.message_user(request, "%d alert(s) sent" % qs.count())
Example 41
Source File: alerts_sms_via_email.py From king-phisher-plugins with BSD 3-Clause "New" or "Revised" License | 5 votes |
def send_alert(self, alert_subscription, message): user = alert_subscription.user if not user.phone_carrier: self.logger.debug("user {0} has no cell phone carrier specified, skipping SMS alert".format(user.name)) return False if not user.phone_number: self.logger.debug("user {0} has no cell phone number specified, skipping SMS alert".format(user.name)) return False try: sms.send_sms(message, user.phone_number, user.phone_carrier) except Exception: self.logger.error("failed to send the SMS alert to {0} ({1} / {2})".format(user.name, user.phone_number, user.phone_carrier), exc_info=True) return False self.logger.debug("sent an SMS alert to user {0} ({1} / {2})".format(user.name, user.phone_number, user.phone_carrier)) return True
Example 42
Source File: send_alert.py From codo-tools with GNU General Public License v3.0 | 5 votes |
def send_alert(zabbix_url, webhook_url, messages): # 这里就是一个长期Token,管理员可以在用户列表选择一个用户进行生成一个长期Token, 但是需要对/tools/v1/zabbix/hooks/接口有权限 params = { "auth_key": "xxxx" } # payload = "{\"data\": \"test\"}" payload = {"zabbix_url": zabbix_url, "messages": messages} headers = {'content-type': "application/json", 'cache-control': "no-cache"} response = requests.post(url=webhook_url, data=json.dumps(payload), headers=headers, params=params) print(response.text)
Example 43
Source File: log.py From scrapydweb with GNU General Public License v3.0 | 5 votes |
def send_alert(self): if (self.flag and date.isoweekday(date.today()) in self.ALERT_WORKING_DAYS # date.isoweekday(datetime.now()) and datetime.now().hour in self.ALERT_WORKING_HOURS ): kwargs = dict( flag=self.flag, pages=self.NA if self.kwargs['pages'] is None else self.kwargs['pages'], items=self.NA if self.kwargs['items'] is None else self.kwargs['items'], job_key=self.job_key, latest_item=self.kwargs['latest_matches']['latest_item'][:100] or self.NA ) subject = u"{flag} [{pages}p, {items}i] {job_key} {latest_item} #scrapydweb".format(**kwargs) self.EMAIL_KWARGS['subject'] = subject self.EMAIL_KWARGS['content'] = self.json_dumps(self.email_content_kwargs, sort_keys=False) data = dict( subject=subject, url_stats=self.email_content_kwargs['url_stats'], url_stop=self.email_content_kwargs['url_stop'], when=self.get_now_string(True), ) if self.ENABLE_SLACK_ALERT: self.logger.info("Sending alert via Slack: %s", subject) _url = url_for('sendtextapi', opt='slack', channel_chatid_subject=None, text=None) self.get_response_from_view(_url, data=data) if self.ENABLE_TELEGRAM_ALERT: self.logger.info("Sending alert via Telegram: %s", subject) _url = url_for('sendtextapi', opt='telegram', channel_chatid_subject=None, text=None) self.get_response_from_view(_url, data=data) if self.ENABLE_EMAIL_ALERT: self.logger.info("Sending alert via Email: %s", subject) args = [ sys.executable, os.path.join(ROOT_DIR, 'utils', 'send_email.py'), self.json_dumps(self.EMAIL_KWARGS, ensure_ascii=True) ] Popen(args)
Example 44
Source File: alert.py From dcept with GNU General Public License v3.0 | 5 votes |
def sendAlert(message): if config.smtp_host: sendEmail(config.smtp_host, config.email_address, config.subject, message, config.smtp_port) if config.syslog_host: sendSyslog(config.syslog_host, message, 1, 4, config.syslog_port)
Example 45
Source File: tasks.py From promgen with MIT License | 5 votes |
def send_alert(sender, target, data, alert_pk=None): """ Send alert to specific target alert_pk is used when quering our alert normally and is missing when we send a test message. In the case we send a test message we want to raise any exceptions so that the test function can handle it """ logger.debug("Sending %s %s", sender, target) try: notifier = notification.load(sender) notifier._send(target, data) except ImportError: logging.exception("Error loading plugin %s", sender) if alert_pk is None: raise except Exception as e: logging.exception("Error sending notification") if alert_pk: util.inc_for_pk(models.Alert, pk=alert_pk, error_count=1) models.AlertError.objects.create(alert_id=alert_pk, message=str(e)) else: raise else: if alert_pk: util.inc_for_pk(models.Alert, pk=alert_pk, sent_count=1)
Example 46
Source File: TrapServer.py From WebTrap with BSD 3-Clause "New" or "Revised" License | 5 votes |
def send_alert_to_syslog(self, additional_data=None): logging_data_format = "Access To: %s\nServer Forensics Data:%s" server_forensics_data = self.get_forensics_data_from_request() logging_data = logging_data_format % ( self.path, server_forensics_data) if additional_data: logging_data += "\nAdditionalData:%s" logging_data = logging_data % (additional_data) alerts_logger = logging.getLogger(__name__) alerts_logger.info(logging_data)
Example 47
Source File: aquamonitor.py From Aquamonitor with GNU Lesser General Public License v3.0 | 5 votes |
def Send_alert(message): logger.info(message) # log the event if TEST_FLAG == 0: Send_email(message) Send_pushover(message) else: print(message)
Example 48
Source File: mail.py From Kairos with GNU General Public License v3.0 | 4 votes |
def send_alert_to_google_sheet(google_api_creds, data, name, sheet='', index=1, search_criteria=''): try: results = [] scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive'] credentials = ServiceAccountCredentials.from_json_keyfile_name(google_api_creds, scope) client = gspread.authorize(credentials) sheet = client.open(name).worksheet(sheet) limit = 100 if config.has_option('api', 'google_write_requests_per_100_seconds_per_user'): limit = config.getint('api', 'google_write_requests_per_100_seconds_per_user') inserted = 0 for url in data: symbol = data[url][0] alert = data[url][1] date = data[url][2] screenshots = data[url][3] [exchange, market] = symbol.split(':') screenshot = '' for chart in screenshots: if screenshot == '': screenshot = screenshots[chart] # noinspection PyBroadException try: setup = alert.split(',')[0] except Exception: setup = name timeframe = '' match = re.search("(\\d+\\s\\w+),", alert) if match: timeframe = match.group(1) row = [date, setup, timeframe, url, screenshot, exchange, market] if TEST: log.info(row) else: result = '' if len(search_criteria) == 0: result = sheet.insert_row(row, index, 'RAW') else: for search_criterium in search_criteria: if str(alert).find(str(search_criterium)) >= 0: result = sheet.insert_row(row, index) break if result: results.append(result) log.debug(str(result)) inserted += 1 if inserted == 100: log.info('API limit reached. Waiting {} seconds before continuing...' + str(limit)) time.sleep(limit) inserted = 0 if len(results) == 1: log.info(str(len(results)) + ' row inserted') else: log.info(str(len(results)) + ' rows inserted') except Exception as e: log.exception(e)
Example 49
Source File: notifications.py From TheSpaghettiDetective with GNU Affero General Public License v3.0 | 4 votes |
def send_failure_alert_slack(printer, rotated_jpg_url, is_warning, print_paused): if not printer.user.slack_access_token: return req = requests.get( url='https://slack.com/api/conversations.list', params={ 'token': printer.user.slack_access_token, 'types': 'public_channel,private_channel' }) req.raise_for_status() slack_channel_ids = [c['id'] for c in req.json()['channels'] if c['is_member']] for slack_channel_id in slack_channel_ids: msg = { "channel": slack_channel_id, "blocks": [ { "type": "section", "text": { "type": "mrkdwn", "text": f"*The Spaghetti Detective - Failure alert*\n\nYour print {printer.current_print.filename or ''} on {printer.name} {'smells fishy' if is_warning else 'is probably failing'}.\nThe printer is {'paused' if print_paused else 'NOT paused'}.\n<{site.build_full_url('/printers/')}|Check it out.>" } } ] } try: msg['blocks'].append( { "type": "image", "image_url": rotated_jpg_url, "alt_text": "Print snapshot" } ) except: pass req = requests.post( url='https://slack.com/api/chat.postMessage', headers={'Authorization': f'Bearer {printer.user.slack_access_token}'}, json=msg ) req.raise_for_status()
Example 50
Source File: tasks.py From honeycomb with MIT License | 4 votes |
def send_alert_to_configured_integration(integration_alert): """Send IntegrationAlert to configured integration.""" try: alert = integration_alert.alert configured_integration = integration_alert.configured_integration integration = configured_integration.integration integration_actions_instance = configured_integration.integration.module alert_fields = dict() if integration.required_fields: if not all([hasattr(alert, _) for _ in integration.required_fields]): logger.debug("Alert does not have all required_fields (%s) for integration %s, skipping", integration.required_fields, integration.name) return exclude_fields = ["alert_type", "service_type"] alert_fields = {} for field in alert.__slots__: if hasattr(alert, field) and field not in exclude_fields: alert_fields[field] = getattr(alert, field) logger.debug("Sending alert %s to %s", alert_fields, integration.name) output_data, output_file_content = integration_actions_instance.send_event(alert_fields) if integration.polling_enabled: integration_alert.status = IntegrationAlertStatuses.POLLING.name polling_integration_alerts.append(integration_alert) else: integration_alert.status = IntegrationAlertStatuses.DONE.name integration_alert.send_time = get_current_datetime_utc() integration_alert.output_data = json.dumps(output_data) # TODO: do something with successfully handled alerts? They are all written to debug log file except exceptions.IntegrationMissingRequiredFieldError as exc: logger.exception("Send response formatting for integration alert %s failed. Missing required fields", integration_alert, exc.message) integration_alert.status = IntegrationAlertStatuses.ERROR_MISSING_SEND_FIELDS.name except exceptions.IntegrationOutputFormatError: logger.exception("Send response formatting for integration alert %s failed", integration_alert) integration_alert.status = IntegrationAlertStatuses.ERROR_SENDING_FORMATTING.name except exceptions.IntegrationSendEventError as exc: integration_send_retries = integration_alert.retries if integration_alert.retries <= MAX_SEND_RETRIES \ else MAX_SEND_RETRIES # making sure we do not exceed celery max retries send_retries_left = integration_send_retries - 1 integration_alert.retries = send_retries_left logger.error("Sending integration alert %s failed. Message: %s. Retries left: %s", integration_alert, exc.message, send_retries_left) if send_retries_left == 0: integration_alert.status = IntegrationAlertStatuses.ERROR_SENDING.name if send_retries_left > 0: sleep(SEND_ALERT_DATA_INTERVAL) send_alert_to_configured_integration(integration_alert)