Need help creating a script to hide desktop widget when user is inactive

Hello everyone !!

I’m fresh new on linux (using Nobara) since 2 days.

i’m currently trying to create a script which will automatically hide desktop widget when there is no mouse (or keyboard) input for a determined time (in my case 5 seconds).

I very bad at coding so i’m using an AI to do most of the job but nothing it create actually works.

Bellow are the steps i’m supposed to do, along with the script;

1:

sudo dnf install python3-dbus python3-pip
pip install pydbus --user

2:

mkdir -p ~/scripts/
nano ~/scripts/toggle_plasma_widgets.py[test

SCRIPT

#!/usr/bin/env python3
import dbus
import time
from pydbus import SessionBus

— CONFIGURATION —

IDLE_THRESHOLD = 5000 # 5 secondes d’inactivité (ms)
CHECK_INTERVAL = 0.5 # Vérification toutes les 0.5s
LOCK_FILE = “/tmp/toggle_widgets.lock”

— FONCTION POUR ARRÊTER LE SCRIPT —

def kill_myself():
print(“[ERREUR] Arrêt du script.”)
try:
import os
os.remove(LOCK_FILE)
except:
pass
exit(1)

— VÉRIFIER SI ON DOIT TUER LE SCRIPT —

import os
if os.path.exists(LOCK_FILE):
print(“[INFO] Fichier lock détecté. Arrêt du script.”)
os.remove(LOCK_FILE)
exit(0)

— FONCTION POUR RÉCUPÉRER LE TEMPS D’INACTIVITÉ (KIdleTime API) —

def get_idle_time():
try:
bus = SessionBus()
kidletime = bus.get(‘org.kde.KIdleTime’, ‘/org/kde/KIdleTime’)
return kidletime.idleTime()
except Exception as e:
print(f"[ERREUR KIdleTime] {e}")
return 0

— FONCTION POUR MASQUER/AFICHER LES WIDGETS —

def toggle_widgets(hide):
try:
bus = SessionBus()
plasmashell = bus.get(‘org.kde.plasmashell’, ‘/PlasmaShell’)

    # Lister les widgets du bureau (location=1)
    widgets = bus.call_blocking(
        'org.kde.plasmashell',
        '/PlasmaShell',
        'org.kde.PlasmaShell',
        'plasmoidItems',
        '',
        signature='',
        reply_signature='a{sa{sv}}'
    )

    for widget_path, widget_props in widgets.items():
        if widget_props.get('location', 0) == 1:  # 1 = Desktop
            plasmashell.call_blocking(
                'org.kde.PlasmaShell',
                '/PlasmaShell',
                'org.kde.PlasmaShell',
                'setPlasmoidVisibility',
                'ssb',
                (widget_path, "hidden", hide),
                signature='ssb'
            )
except Exception as e:
    print(f"[ERREUR plasmoid] {e}")

— BOUCLE PRINCIPALE —

if name == “main”:
error_count = 0
max_errors = 3
while True:
idle_time = get_idle_time()
if idle_time == 0:
error_count += 1
print(f"[ERREUR] Impossible de récupérer idleTime (attempt {error_count}/{max_errors})")
if error_count >= max_errors:
kill_myself()
time.sleep(CHECK_INTERVAL)
continue
error_count = 0

    toggle_widgets(idle_time > IDLE_THRESHOLD)
    time.sleep(CHECK_INTERVAL)

3:

chmod +x ~/scripts/toggle_plasma_widgets.py

4:

~/scripts/toggle_plasma_widgets.py

On step 4 i get the following error:

[ERREUR KIdleTime] g-dbus-error-quark: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: The name is not activatable (2)
[ERREUR] Impossible to retreave idleTime (attempt 3/3)

Feel free to ask my for translation in the script :slight_smile:

(I’m on Nobara 44, KDE version ofc, and Linux 7.2.4)

thank you!

hi, welcome.

ah, the crux of the problem right there.

i would suggest first learning how to work python scripts on your own first (hello world) and maybe using AI to help you accomplish your programing goals, once you have had some success.

throwing the problem at AI and expecting it to work, is a good way to bork your system.

i hope at least you have a working set up backups in case you do.

From what I can see, ‘org.kde.KIdleTime’ is just an imaginary dbus endpoint your AI made up. KIdleTime is a c++ framework which isn’t accessible in your python script.

I did some quick research and it seems xprintidle is the python alternative (i’m might be wrong). Do you think that will work?

Hi! Yeah i get your point. I did some programming in high school so i have the fondamentals, even if i never really catch on it. Don’t worry i’m not copy-pasting everything mindlessly. I will try a least to modify this script by hand.

It’s not really a “python alternative”, but a cli tool that prints the idle time. It only works for X11 and I’d wager you’re probably running plasma in wayland (type kinfo in a cli and look under Graphics Platform to find out). It seems there exists a wayland port called wprintidle.
Either way, you’d first have to install either tool (probably involving compiling them yourself since they seem rather minor) and then you can use python’s subprocess module to run them and return the idle time.

That does seem kind of convoluted though, especially since your script will have to keep running and check this every few seconds.

hmm i see you think it will reduce my performances? I will at least try using wprintidle and see how it goes.

Actually, wprintidle works on zig and not on python from what i saw. Sway might be the way to go but it seems to be a very different tool. I will continue to look into that