使用 DBus 监听传入的 libnotify 通知

man*_*ine 9 libnotify python

我正在尝试通过 espeak 过滤每个通知。但是,我似乎找不到从 python 脚本中获取通知正文的方法,甚至找不到要收听的信号名称。

bus.add_signal_receiver(espeak,
                    dbus_interface="org.freedesktop.Notifications",
                    signal_name="??")
Run Code Online (Sandbox Code Playgroud)

尝试为此使用谷歌似乎只会产生涉及创建新通知的结果,所以我现在完全迷失了。

任何人都可以帮助我吗?

简而言之,我想要的是使用python监听传入的通知,并获取通知的“body”属性。

小智 13

为了保持最新:从 dbus 1.5.something 添加匹配字符串时需要一个额外的参数,bus.add_match_string_non_blocking以确保我们收到所有内容。

结果代码如下:

import glib
import dbus
from dbus.mainloop.glib import DBusGMainLoop

def notifications(bus, message):
    print [arg for arg in message.get_args_list()]

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 = glib.MainLoop()
mainloop.run()
Run Code Online (Sandbox Code Playgroud)

  • 在我的 Python 安装(Python 3、Ubuntu)上,我需要 `from gi.repository import GLib as glib` 来完成这项工作。 (4认同)

Mes*_*ion 6

通知是指某些软件发送的“OSD 气泡”,例如更改音量、IM 聊天等?你想创建一个 python 程序来捕获那些吗?

好吧,Ask Ubuntu 不是程序员的 QA,软件开发有点超出范围,但这里有一些我确实捕获通知气泡的代码:

import glib
import dbus
from dbus.mainloop.glib import DBusGMainLoop

def notifications(bus, message):
    if message.get_member() == "Notify":
        print [arg for arg in message.get_args_list()]

DBusGMainLoop(set_as_default=True)

bus = dbus.SessionBus()
bus.add_match_string_non_blocking("interface='org.freedesktop.Notifications'")
bus.add_message_filter(notifications)

mainloop = glib.MainLoop()
mainloop.run()
Run Code Online (Sandbox Code Playgroud)

让它在终端中运行,然后打开另一个终端窗口并测试它:

notify-send --icon=/usr/share/pixmaps/debian-logo.png "My Title" "Some text body"
Run Code Online (Sandbox Code Playgroud)

程序将输出:

[dbus.String(u'notify-send'), dbus.UInt32(0L), dbus.String(u'/usr/share/pixmaps/debian-logo.png'), dbus.String(u'My Title'), dbus.String(u'Some text body'),...
Run Code Online (Sandbox Code Playgroud)

您可能已经猜到,message.get_args_list()[0]是发件人,[2] 表示图标,[3] 表示摘要,[4] 表示正文。

对于其他字段的含义,请查看官方规范文档