Skip to content

Instantly share code, notes, and snippets.

@benediktkr
Last active April 6, 2022 13:33
Show Gist options
  • Save benediktkr/defab17e1b7be78df78e26efb53d1f4f to your computer and use it in GitHub Desktop.
Save benediktkr/defab17e1b7be78df78e26efb53d1f4f to your computer and use it in GitHub Desktop.
slack webhook in python
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
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