Architecture
[notification_slack.py] <--[comment]-- [run_and_notify.sh]
Prepare
- Python Environment
- Slack API Setting
Notification wih Python
notification_slack.py
import slack
import argparse
OAUTH_TOKEN = 'YOUR_SLACK_OAUTH_TOKEN'
CHANNEL_NAME = 'CHANNEL_NAME'
client = slack.WebClient(token=OAUTH_TOKEN)
parser = argparse.ArgumentParser(
prog='SlackMessenger',
description='A script to post a comment to a Slack channel',
epilog=f'This message will send to {CHANNEL_NAME}'
)
parser.add_argument('-c', '--comment', required=True, help='Comment to be posted')
args = parser.parse_args()
text_base = f'{args.comment}'
response = client.chat_postMessage(
channel=CHANNEL_NAME,
text=text_base
)
Run this command
sudo mv notification_slack.py /usr/bin/
sudo chmod +x /usr/bin/notification_slack.py
sudo bash -c "echo \"alias notify_slack='python3 /usr/bin/notification_slack.py'\" >> /etc/bash.bashrc"
/usr/bin/python3 -m pip install slack slackclient==2.9.4
source /etc/bash.bashrc
Usage
notify_slack -c 'Hello World!'
Shell script
run_and_notify.sh
#!/bin/sh
python3 /usr/bin/notification_slack.py -c "$1 will run!"
nohup $1 &
PID=$!
wait $PID
python3 /usr/bin/notification_slack.py -c "$1 was successful!"
Run this command
sudo mv run_and_notify.sh /usr/bin/
sudo chmod +x /usr/bin/run_and_notify.sh
sudo bash -c "echo \"alias run_notify='sh run_and_notify.sh'\" >> /etc/bash.bashrc"
source /etc/bash.bashrc
Usage
run_notify 'echo ThisIsTest'