Reddit instead of fortune(1)
Latest update:
The idea of fetching some Reddit post titles to print them randomly
in the terminal dates back to at least 2016. Taking the feed
from /r/showerthoughts subreddit, for example, one could place the
following script into his .bash_login
or elsewhere:
It's a slightly naïve 3-liner that tries to protect itself from 429
that Reddit frequently returns, in which case the script gracefully
outputs nothing. w3m is required to convert &
& friends into
their corresponding symbols.
The 1st enhancement here would be to cache the JSON. The enterprise
approach is to set up a cron job that saves the data into a temporary
file &, if that operation succeeds, renames it into a well known (by
the script that parses the JSON) path.
The mickey mouse way is to check the mtime of the previously saved
JSON & delete the file once it becomes too old.
The 2nd enhancement would be to fetch multiple subreddits & merge them
together.
A relatively small makefile can handle all this:
$ cat reddit-wisdom
#!/usr/bin/make -sf
r := showerthoughts CrazyIdeas oneliners
update := 600
wits := /tmp/reddit-wisdom/all.txt
age := $(shell expr `date +%s` - `date -r $(wits) +%s 2>/dev/null || echo 0`)
$(shell [ $(age) -gt $(update) ] && rm -f /tmp/reddit-wisdom/*)
all: $(wits)
sort -R < $< | head -1 | w3m -dump -T text/html
$(wits): $(patsubst %, /tmp/reddit-wisdom/%.json, $(r))
jq -r '.data?.children[]?.data | "\"\(.title)\" -- \(.author)" | gsub("\\n"; " ")' $^ > $@
/tmp/reddit-wisdom/%.json:
mkdir -p $(dir $@)
echo Fetching r/$*
curl -sf 'https://www.reddit.com/r/$*/top.json?sort=top&t=week&limit=100' > $@
.DELETE_ON_ERROR:
It considers remote data stale if it's older that 600 seconds. I think
it's safe to increase the value to at least 48 hours.
Note that the default subreddits might include NSFW content.
$ ./reddit-wisdom
Fetching r/showerthoughts
Fetching r/CrazyIdeas
Fetching r/oneliners
"The shovel was a ground breaking invention." -- EndersGame_Reviewer
$ ./reddit-wisdom
"Name your daughters Elle and Noelle" -- EmpireStrikes1st
Tags: ойті
Authors: ag