Last active
December 14, 2024 22:20
-
Star
(137)
You must be signed in to star a gist -
Fork
(33)
You must be signed in to fork a gist
-
-
Save devStepsize/b1b795309a217d24566dcc0ad136f784 to your computer and use it in GitHub Desktop.
POST a JSON payload to a Slack Incoming Webhook using Python requests
This file contains hidden or 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
''' | |
This is an example of how to send data to Slack webhooks in Python with the | |
requests module. | |
Detailed documentation of Slack Incoming Webhooks: | |
https://api.slack.com/incoming-webhooks | |
''' | |
import json | |
import requests | |
# Set the webhook_url to the one provided by Slack when you create the webhook at https://my.slack.com/services/new/incoming-webhook/ | |
webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX' | |
slack_data = {'text': "Sup! We're hacking shit together @HackSussex :spaghetti:"} | |
response = requests.post( | |
webhook_url, data=json.dumps(slack_data), | |
headers={'Content-Type': 'application/json'} | |
) | |
if response.status_code != 200: | |
raise ValueError( | |
'Request to slack returned an error %s, the response is:\n%s' | |
% (response.status_code, response.text) | |
) |
Hi, this is working example:
import requests
def send_slack_notif():
url = 'YOUR_SLACK_WEBHOOK_URL'
payload = {
"blocks": [
{
"type": "section",
"text": {
"type": "plain_text",
"text": ":red_circle: This is a plain text section block.",
"emoji": True
}
}
]
}
r = requests.post(url, json=payload)
send_slack_notif()
I want to format the code in the form of code.
```
slack_data = {
"text": "```\n" + message + "\n```"
}
response = requests.post(
url,
proxies={
"http_proxy": <proxy>,
},
json=slack_data,
headers={"Content-Type": "application/json"},
timeout=5,
)
print(response.text)
```
This does not format my code.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@rafaelnpaiva - I have this problem also.
You need to use the block strucutre that Slack is expecting: (found here)
I also need to send a simple JSON payload, and I really don't understand why there isn't a way to send our own key:value JSON block...I get that it won't nessasarily be pretty like Slack likes things to be... but sometimes we just need payloads.
@guymorrell do you have any ideas?