Skip to content

Instantly share code, notes, and snippets.

@s0lst1ce
Last active August 3, 2022 11:59
Show Gist options
  • Save s0lst1ce/a50f84eb0e5da22c7acc67543b47d164 to your computer and use it in GitHub Desktop.
Save s0lst1ce/a50f84eb0e5da22c7acc67543b47d164 to your computer and use it in GitHub Desktop.
APOD discord webhook
import requests
import json
webhook_url = "webhook_token"
apod_url = "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY"
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": "https://pbs.twimg.com/profile_images/19829782/apod_400x400.png",
"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
else:
embed["footer"].pop("text")
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"]
else:
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"]
else:
image_url = data["url"]
elif data["media_type"] == "video":
image_url = None
video_url = data["url"]
else:
raise ValueError("Media type was neither image nor video")
return title, description, timestamp, author, image_url, video_url
def post_to_discord(message):
res = requests.post(webhook_url, data=message, headers=headers)
def post_latest():
post = construct_post(*parse_apod(todays_pic()))
res = post_to_discord(post)
post_latest()
@s0lst1ce
Copy link
Author

s0lst1ce commented Aug 3, 2022

Naive discord webhook which posts the latest entry from https://apod.nasa.gov/ (requires python>=3.6 and requests).

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