Last active
April 6, 2022 13:33
-
-
Save benediktkr/defab17e1b7be78df78e26efb53d1f4f to your computer and use it in GitHub Desktop.
slack webhook in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
# this file exists on mgmt control. reading from a file avoids having to | |
# template the token into the script. | |
with open('/usr/local/etc/slack_token') as f: | |
token = json.loads(f.read())['slack_token'] | |
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} | |
url = "https://hooks.slack.com/services/" + token | |
# simple way | |
payload = { | |
# optional | |
"icon_emoji": ":bob_ross:", | |
"username": "bob the bot", | |
"channel": "#support-python", | |
"text": "hello slack", | |
} | |
try: | |
r = requests.post(url, json=payload, headers=headers) | |
r.raise_for_status() | |
print(r.text) | |
except requests.exceptions.RequestException as e: | |
raise |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
# this file exists on mgmt control. reading from a file avoids having to | |
# template the token into the script. | |
with open('/usr/local/etc/slack_token') as f: | |
token = json.loads(f.read())['slack_token'] | |
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} | |
url = "https://hooks.slack.com/services/" + token | |
# alternative - adds a green bar next to the message | |
payload = { | |
'icon_emoji': ":bob_ross:", | |
'channel': '#support-python', | |
'username': "bob the bot", | |
# optional - adds a bar next to the message | |
'attachments': [{ | |
'text': "everything is fine i promise", | |
# the color of the bar | |
'color': 'good' | |
}], | |
# makes this optional (otherwise posts the text above the "attachment") | |
"text": "hello slack!", | |
} | |
try: | |
r = requests.post(url, json=payload, headers=headers) | |
r.raise_for_status() | |
print(r.text) | |
except requests.exceptions.RequestException as e: | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment