-
-
Save karnauskas/a27f91ac83590c9eda4dc2c0bd7d8a77 to your computer and use it in GitHub Desktop.
Discord webhook with Python requests
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 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment