Skip to content

Instantly share code, notes, and snippets.

@aaangeletakis
Last active October 10, 2017 14:18
Show Gist options
  • Save aaangeletakis/d069db669f625b844592f615df2deae2 to your computer and use it in GitHub Desktop.
Save aaangeletakis/d069db669f625b844592f615df2deae2 to your computer and use it in GitHub Desktop.
A python script to auto download the Bing image of the day
# -*- coding: UTF-8 -*-
from urllib2 import urlopen
from urllib2 import Request
from json import loads
from datetime import date
from os.path import expanduser
from os.path import isdir
from os import chdir
from os import makedirs
home = expanduser('~')
folder = "Pictures"
BBFolder = "%s/%s/BingDailyImages" % (home, folder) #change to "" if you don't care
LogPath = "%s/BING_BACK_LOG.txt" % (BBFolder)
today = date.today()
todaydate = "%s\%s\%s"%(today.month, today.day, today.year)
ImgJSON = ""
ImgURL = ""
ImgPath = ""
ImgN = ""
res = ""
def createFolder(path):
if isdir(path) is False:
makedirs(path)
return 0
else:
return 1;
def downloadPic(url, name):
with open(name,'wb')as f:
f.write(urlopen(url).read())
f.close()
def log(str):
with open(LogPath, "a+") as f:
try:
f.write("%s ERROR: %s"%(todaydate, string))
except:
f.close()
quit()
f.close()
quit()
createFolder("%s" %(BBFolder))
#make request to get the image json
req = Request("http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US")
try:
res = urlopen(req)
except URLError as e:
log("URLError -> %s" % e.reason)
except HTTPError as e:
log("HTTPError -> (CODE %s) %s"% (e.code, e.read()))
except OSError as e:
log("OSError -> %s" % e)
data = res.read()
#parse json to get the image url
ImgJSON = loads(data)
ImgPath = ImgJSON['images'][0]['url']
ImgURL = "http://www.bing.com%s"%(ImgPath)
#check if it is the right path
if ("/az/hprichbg/rb/" in ImgPath) is False:
log("String \'/az/hprichbg/rb/\' not in string \'%s\'" % (ImgPath))
ImgN = ImgPath.replace("/az/hprichbg/rb/", "")
todayfolder = "%s/%s" %(BBFolder, todaydate)
createFolder(todayfolder)
chdir(todayfolder)
#get image
downloadPic(ImgURL, ImgN)
#set as wall paper
# IDK how to do this cross platform
#if (call("gsettings set org.gnome.desktop.background picture-uri file:///%s/%s/%s" % (home, folder, ImgN), shell=True)) is False:
# log("Unable to exacute shell command \'gsettings set org.gnome.desktop.background picture-uri file:///%s/%s/%s\'"%(home, folder, ImgN))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment