Using Python & Bing to change a desktop wallpaper on Linux KDE

A small script which downloads an image of the day from Bing and sets the wallpaper on a Linux KDE.

The script carries out the following.

  1. Makes a request to Bing.com API (https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1) for the latest Image of the day

  2. Saves image to disk

  3. Connect to dbus and use the plasmashell dbus interface to set wallpaper

Bing returns a JSON object in the following format.

{
   "images":[
      {
         "startdate":"20190928",
         "fullstartdate":"201909282300",
         "enddate":"20190929",
         "url":"/th?id=OHR.ClavijoLandscape_EN-GB0019183029_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp",
         "urlbase":"/th?id=OHR.ClavijoLandscape_EN-GB0019183029",
         "copyright":"Autumnal landscape near the town of Clavijo in Spain's Rioja district (© Olimpio Fantuz/eStock Photo)",
         "copyrightlink":"https://www.bing.com/search?q=rioja+province+Spain&form=hpcapt&filters=HpDate%3a%2220190928_2300%22",
         "title":"Wine time",
         "quiz":"/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20190928_ClavijoLandscape%22&FORM=HPQUIZ",
         "wp":true,
         "hsh":"ec4aa405a92622ad1f44ae694fea60c9",
         "drk":1,
         "top":1,
         "bot":1,
         "hs":[

         ]
      }
   ],
   "tooltips":{
      "loading":"Loading...",
      "previous":"Previous image",
      "next":"Next image",
      "walle":"This image is not available to download as wallpaper.",
      "walls":"Download this image. Use of this image is restricted to wallpaper only."
   }
}

Python is used to parse the JSON object and download the image.

The code to connect to the dbus session is below.

def setwallpaper(filepath, plugin = 'org.kde.image'):
      jscript = """
      var allDesktops = desktops();
      print (allDesktops);
      for (i=0;i<allDesktops.length;i++) {
            d = allDesktops[i];
            d.wallpaperPlugin = "%s";
            d.currentConfigGroup = Array("Wallpaper", "%s", "General");
            d.writeConfig("Image", "file://%s")
      }
      """
      bus = dbus.SessionBus()
      plasma = dbus.Interface(bus.get_object('org.kde.plasmashell', '/PlasmaShell'), dbus_interface='org.kde.PlasmaShell')
      plasma.evaluateScript(jscript % (plugin, plugin, filepath))

I’ve added the script into ~/.config/autostart-scripts/ so that it starts on login.

The script is available on Gitlab here - https://gitlab.com/snippets/1942230

Last updated on 29 Sep 2019
Published on 29 Sep 2019