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.







Friday, June 17, 2022

How to execute different select queries at once in Oracle database using SQL*Plus command line?


 (SQL*Plus) is a command-line tool for accessing Oracle Database using a terminal.

It enables you to enter and execute SQL, PL/SQL, and SQL*Plus commands to do the following things.

  • Query, insert, and update data
  • Execute PL/SQL procedures
  • Examine table and object definitions
  • Develop and run batch scripts
  • Perform database administration


Friday, April 22, 2022

How to export data from Oracle database using SQL*Plus command line?


Oracle database is a collection of data which treated as a unit.  Oracle Database is the first database designed for enterprise grid computing which supports to connect hardware and software components on demand to meet the changing needs of businesses.


SQL*Plus is an interactive and batch command-line query tool that is installed with every Oracle Database installation. It can access through the following ways.

  • Command-line user interface
  • Windows Graphical User Interface (GUI)
  • iSQL*Plus web-based user interface


In this article, I am focusing on how can we interact with the Oracle database using the Command-line user interface.

Thursday, May 27, 2021

Introduction to Coreference Resolution in NLP


What is Natural Language Processing(NLP)?



Most probably you may have experience of using Google Home with voice commands or finding something on the internet using Siri on your iPhone. These are two practical applications built using NLP.


Natural Language Processing is a branch of Artificial Intelligence that makes it possible for computers to interpret, understand and manipulate human language. It tries to fill the gap between computer understanding and human communication. Speech recognition, spelling checking, keyword search, and many more techniques come under NLP.


Sunday, December 13, 2020

Working with WSO2 ESB sequence

What is Apache Synapse?


Apache Synapse is a lightweight and high-performance Enterprise Service Bus (ESB) which acts as a bridge between several applications. It uses Apache Axis2 as its underlying web services engine. Synapse is configured using a simple, XML-based configuration language.



Monday, August 31, 2020

Introduction to Quartz Scheduler

When  you are implementing new functionality in Java, you may have to run a task in one of the following ways.

  • daily at 8.00AM. 

  • after every 10 minutes.

  • only weekends.

  • once a month or year.



You need to use a scheduler to fulfil this requirement and you can select one of the following.

Sunday, June 14, 2020

How to add FHIR module into the OpenMRS Platform?

What is OpenMRS?




A few decades back,  all the medical reports of patients were recorded as paper records. It could not be easy to manage and had to spend more time when working on them. When modern technology came, Health Care Applications were created and used to effectively record and manage patient medical records. Some of the Health Care applications are created as free and open source applications. OpenMRS is one of the open-source EMR tools that have been developed and implemented since 2004. It is used by healthcare workers over 5,500 health facilities around the world including 169 countries.

Monday, May 25, 2020

What is FHIR?

FHIR is the abbreviation for Fast Healthcare Interoperability Resources. It provides a standard to exchange electronic healthcare records by defining data formats and resources. 

Monday, May 11, 2020

What is WSO2 ESB?


What is ESB?


An Enterprise Service Bus (ESB) is fundamentally a software architecture. It gives a communication system between mutually interacting software applications in a service-oriented architecture. It removes the point-to-point integration and integrates numerous applications together over a bus-like infrastructure. It will handle transforming and routing the messages according to their appropriate destinations.

Sunday, March 1, 2020

Getting Started with Maven

Since Ant, Maven, and Gradle are dominated in the JVM ecosystem as  Java build automation tools, you may be familiar with Maven If you have ever worked on a Java Project.

Let’s explore how these Java build automation tools evolved in the JVM ecosystem.

  • Apache Ant (“Another Neat Tool”) is a Java library which is used to automate the build processes for Java applications. Other than that it can be used for building non-Java applications.
  • Apache Maven is a build automation tool and also a dependency management tool. It is primarily used for Java applications. Maven also uses XML files the same as Apache Ant but in a much more manageable way.
  • Gradle is a dependency management and a build automation tool which was built upon the concepts of Ant and Maven.

In this article, I am going to discuss Maven as a dependency management tool. 



Monday, February 3, 2020

Glance over AWS re:Invent 2019


AWS re:Invent is one of the major learning conferences for global cloud computing community. It is hosted by Amazon Web Services. This event consists of keynote announcements, training, technical sessions, certification opportunities and many more. Last time it took place in Las Vegas, USA in December with over 75 launches and announcements of new services and features. 



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...