Showing posts with label Monitoring Scripting Slack. Show all posts
Showing posts with label Monitoring Scripting Slack. Show all posts

Tuesday, July 18, 2023

How to send Slack notification using a Python script?

 In this article,  I am focussing on sending Slack notifications periodically based on the records in the database. Suppose we have to monitor table record count daily and send its status to a Slack channel.


Mainly this requirement has 3 parts.

  1. Get Slack API token to  access the Slack platform
  2. Implement python script
  3. Automate the Python script execution

Let’s focus on each part and learn what we need to do to fulfil each requirement.


Get API Token from Slack Integration Settings

Access tokens are the keys to access the Slack platform. Tokens tie together all the scopes and permissions your app has obtained, allowing it to read, write, and interact.

You need to follow up following steps to retrieve the API Token.


Step1:- Create Your Slack  account  and log in to the account

            https://app.slack.com/client/ 

Step 2 - Redirect the page to https://app.slack.com/apps to land on the “slack app directory”

Step 3 - Search “bots” in the Search Bar and Click on Bots.

                      Step 4 - You will be landed on the relevant Bot page
Step 5 - Click on “Add to Slack” and go to the new configuration page.

Step 6 - Add Username into the text field and click “Add bot integration”. Then the page will be redirected to the “edit configuration” page.
Step 7 -  You can take the API Token from here and it needs to call Slack notification API.


Create Python Script

According to this requirement, we need to access the database and execute a  query to retrieve the record count and then send a message.


The following Python script contains the required implementation to fulfil that.


#!/usr/bin/env python3


#import required dependencies

from slacker import Slacker

from datetime import datetime

from pymongo import MongoClient



import smtplib

import os

import psutil

import command

import sys

import pymongo



#Initiate Slacker

slack = Slacker('<your-slack-api-token-goes-here>')



# datetime object containing current date and time

now = datetime.now()

dt_string = now.strftime("%d/%m/%Y %H:%M:%S")


uri ="mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false"

 

#instantiate a mongo client 

client=MongoClient(uri)


#access the relevant DB schema

db = client["EShop"] 


#access the relevant DB collection

Transactions = db["Transactions"]


#execute the count query
transactionsCount = Transactions.count_documents({})

#compose the message
message= 'Monitoring date and time = ' + dt_string + "\n\n" + 'Transactions Count :' + str(transactionsCount)


print("Monitoring Status: ",message)

#Sent a message to the channel
slack.chat.post_message('testchan', message);



Automate the Python script execution



Crontab is a time-based job scheduler available in linux operating systems, It allows you to schedule and automate repetitive tasks to run at specific intervals or times.

These tasks can be anything from running scripts, executing commands, or running programs.You can open the crontab by ‘crontab -e’ command. If this is the first time you are using crontab,you may be prompted to choose an editor (e.g., nano, vim, etc.). Select your preferred editor and proceed.


Then add an entry to that file to automate the Python script execution.


Suppose I added an entry as follows.

30 15 * * * /usr/bin/python3 /var/data/Monitoring/scripts/transcationsMonitoringScript.py >> /var/data/Monitoring/logs/transactionMonitoring.log 2>&1


After making changes to the crontab file, save and exit the editor according to the editor.


This entry indicates that the script /var/data/Monitoring/scripts/transcationsMonitoringScript.py will be executed every day at 3:30 PM and related logs will be created on the /var/data/Monitoring/logs/transactionMonitoring.log file.


After completing all these steps, the notification service implemented using a Python script is ready to work as a cron job.

Slacker is a full-featured Python interface for the Slack API. For years it's been the most popular Python library for Slack and Eventually Slack decided to go with their library.


Nowadays the recommended approach is to use the requests library to make HTTP POST requests to the Slack API's webhook URL.







How to send Slack notification using a Python script?

 In this article,  I am focussing on sending Slack notifications periodically based on the records in the database. Suppose we have to monit...