python-3.xdbus

How to read notifications using D-Bus and Python 3


I was developing simple application, which reads notifications from D-Bus and does some stuff upon receiving it.

This turned out to be quite a headache so I am sharing my code with you all.


Solution

  • import gi.repository.GLib
    import dbus
    from dbus.mainloop.glib import DBusGMainLoop
    
    def notifications(bus, message):
        # do your magic
    
    DBusGMainLoop(set_as_default=True)
    
    bus = dbus.SessionBus()
    bus.add_match_string_non_blocking("eavesdrop=true, interface='org.freedesktop.Notifications', member='Notify'")
    bus.add_message_filter(notifications)
    
    mainloop = gi.repository.GLib.MainLoop()
    mainloop.run()