Write a script in Shell and Python to notify you in Slack when the process is finished

background

Frequently at work, data acquisition, processing, and analysis execution are processed in the Linux environment of the server. You can check if the process is finished with ps on the terminal, but it is troublesome to check each time. I want to take prompt action when processing is broken. A common method is to detect by POSTing a message via email or SNS. Communication in Slack is the mainstream in my workplace.

Purpose

POST a message in Slack to determine if it's done.

Premise

It is assumed that you have already created a Slack account.

environment

Apps & Integrations to POST messages to Slack

There seem to be various Apps & Integrations in Slack. This time, I will summarize the methods of POSTing messages by the following two methods that are often seen on the Internet. Personally, I like "Incoming Web Hooks" because it has fewer required items and shorter code.

name Easy features
Slack Web API You can do various things
Incoming WebHooks Easy channel posting

How to get a token

Very easy. Log in to slack on the WEB and follow the steps below.

name Acquisition method
Slack Web API Create tokenpush.
・パスワード入力後、押したところにトークンが表示される。
Incoming WebHooks Select Post to Channel and Add Incoming WebHooks Integrationpush.
・Webhook URLの横にトークンが表示される。

Try to POST the message

Try POSTing a message with Shell and Python

Slack Web API Click here for a list of API methods (https://api.slack.com/methods). This time I want to POST the message, so I use the "chat.postMessage" method.

Parameter list

The list of parameters is here. The required items are as follows.

Parameter name Description
token token
text Text to post
channel Channel name
Encoded ID for direct messages

This time, we will create a sample using "token", "text", "channel", "username", and "link_names".

※ Caution If you want to POST a message to channel, there is no problem with "# ", but if you want to POST with a direct message, if you use "@ ", it will be POSTed to slackbot. As a solution, you need to specify "encoded ID". For the "encode ID" of your slack direct message list, press "Test Method" at here to display the list. The "id" of the response corresponds to the "encoded ID".

Shell

#Setting
TOKEN='<Obtained token>'
CHANNEL='<Channel name>'
USERNAME='test_username'
LINK_NAMES='1'
URL='https://slack.com/api/chat.postMessage'

# post
curl="curl -XPOST -d \"token=${TOKEN}\" \
    -d \"text=${TEXT}\" \
    -d \"channel=${CHANNEL}\" \
    -d \"username=${USERNAME}\" \
    -d \"link_names=${LINK_NAMES}\" \
    ${URL}"
eval ${curl}

Python

#Library import
import requests

#Setting
TOKEN='<Obtained token>'
CHANNEL='<Channel name>'
TEXT='test'
USERNAME='test_username'
URL='https://slack.com/api/chat.postMessage'

# post
post_json = {
    'token': TOKEN,
    'text': TEXT,
    'channel': CHANNEL,
    'username': USERNAME,
    'link_names': 1
}
requests.post(URL, data = post_json)

Incoming WebHooks Note that the POST method is slightly different from that of the Slack Web API.

Parameter list

The parameters are as follows. This time, create a sample using "text", "username", and "link_names".

Parameter name Required item Description
text Text to post
username Post username
icon_url URL in the profile image of the post
icon_emoji Emoji to put in the profile image of the post
link_names Mention
channel Channel name
attachments AttachmentsFill in the form

Shell

#Setting
URL='<Obtained token>'
TEXT='test_text'
USERNAME='test_username'
LINK_NAMES='1'

# post
curl="curl -X POST --data '{ \
    \"text\": \"${TEXT}\" \
    ,\"username\": \"${USERNAME}\" \
    ,\"link_names\" : ${LINK_NAMES}}' \
    ${URL}"
eval ${curl}

Python

#Library import
import requests
import json

#Setting
URL='<Obtained token>'
TEXT='test'
USERNAME='test_username'

# post
post_json = {
    'text': TEXT,
    'username': USERNAME,
    'link_names': 1
}
requests.post(URL, data = json.dumps(post_json))

Other

--The list of pictograms is listed here [http://qiita.com/koukun/items/ae673f2bae8f1525b6af)

reference

Recommended Posts

Write a script in Shell and Python to notify you in Slack when the process is finished
Use Heroku in python to notify Slack when a specific word is muttered on Twitter
Allow Slack to notify you of the end of a time-consuming program process
Notify Slack when the machine learning process running on GCP is finished
Process the files in the folder in order with a shell script
What to do if you get the error RuntimeError: Python is not installed as a framework when trying to use matplitlib and pylab in Python 3.3
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
Recursively get the Excel list in a specific folder with python and write it to Excel.
[Python] When you want to import and use your own package in the upper directory
Create a shell script to run the python file multiple times
Let's use AWS Lambda to create a mechanism to notify slack when the value monitored by CloudWatch is exceeded on Python
What to do when the value type is ambiguous in Python?
Write the test in a python docstring
Run the Python interpreter in a script
Creating a shell script to write a diary
How to use is and == in Python
How to write when you want to put a number after the group number to be replaced with a regular expression in re.sub of Python
[Introduction to Python] What is the difference between a list and a tuple?
How to write the correct shebang in Perl, Python and Ruby scripts
How to write a string when there are multiple lines in python
A shell script to make sure you don't forget the pipenv shell again
Notify using Notification Center when the execution environment is macOS in Python
How to automatically notify by phone when the python system is down
What is the fastest way to create a reverse dictionary in python?
[Python] What to do when PEP8 is violated in the process of importing from the directory added to sys.path
How to input a character string in Python and output it as it is or in the opposite direction.
[Xonsh] The Python shell is sharp and god
About the difference between "==" and "is" in python
The trick to write flatten concisely in python
How to notify a Discord channel in Python
Launch a shell while a Python script is running
[Python] Throw a message to the slack channel
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
Output timing is incorrect when standard (error) output is converted to a file in Python
[Python] What to check when you get a Unicode Decode Error in Django
Notify slack when the switch sales page is updated ~ slack bot development with python ③ ~
I didn't have to write a decorator in the class Thank you contextmanager
I created a script to check if English is entered in the specified position of the JSON file in Python.
A Python script that crawls RSS in Azure Status and posts it to Hipchat
Create a python script to check if the link at the specified URL is valid 2
When a file is placed in the shared folder of Raspberry Pi, the process is executed.
Consideration when you can do a good job in 10 years with Python3 and Scala3.
Let's understand the standard input / output of bash together and write a shell script.
Differences in behavior between append () and "+ =" operators when adding data to a list in Python
Created a Python library to write complex comprehensions and reduce in an easy-to-read manner
I want to write in Python! (2) Let's write a test
Create a python script to check if the link at the specified URL is valid
What to do when only the window is displayed and nothing is displayed in pygame Note
A memorandum to run a python script in a bat file
A convenient function memo to use when you want to enter the debugger if an error occurs when running a Python script.
Things to note when initializing a list in Python
What's in that variable (when running a Python script)
Write tests in Python to profile and check coverage
[Note] How to write QR code and description in the same image with python
I want to write a triple loop and conditional branch in one line in python
I want to write in Python! (3) Utilize the mock
How to check in Python if one of the elements of a list is in another list
Write a log-scale histogram on the x-axis in python
[Mac] A super-easy way to execute system commands in Python and output the results
When you want to plt.save in a for statement
It is easy to execute SQL with Python and output the result in Excel