Skip to content

Instantly share code, notes, and snippets.

Last active August 3, 2022 11:59
What would you like to do?
APOD discord webhook
import requests
import json
webhook_url = "webhook_token"
apod_url = ""
headers = {
"Content-Type": "application/json",
embed_template = {
"title": "", # image title
"description": "", # description of the image
# "url": "", # url of the image
"color": 11768220,
"timestamp": "", # a YYYY-MM-DD timestamp
"footer": {
"icon_url": "",
"text": "", # copyright field on NASA's API (image's author)
def construct_post(title, description, timestamp, author, image_url, video_url):
embed = embed_template
embed["title"] = title
embed["description"] = description
embed["timestamp"] = timestamp
if author:
embed["footer"]["text"] = author
if image_url:
embed["image"] = {
"url": f"{image_url}"
} # f-strings because the json module is finicky and demands strings with double quotes (may be fixed in newer versions)
post = {"embeds": [embed]}
if video_url: # do note it shouldn't be possible to have both image and video
post["content"] = f"{video_url}"
return json.dumps(post).encode("utf-8")
def todays_pic():
res = requests.get(apod_url)
# we stop everything if the request failed or we can't parse the result (res) as JSON
# hence it is not necessary to gracefully handle exceptions
json_res = res.json()
if json_res["service_version"] != "v1":
raise ValueError("API version if not compatible")
return json_res
def parse_apod(data):
if "copyright" in data:
author = data["copyright"]
author = None
timestamp = data["date"]
title = data["title"]
description = data["explanation"]
if data["media_type"] == "image":
video_url = None
if "hdurl" in data:
image_url = data["hdurl"]
image_url = data["url"]
elif data["media_type"] == "video":
image_url = None
video_url = data["url"]
raise ValueError("Media type was neither image nor video")
return title, description, timestamp, author, image_url, video_url
def post_to_discord(message):
res =, data=message, headers=headers)
def post_latest():
post = construct_post(*parse_apod(todays_pic()))
res = post_to_discord(post)
Copy link

s0lst1ce commented Aug 3, 2022

Naive discord webhook which posts the latest entry from (requires python>=3.6 and requests).

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