make a post request to a discord webhook with an avatar in python

To send a post request to a discord webhook with an avatar in Python, you can use the requests library. Follow these steps:

  1. Import the requests module:
main.py
import requests
16 chars
2 lines
  1. Create a variable to store the URL of the webhook:
main.py
webhook_url = "https://discord.com/api/webhooks/WEBHOOK_ID/TOKEN"
66 chars
2 lines

Replace WEBHOOK_ID with the ID of your webhook, and TOKEN with the token of your webhook.

  1. Create a dictionary that contains the payload you want to send to the webhook:
main.py
payload = {
    "content": "Hello, world!",
    "avatar_url": "https://example.com/avatar.png"
}
97 chars
5 lines

Replace Hello, world! with the message you want to send, and https://example.com/avatar.png with the URL of the avatar you want to send.

  1. Send the post request using the requests.post() method:
main.py
response = requests.post(webhook_url, json=payload)
52 chars
2 lines

The json parameter is used to pass the payload as a JSON object.

  1. Check the response status code to make sure the request was successful:
main.py
if response.status_code == 204:
    print("Message sent successfully")
else:
    print("Error sending message")
112 chars
5 lines

Here's the complete code:

main.py
import requests

webhook_url = "https://discord.com/api/webhooks/WEBHOOK_ID/TOKEN"

payload = {
    "content": "Hello, world!",
    "avatar_url": "https://example.com/avatar.png"
}

response = requests.post(webhook_url, json=payload)

if response.status_code == 204:
    print("Message sent successfully")
else:
    print("Error sending message")
347 chars
16 lines

gistlibby LogSnag