Skip to content

Instantly share code, notes, and snippets.

@ronsen
Last active January 20, 2025 03:55
Show Gist options
  • Save ronsen/bc2df782e482e3de78adf70012058f5d to your computer and use it in GitHub Desktop.
Save ronsen/bc2df782e482e3de78adf70012058f5d to your computer and use it in GitHub Desktop.
Get the latest Bing wallpaper
#!/bin/python
import sys
import requests
import string
import os
import subprocess
from pathlib import Path
debug = True
url = "https://peapix.com/bing/feed?country=us"
pictures_dir = Path.home() / "pictures/bing"
pictures_dir.mkdir(parents=True, exist_ok=True)
def main(debug: bool):
response = requests.get(url)
if response.status_code == 200:
data = response.json()
image = data[0]
filename = image["date"].replace(
"-", "") + "-" + slug(image["title"]) + ".jpg"
path = pictures_dir / filename
if not path.exists():
resp = requests.get(image["imageUrl"])
if resp.status_code == 200:
with open(path, "wb") as file:
file.write(resp.content)
if (debug):
print(f"File dowloaded: {filename}")
else:
if (debug):
print(f"File exists: {filename}")
change_background(path)
else:
if (debug):
print(f"Failed to download from {url}")
def slug(title: str):
translator = str.maketrans("", "", string.punctuation)
title = title.translate(translator)
return title.replace(" ", "")
def detect_desktop_environment():
desktop_env = os.environ.get("XDG_CURRENT_DESKTOP") or os.environ.get(
"DESKTOP_SESSION"
)
if desktop_env:
return desktop_env.lower()
try:
processes = subprocess.check_output(
"ps -e", shell=True).decode("utf-8").lower()
if "gnome-session" in processes:
return "gnome"
elif "kded" in processes or "plasmashell" in processes:
return "kde"
elif "xfce4-session" in processes:
return "xfce"
elif "lxsession" in processes:
return "lxde"
elif "mate-session" in processes:
return "mate"
elif "cinnamon-session" in processes:
return "cinnamon"
except subprocess.CalledProcessError:
pass
return "unknown"
def change_background(image_path: str):
desktop_environment = detect_desktop_environment()
if desktop_environment == "xfce":
monitor = subprocess.getoutput(
"xfconf-query -c xfce4-desktop -l | grep last-image | head -n 1"
)
subprocess.run(
["xfconf-query", "-c", "xfce4-desktop",
"-p", monitor, "-s", image_path]
)
if desktop_environment == "gnome":
subprocess.run(
[
"gsettings",
"set",
"org.gnome.desktop.background",
"picture-uri",
f"file://{
image_path}",
]
)
def str_to_bool(s: str) -> bool:
if s.lower() in ['true', '1', 't', 'y', 'yes']:
return True
elif s.lower() in ['false', '0', 'f', 'n', 'no']:
return False
else:
return True
if __name__ == "__main__":
if len(sys.argv) > 1:
debug = str_to_bool(sys.argv[1])
main(debug)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment