Skip to content

Instantly share code, notes, and snippets.

@lzambarda
Last active July 10, 2022 20:56
Show Gist options
  • Save lzambarda/15b7835d00a2c8dfbf30b673fc954960 to your computer and use it in GitHub Desktop.
Save lzambarda/15b7835d00a2c8dfbf30b673fc954960 to your computer and use it in GitHub Desktop.
Automatically set macOS desktop backgorund wallpaper image using pexels' APIs
#!/bin/bash
# This script can be launched at login time by creating an app wrapper with Automator.
# 1. open Automator
# 2. create a new application
# 3. search for and add "Run shell script"
# 4. either copy the code below or invoke it
# 5. save your new "app"
# 6. go to "System Preferences > Users & Groups > Login items" and add the new app
# Get yours from pexels
PEXELS_API_KEY=PLEASE_SET_ME
# The search term(s) you want to use for fetching images. Here we pick a random one every time.
TOPICS=(Nature Space Mountains Ocean)
TOPIC=${TOPICS[$(($RANDOM % ${#TOPICS[@]}))]}
res=$(system_profiler SPDisplaysDataType | grep Resolution: | grep -oE "([0-9]+ x [0-9]+)")
width=$(echo $res | grep -oE "^[0-9]+")
height=$(echo $res | grep -oE "[0-9]+$")
results=$(curl -sH "Authorization: $PEXELS_API_KEY" \
"https://api.pexels.com/v1/search?query=$TOPIC&orientation=landscape&size=medium&per_page=100")
ids=()
for idstr in $(echo $results | grep -oE '"id":[0-9]+'); do
ids+=($(echo $idstr | grep -oE "[0-9]+"))
done
id=${ids[$(($RANDOM % ${#ids[@]}))]}
url="https://images.pexels.com/photos/$id/pexels-photo-$id.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=$height&w=$width"
dst=$(mktemp)
#dst="/Users/lucazambarda/Desktop/test.jpeg"
curl -s -o $dst $url
osascript -e "tell application \"Finder\" to set desktop picture to POSIX file \"$dst\""
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment