def send_slack_notification(channel, channel_url, game, live_started_at, thumbnail_url, title, viewers): slack = Slack(url=config['webhook-url'].format(os.getenv('SLACK_API_KEY'))) slack.post( text='{} is live: {}'.format(channel, game), blocks=[{ 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*{} is live: {}*'.format(channel, game) } }, { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '<{url}|{channel}: {title}>\n{channel} now streaming "{game} - {title}" with {viewers} viewers ({time})' .format(url=channel_url, channel=channel, title=title, viewers=viewers, game=game, time=utc_to_local(live_started_at).strftime( '%d %b %Y at %H:%M')) }, 'accessory': { 'type': 'image', 'image_url': thumbnail_url, 'alt_text': 'Twitch thumbnail' } }])
def backup_not_found(): ls = subprocess.Popen(['ls', '-lt', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) head = subprocess.Popen(['head', '-11'], stdin=ls.stdout, stdout=subprocess.PIPE, text=True) tail = subprocess.Popen(['tail', '-10'], stdin=head.stdout, stdout=subprocess.PIPE, text=True) res = tail.communicate() message = """ Pi-Hole backup FAILED! Backup file not present. The 10 most recent files are thus: ```{}``` manual investigation is necessary. """.format(res[0]) slack = Slack(url=webhook) slack.post(text=message)
def send_slack_webhook_message(match, videogoal, videogoal_mirror, event_filter): try: webhooks = Webhook.objects.filter( destination__exact=Webhook.WebhookDestinations.Slack, event_type=event_filter) print( f"WEBHOOK - Checking {str(event_filter)} - {str(len(webhooks))} SLACK WEBHOOKS", flush=True) for wh in webhooks: to_send = check_conditions(match, wh) and \ check_link_regex(wh, videogoal, videogoal_mirror, event_filter) and \ check_author(wh, videogoal, videogoal_mirror, event_filter) if not to_send: continue message = format_event_message(match, videogoal, videogoal_mirror, wh.message) try: slack = Slack(url=wh.webhook_url) response = slack.post(text=message) print(response, flush=True) except Exception as ex: print("Error sending webhook single message: " + str(ex), flush=True) except Exception as ex: print("Error sending webhook messages: " + str(ex), flush=True)
def playbook_on_stats(self, stats): if stats.failures: message = "Failure" color = 'danger' else: message = "Success" color = 'good' execution_time = time.time()-self.start_time slack = Slack(url=webhook_url) message = "{}@{}\nPlaybook: {}".format(self.user, self.hostname, self.playbook_name) fields = [{ "title": "Start time", "value": "{}".format(self.start_datetime), "short": True },{ "title": "Execution time", "value": "{:10.2f}s".format(execution_time), "short": True }] for cat in ("ok","changed","unreachable","failures","skipped","rescued","ignored"): results = getattr(stats, cat, {}) found = False if results: for key in getattr(stats, cat, {}).keys(): found = True fields.append( { "title": cat.capitalize(), "value": "{}".format(getattr(stats, cat, {}).get(key)), "short": True } ) if not found: fields.append( { "title": cat.capitalize(), "value": "0", "short": True } ) self._display.warning(stats.__dict__) payload = [{ "fallback": "Ansible Play Recap for {}".format(self.playbook_name), "color": str(color), "title": "Ansible Play Recap : {}".format(self.playbook_name), "text": str(message), "fields": fields }] slack.post(attachments=payload)
def sendMessage(message): slack = Slack(url='https://hooks.slack.com/services/###') # Slack webhook slack.post( attachments=[{ "color": "#ff0000", #"fallback": "Plan a vacation", "author_name": "", "title": "Speedtest", "text": message }] )
def main(): quotes = download_quotes(target_url) quotes = remove_markdown_heading_spaces(quotes) quote = pick_quote_for_today(quotes) print("Quote of the day") print(quote) if slack_webhook_url is not None: slack = Slack(url=slack_webhook_url) slack.post(text=quote)
def handle(event, context): # Make sure to create the secrets below webhook_url = fetch_secret("slack-webhook-url") stripe.api_key = fetch_secret("stripe-secret-key") webhook_secret = fetch_secret("webhook-secret") payload = event.body received_sig = event.headers.get("Stripe-Signature", None) try: event = stripe.Webhook.construct_event( payload, received_sig, webhook_secret ) except ValueError: print("Error while decoding event!") return { "body": "Bad payload", "statusCode": 400 } except stripe.error.SignatureVerificationError: print("Invalid signature!") return { "body": "Bad signature", "statusCode": 400 } # Fail for all other event types if event.type != "charge.succeeded": return { "body":"Unsupported event type", "statusCode": 422 } amount = numbers.format_currency( event.data.object.amount / 100, event.data.object.currency.upper(), locale='en' ) try: slack = Slack(url=webhook_url) slack.post(text=f"You have a received a new payment of {amount} :moneybag: :tada:") except: print("An error occured when trying to send slack message.") return { "body": "Could not send slack message", "statusCode": 500 } return { "body": "Notification was sent successfully to Slack", "statusCode": 200 }
def sendSlack(self): self.set_globalSettings(self.defaultSettings, "SlackWebHook") if len(self.globalSettings.get("SlackWebHook")) > 0: lis = self.get_list(self.globalSettings.get("SlackWebHook")) try: for hooks in lis: text = self.subject+"\n\n"+self.body slack = Slack(url=hooks) slack.post(text=text) logger.info(f"Slack sent to: {hooks}") except Exception as ex: logger.info(ex)
def crawling(): with open('config.json', 'r') as f: config = json.load(f) time.sleep(random.choice(r_times)) html = requests.get( web_url, headers={ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36' }).text soup = BeautifulSoup(html, 'html.parser') result_text = soup.text[6:-2] a = json.loads(result_text) postList = a['result']['popularPostBlockInfoList'][0]['postList'] now = datetime.datetime.now() month = int(now.strftime('%m')) nowDate = now.strftime( (str(month) + '월%d일' ).encode('unicode-escape').decode()).encode().decode('unicode-escape') for post in postList: if nowDate in post['titleWithInspectMessage']: img_src = post['thumbnailList'][0]['encodedThumbnailUrl'] slack = Slack(url=config['WEBHOOK_URL']) today_menu = "쉐프스케치, " + "[" + nowDate + "] 오늘의 메뉴" slack.post( text=today_menu, channel="#오늘의메뉴", attachments=[{ # "fallback": href, # "pretext": href, "color": "#00FFFF", "author_name": "", "title": today_menu, # "title_link": href, "image_url": img_src, "thumb_url": img_src, # "actions": [ # { # "name": "action", # "type": "button", # "text": "Complete this task", # "style": "", # "value": "complete" # }, # ] }])
def success(message): slack = Slack(url=SLACK_WEBHOOK) slack.post(text=KST.strftime('%Y.%m.%d') + " 자가진단 결과: ✅ 성공", attachments=[{ "color": "#00b894", "author_name": "✅ " + KST.strftime('%Y.%m.%d'), "title": message, "text": "처리 기준 (KST): " + KST.strftime('%Y-%m-%d %H:%M:%S') }])
def failed(message): slack = Slack(url=SLACK_WEBHOOK) slack.post(text=KST.strftime('%Y.%m.%d') + " 자가진단 결과: ⛔️ 실패", attachments=[{ "color": "#d63031", "author_name": "⛔ " + KST.strftime('%Y.%m.%d'), "title": message, "text": "처리 기준 (KST): " + KST.strftime('%Y-%m-%d %H:%M:%S') }])
def send_alert(data): if config.send_telegram_alerts: tg_bot = Bot(token=config.tg_token) try: tg_bot.sendMessage(data['telegram'], data['msg'].encode('latin-1', 'backslashreplace').decode('unicode_escape'), parse_mode='MARKDOWN') except KeyError: tg_bot.sendMessage(config.channel, data['msg'].encode('latin-1', 'backslashreplace').decode('unicode_escape'), parse_mode='MARKDOWN') except Exception as e: print('[X] Telegram Error:\n>', e) if config.send_discord_alerts: try: webhook = DiscordWebhook(url="https://discord.com/api/webhooks/" + data['discord']) embed = DiscordEmbed(title=data['msg']) webhook.add_embed(embed) response = webhook.execute() except KeyError: webhook = DiscordWebhook(url="https://discord.com/api/webhooks/" + config.discord_webhook) embed = DiscordEmbed(title=data['msg']) webhook.add_embed(embed) response = webhook.execute() except Exception as e: print('[X] Discord Error:\n>', e) if config.send_slack_alerts: try: slack = Slack(url='https://hooks.slack.com/services/' + data['slack']) slack.post(text=data['msg']) except KeyError: slack = Slack(url='https://hooks.slack.com/services/' + config.slack_webhook) slack.post(text=data['msg']) except Exception as e: print('[X] Slack Error:\n>', e) if config.send_twitter_alerts: tw_auth = tweepy.OAuthHandler(config.tw_ckey, config.tw_csecret) tw_auth.set_access_token(config.tw_atoken, config.tw_asecret) tw_api = tweepy.API(tw_auth) try: tw_api.update_status(status=data['msg'].replace('*', '').replace('_', '').replace('`', '')) except Exception as e: print('[X] Twitter Error:\n>', e) if config.send_email_alerts: try: email_msg = MIMEText(data['msg'].replace('*', '').replace('_', '').replace('`', '')) email_msg['Subject'] = config.email_subject email_msg['From'] = config.email_sender email_msg['To'] = config.email_sender context = ssl.create_default_context() with smtplib.SMTP_SSL(config.email_host, config.email_port, context=context) as server: server.login(config.email_user, config.email_password) server.sendmail(config.email_sender, config.email_receivers, email_msg.as_string()) server.quit() except Exception as e: print('[X] Email Error:\n>', e)
async def scale_down(request): #authentication of requester to autoscaler global TOKEN if request.match_dict['token'] != TOKEN: print(f"token '{request.match_dict['token']}' not valid\n") return request.Response(text='ok') #authentication with Rancher pool = await get_nodepool() #setup slack webhook slack = Slack(url=SLACK_URL) #if we have reached the minimum number of nodes possible, end request if pool['quantity'] <= RANCHER_VM_MIN: print(f'quantity <= {RANCHER_VM_MIN}\n') slack.post(text="Autoscaler message: Not scaling down, quantity <= "+str(RANCHER_VM_MIN)) return request.Response(text='ok') # check if we have Cordoned node cordoned_node, message = await try_cordon_last_node_of_nodepool(pool['links']['nodes'], pool['hostnamePrefix']) print(f"{message}") if cordoned_node: print(f"Not scaling down, cordoning node instead. Waiting for next message...\n") slack.post(text="Autoscaler message: "+message+ "\nNot scaling down, Waiting for next message...") return request.Response(text='ok') #if we have reached here, scale down the node pool old = pool['quantity'] pool['quantity'] = pool['quantity'] - 1 print(f"scale down {old} --> {pool['quantity']}") slack.post(text="Autoscaler message: "+message+ "\nscale down "+str(old)+" --> "+str(pool['quantity'])) await set_nodepool(pool) return request.Response(text='ok')
async def scale_up(request): global TOKEN global RANCHER_VM_MAX #authentication of requester to autoscaler if request.match_dict['token'] != TOKEN: print(f"token '{request.match_dict['token']}' not valid\n") return request.Response(text='ok') #authentication with Rancher pool = await get_nodepool() # check if we have uncordoned a node uncordoned_node, message = await try_uncordon_node_of_nodepool(pool['links']['nodes']) print(f"{message}") slack = Slack(url=SLACK_URL) if uncordoned_node: print(f"Not scaling up, Waiting for next message...\n") slack.post(text="Autoscaler message: "+message+ "\nNot scaling up, Waiting for next message...") return request.Response(text='ok') old = pool['quantity'] pool['quantity'] = pool['quantity'] + 1 # limit maximum VMs if RANCHER_VM_MAX + 1 <= pool['quantity']: print(f"Not scaling up, at maximum number of nodes\n") slack.post(text="Autoscaler message: "+message+ "\nNot scaling up, at maximum number of nodes") return request.Response(text='ok') slack.post(text="Autoscaler message: "+message) print(f"scale up {old} --> {pool['quantity']}") await set_nodepool(pool) return request.Response(text='ok')
def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') slack_url = os.getenv('SLACK_URL') slack = Slack(url=(slack_url)) req_body = req.get_json() logging.info(format(req_body)) slack.post(text=f"system: {req_body['systemName']} \n" f"system model: {req_body['systemModel']} \n" f"current score: {req_body['currentScore']} \n" f"timestamp: {req_body['timestampIso8601']} \n" "description: {req_body['description']} \n" "resolution: {req_body['resolution']}") # slack.post(text=f"system: {req_body}") logging.info('Successfully posted to Slack.') return func.HttpResponse(format(req_body))
def initialize_g_vars(): global logger, es_client, slack_client, args logger = setup_logger() args = setup_args() es_client = Elasticsearch( ['{}:{}'.format(args.elasticsearch_url, args.elasticsearch_port)]) slack_client = Slack(url=args.slack_web_hook) logger.info('Global variables initialized succcessfully...')
def nfs_not_mounted(): # print('NFS not mounted') cmd = ['df', '-h'] res = subprocess.run(cmd, capture_output=True, text=True) message = """ Pi-Hole backup FAILED! Backup directory not present. the following is the output of `df -h`: ```{}``` manual investigation is necessary. """.format(res.stdout) slack = Slack(url=webhook) slack.post(text=message)
def _configure_slack(): config = get_config() slack_hook_url = config.get('slack', 'hookurl', fallback=None) if slack_hook_url: return Slack(url=slack_hook_url) else: print(f"warning: No Slack connection details found in configuration file") return None
def sendSlackNotify(event: eventData.ContEvent, data: dataData.ContData, config: configInit.Config): slackClient = Slack(url=config.slackUrl) imageIcon = logoIcons.getLogoUrl(event.image) mainInfo = f"_Docker Container Crashed Detected_\n\n:pirate_flag: *Container Name*\n `{event.name.capitalize()}`\n\n" introMsg = sectionWithImage(mainInfo, imageIcon) errorMsg = newSection(f"{data.errorMsg}\n") tagsField = None if config.tags is not None: tags = "" for t in config.tags: tags = tags + f"`{t}`; " tagsField = f":flags: *Tags*\n{tags}\n\n" tagsField = newSection(tagsField) restartPolicy = None if data.restartPolicy is not None: restartPolicy = f":repeat: *Restart Policy*: `{data.restartPolicy}`\n:repeat_one: *Max Count Restarts Notify*: `{config.restartPolicyCountNotify}`\n" restartPolicy = restartPolicy + f":arrows_counterclockwise: *Current Restart Count*: `{data.restartCount}`\n\n" restartPolicy = newSection(restartPolicy) image = f":frame_with_picture: *Image*\n`{event.image}`\n\n" image = newSection(image) exitCode = f":small_orange_diamond: *Exit Code*\n `{data.exitCode}`\n\n" exitCode = newSection(exitCode) oomKilled = f":anger: OOMKilled\n`{data.oomKilled}`\n\n" oomKilled = newSection(oomKilled) allFields = [introMsg, errorMsg, divider(), tagsField, restartPolicy, image, exitCode, oomKilled] filteredFields = [i for i in allFields if i] try: slackClient.post(blocks=filteredFields) except Exception as e: print(f"ERROR while sending message to Slack. Please check if the webhook URL is valid - now exiting! {e}") sys.exit(0)
def post(self): # Get name and email to send Slack logging.error("Send Slack Root") json_input = request.get_json() user_name_raw = json_input['user_name'] logging.error("raw : " + user_name_raw) user_email_raw = json_input['user_email'] logging.error("raw : " + user_email_raw) slack = Slack( url=f'https://hooks.slack.com/services/{config.slack_key}') slack.post( text= f"User : {user_name_raw} , email : {user_email_raw} have requested a demo" ) # return OK return "OK"
def send_slack_webhook_message(match, videogoal, videogoal_mirror, event_filter): try: webhooks = Webhook.objects.filter( destination__exact=Webhook.WebhookDestinations.Slack, event_type=event_filter) for wh in webhooks: to_send = check_conditions(match, wh) and \ check_link_regex(wh, videogoal, videogoal_mirror, event_filter) and \ check_author(wh, videogoal, videogoal_mirror, event_filter) if not to_send: return message = format_event_message(match, videogoal, videogoal_mirror, wh.message) try: slack = Slack(url=wh.webhook_url) response = slack.post(text=message) print(response) except Exception as ex: print("Error sending webhook single message: " + str(ex)) except Exception as ex: print("Error sending webhook messages: " + str(ex))
def backup_found(): ls = subprocess.Popen(['ls', '-lt', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) head = subprocess.Popen(['head', '-2'], stdin=ls.stdout, stdout=subprocess.PIPE, text=True) tail = subprocess.Popen(['tail', '-1'], stdin=head.stdout, stdout=subprocess.PIPE, text=True) res = tail.communicate() message = """ Pi-Hole backup SUCCEEDED! Backup file created. The most recent file is: ```{}``` Qapla'! """.format(res[0]) slack = Slack(url=webhook) slack.post(text=message)
def send_message(sender, instance, **kwargs): if kwargs['action'] != 'post_add': return result = '' for wh in instance.webhooks.all(): if wh.destination == Webhook.WebhookDestinations.Discord: try: webhook = DiscordWebhook(url=wh.webhook_url, content=instance.message) response = webhook.execute() result += wh.title + "\n" + str(response.content) + "\n\n" print(response.content, flush=True) except Exception as ex: print("Error sending webhook single message: " + str(ex), flush=True) result += wh.title + "\n" + str(ex) + "\n\n" elif wh.destination == Webhook.WebhookDestinations.Slack: try: slack = Slack(url=wh.webhook_url) response = slack.post(text=instance.message) print(response, flush=True) result += wh.title + "\n" + str(response) + "\n\n" except Exception as ex: print("Error sending webhook single message: " + str(ex), flush=True) result += wh.title + "\n" + str(ex) + "\n\n" CustomMessage.objects.filter(id=instance.id).update(result=result)
def send(self): webhook_url = self.get_destination() payload = self.get_messages() slack = Slack(url=webhook_url) if 'text' not in payload.keys(): expression = payload messages = 'text key not exist on payload input' raise InputExpression(expression, messages) elif 'attachments' not in payload.keys(): slack.post(text=payload['text']) else: slack.post(text=payload['text'], attachments=payload['attachments'])
def notify(self, message: str, changes_link: Optional[str]) -> None: """ Handle notification send through Slack webhooks. :param message: Message to send :type message: str :param changes_link: Link to the list of changes :type changes_link: Optional[str] """ try: # Every recipient is a slack webhook URL for hook in self.recipients: logging.debug('Sending to hook "%s"', hook) Slack(url=hook).post(text=message) logging.debug("Notification sent") except Exception as exc: raise NotificationSendError from exc
def publish_cluster(): slack= Slack(url='https://hooks.slack.com/services/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') credentials = key_read(file_loc) # Code for Redshift Task try: session = boto3.Session( aws_access_key_id=credentials['access_key'] , aws_secret_access_key=credentials['secret_key'], aws_session_token=credentials['token'] ) ddb = session.client('redshift', 'us-east-1') cluster_list = ddb.describe_clusters() slack.post(text="Describe Clusters Detail Successful") except: slack.post("Invalid Credentials or EC2 Role")
def lambda_handler(event, context): print('add current working directory to PATH') slack = Slack(url=os.environ['SLACK_WEBHOOK_URL']) os.environ['PATH'] = os.environ['PATH'] + ':' + os.path.dirname( os.path.abspath(__file__)) + ':' + os.path.join( os.path.dirname(os.path.abspath(__file__)), 'bin') try: mp3file_name = download() upload_to_s3(mp3file_name, os.environ['UPLOAD_GOOGLE_DRIVE_DIRECTORY']) upload_to_google_drive(mp3file_name, os.environ['UPLOAD_GOOGLE_DRIVE_DIRECTORY']) upload_to_youtube_music(mp3file_name) slack.post(text='[insideout] :tada: done recording insideout') except Exception as e: slack.post(text='[insideout] :red_circle: failed to record insideout') raise e # run radirec return { 'isBase64Encoded': False, 'statusCode': 200, 'headers': {}, 'body': '{"message": "Hello from AWS Lambda"}' }
def notify_slack(post): slack = Slack(url=os.environ.get('SLACK_URL')) slack.post(text=post)
from typing import Optional import requests import click from ratelimit import limits, sleep_and_retry from pydantic import BaseModel, HttpUrl from loguru import logger from rich.logging import RichHandler from slack_webhook import Slack # Set-up loggers logger.configure(handlers=[{ "sink": RichHandler(), "format": "<level>{message}</level>", }]) slack = Slack(url=os.environ["SLACK_HOOK"]) class CentreSante(BaseModel): """Centre de Sante in DoctoLib.""" ville: str name: str def url(self) -> HttpUrl: """Get the URL of the center.""" return f"https://www.doctolib.fr/centre-de-sante/{self.ville}/{self.name}" class Notification:
# # main processing loop # run_flag = RunFlag() # create and reset the relays relay1 = PiRelay.Relay("RELAY1") relay2 = PiRelay.Relay("RELAY2") relay3 = PiRelay.Relay("RELAY3") relay4 = PiRelay.Relay("RELAY4") sensor = initSensor() # env sensor logger = logAction(loc) # local logger # note: slackHook imported from creds.py slack = Slack(url=slackHook) # Initialize library. if (noDisplay is False): disp.begin() # Clear display. disp.clear() disp.display() # Create blank image for drawing. # Make sure to create image with mode '1' for 1-bit color. width = disp.width #width = 128 height = disp.height #height = 32