Skip to content

Instantly share code, notes, and snippets.

@xjxckk
Last active June 17, 2024 06:30
Show Gist options
  • Save xjxckk/d967ab79dcb011cda9d2bf10734d7353 to your computer and use it in GitHub Desktop.
Save xjxckk/d967ab79dcb011cda9d2bf10734d7353 to your computer and use it in GitHub Desktop.
Discord webhook with Python requests
import requests, json
url = 'https://discord.com/api/webhooks/123/131232123' # Create webhook in your server integrations and copy webhook URL here
## Text only:
data = {
"content" : "Test webhook message"
}
result = requests.post(url, json=data)
## Text with local image:
files = {
'payload_json': (None, '{"content": "hello"}'), # None in this tuple sets no filename and is needed to send the text
'media': open('test.jpg', 'rb')
}
result = requests.post(url, files=files)
## Dynamic text with local image:
# Uses JSON dumps to stringify the dict with "" (if you use str() it will do it with '')
payload = {"content": caption}
files = {
'payload_json': (None, json.dumps(payload)), # None in this tuple sets no filename and is needed to send the text
'media': open('test.jpg', 'rb')
}
result = requests.post(url, files=files)
## Text with image from URL
image_url = 'https://i.redd.it/uv3jxuz6ds581.jpg'
response = requests.get(image_url)
image = response.content
# You must specify the file format when posting a file from URL.
# An image does not have to use the same format as the URL (URL is a .jpg but we will post it as a .png)
# Format can be changed to .mp4, .gif etc.
files = {
'payload_json': (None, '{"content": "hello"}'), # None in this tuple sets no filename and is needed to send the text
'media.png': image
}
result = requests.post(url, files=files)
## Check response:
print(result) # Code 204 (Success with empty response)
print(json.dumps(result.json(), indent=4)) # Format json response before printing
@TiNi27
Copy link

TiNi27 commented Sep 23, 2023

thanks

@FTSMAG
Copy link

FTSMAG commented Nov 22, 2023

It was very useful, thank you very much. I have been looking for this information for a very long time! You are a super person 👍 ^_^

@rukeba
Copy link

rukeba commented Jan 14, 2024

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment