aboutsummaryrefslogtreecommitdiff
path: root/apod-bot.sh
blob: 67e3a045a23ee88587648cb5182e6a4e392783af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#! /usr/bin/bash -e

# This work is in the public domain.
#
# It was completed by Arun I in 2016.
#
# Though you are not legally obliged to do so, I would appreciate it
# if you credit me for this work by not removing this notice, and
# hopefully linking to this project at
# https://git.systemreboot.net/nasa-apod-gnu-social-bot/about/
#
# To run this script, you will need jq, the command line JSON
# processor and pup, the command line HTML processor.

# Settings
social_api_url=https://social.systemreboot.net/api
bot_username=apod
bot_password=secret-password-here

apod_base_url=https://apod.nasa.gov/apod

# Download HTML page, and scrape required information
apod_html=$(curl -sS $apod_base_url/astropix.html)

title=$(echo "$apod_html" | pup 'center:nth-child(2) > b:nth-child(1) text{}' \
	       | sed -e 's/^ *//' -e 's/ *$//')
image_link=$apod_base_url/$(echo "$apod_html" | pup -p 'img attr{src}')
youtube_video_id=$(echo "$apod_html" | pup 'iframe attr{src}' | awk -F/ '{print $5}' | awk -F? '{print $1}')
youtube_link="https://www.youtube.com/watch?v=$youtube_video_id"
if [[ -z "$youtube_video_id" ]]
then
    media_link=$image_link
else
    media_link=$youtube_link
fi
date=$(echo "$apod_html" | pup ':contains("Discuss") attr{href}' | awk -F= '{print $2}')
page_link=$apod_base_url/ap$date.html

# Construct notice
notice="$title $page_link $media_link"

# Ensure we are not publishing a duplicate notice
previous_notice=$(curl -sSu "$bot_username:$bot_password" $social_api_url/statuses/home_timeline.json \
		      | jq -r '.[0] | .text')
if [[ "$notice" = "$previous_notice" ]]
then
    echo "Notice \"$notice\" already published. Aborting..." >&2
    exit 1
fi

# Check image and page links exist
wget --spider $media_link
wget --spider $page_link

# Publish notice
curl -sSu "$bot_username:$bot_password" --data-urlencode "status=$notice" \
     $social_api_url/statuses/update.json \
    | jq -r '"Published notice \"\(.text)\" on \(.created_at)"'