updateWallpaper.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/bin/python
  2. from time import sleep
  3. import argparse
  4. import os
  5. import shutil
  6. import certifi
  7. import urllib3
  8. import anyjson
  9. class BingWallpaperChanger:
  10. def __init__(self, saveDir, wallpaperCmd):
  11. self.saveDir = saveDir
  12. self.savePath = saveDir +"/wallpaper"
  13. self.wallpaperCmd = wallpaperCmd.replace("$PATH", self.savePath)
  14. self.lastUrl = None
  15. def setWallpaper(self):
  16. print("Setting new wallpaper")
  17. os.system(self.wallpaperCmd)
  18. def updateLatest(self):
  19. print("test")
  20. http = urllib3.PoolManager(
  21. cert_reqs='CERT_REQUIRED',
  22. ca_certs=certifi.where())
  23. jsonReq = http.request('GET', 'https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=en-US')
  24. if jsonReq.status != 200:
  25. print("bing.com not responding")
  26. exit()
  27. json = anyjson.deserialize(jsonReq.data.decode("utf-8"))
  28. for img in json["images"]:
  29. if img["url"] != self.lastUrl:
  30. try:
  31. os.makedirs(self.savePath)
  32. except FileExistsError:
  33. pass
  34. with http.request('GET', "https://www.bing.com/" +img["url"], preload_content=False) as r, open(self.savePath, 'wb') as outFile:
  35. shutil.copyfileobj(r, outFile)
  36. self.lastUrl = img["url"]
  37. return True
  38. return False
  39. return False
  40. def run(self, delay):
  41. while True:
  42. if self.updateLatest():
  43. self.setWallpaper()
  44. sleep(delay)
  45. if __name__ == '__main__':
  46. parser = argparse.ArgumentParser()
  47. parser.add_argument("--delay", default=30)
  48. parser.add_argument("--saveDir", default=os.environ["HOME"] +"/.local/share/bing")
  49. parser.add_argument("--wallpaperCmd", default="gsettings set org.gnome.desktop.background picture-uri file://$PATH")
  50. args = parser.parse_args()
  51. wallpaperChanger = BingWallpaperChanger(args.saveDir, args.wallpaperCmd)
  52. wallpaperChanger.run(int(args.delay) * 60)