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.
- Get Slack API token to access the Slack platform
- Implement python script
- Automate the Python script execution
Get API Token from Slack Integration Settings
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
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
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.