Skip to content

Instantly share code, notes, and snippets.

@coodoo
Last active April 20, 2021 08:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coodoo/1c793af1c5a28369fdaaa0ed9209f275 to your computer and use it in GitHub Desktop.
Save coodoo/1c793af1c5a28369fdaaa0ed9209f275 to your computer and use it in GitHub Desktop.
const fetch = require('node-fetch')
const fs = require('fs-extra')
const { execSync } = require('child_process')
const main = async () => {
const query = `nasa,cycling,surfing,underwater,swimming`
const size = `1`
const order = `latest`
const orientation=`landscape`
const photoName = 'photo.png'
//
const url = `https://api.unsplash.com/search/photos/?client_id=YOUR_KEY&query=${query}&per_page=${size}&order_by=${order}&orientation=${orientation}`
await fetch( url,
{
headers: {
'Content-Type': 'application/json',
},
})
.then(async (resp) => {
//
if (resp.ok === true) {
let result = await resp.json()
const { results } = result
const image_url = results[0].urls.full
//
await fetch(image_url)
.then(async (resp) => {
const buf = await resp.buffer()
fs.writeFileSync( photoName, buf )
})
.catch((err) => console.log('[fetch] 其它原因出錯', err))
} else {
const fail = await resp.text()
console.log(`[fetch] 失敗`, fail)
}
})
.catch((err) => console.log('[fetch] 其它原因出錯', err))
execSync(`wallpaper set ${__dirname}/photo.png`)
}
main()
@coodoo
Copy link
Author

coodoo commented Apr 19, 2021

使用方式:

  1. 下載此份程式並安裝它所需的 npm 套件(例如 node-fetchfs-extra)

  2. 先裝 wallpaper

$ brew install wallpaper

  1. 設定 crontab 每五分鐘跑此程式一次

*/5 5-17 * * * /usr/local/bin/node /full/path/to/folder/run.js

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