Звуковое уведомление по SSH

Вместо «Системные настройки» Gnome3.8 не имеет заголовка, который только «Настройки»? Я прочитал, что функции конфиденциальности вернулись в Gnome 3.8, и вы можете найти их в разделе «Настройки»

12
задан 16 September 2011 в 03:54

15 ответов

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

##
## Put me in ~/.irssi/scripts, and then execute the following in irssi:
##
##       /load perl
##       /script load notifyudp
##

use strict;
use Irssi;
use IO::Socket;
use vars qw($VERSION %IRSSI);
use Time::HiRes qw(time);

$VERSION = "0.3.20140930";
%IRSSI = (
    authors     => 'Lekensteyn',
    contact     => 'lekensteyn@gmail.com',
    name        => 'notifyudp.pl',
    description => 'Send a UDP signal to a remote machine',
    license     => 'GPLv3+'
);

Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', '');
# port 0 = disabled
Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0);
Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0);

my $sock;

sub notify_load {
    if ($sock) {
        Irssi::print('NotifyUDP: Already connected.');
        return;
    }
    my $ip = Irssi::settings_get_str('notifyudp_ip_addr');
    my $port = Irssi::settings_get_int('notifyudp_port');
    if (!$port || !$ip) {
        Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..');
        return;
    }
    if ($port < 1024 || $port > 65535) {
        Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.');
        Irssi::settings_set_int('notifyudp_port', 0);
        return;
    }
    $sock = new IO::Socket::INET(
        PeerAddr => $ip,
        PeerPort => $port,
        Proto => 'udp',
        Timeout => 1
    );
    Irssi::print("NotifyUDP: IP $ip will be notified on port $port.");
}

my $last_time = 0;
sub notify {
    if ($sock) {
        my $now = time;
        my $notify_delay = 1.3;
        if (abs($now - $last_time) > $notify_delay) {
            $last_time = $now;
            $sock->send("M");
        }
    }
}
sub notify_if_hilighted {
    my ($dest, $text, $stripped) = @_;
    if ($dest->{level} & MSGLEVEL_HILIGHT) {
        notify();
    }
}

sub notify_stop {
    if ($sock) {
        Irssi::print("NotifyUDP: Stopping.");
        $sock->send("S");
        $sock = undef;
    } else {
        Irssi::print("NotifyUDP: not active.");
    }
}

sub cmd_notifyudp {
    my ($cmd) = @_;
    if ($cmd eq 'start') {
        notify_load();
    } elsif ($cmd eq 'stop') {
        notify_stop();
    } elsif ($cmd eq 'ping') {
        notify();
    } else {
        Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]');
    }
}

Irssi::command_bind('notifyudp', 'cmd_notifyudp');

my @signals = (
# Uncomment the following to get notifs for every (channel) message
#'message public',
'message private',
'dcc request',

'message irc notice', # NickServ responses and such

# whenever the server dies
'server connected',
'server connect failed',
'server disconnected',

'message invite',
'message topic',
'message dcc',
'ctcp msg',
'ctcp reply',
);
Irssi::signal_add('print text', 'notify_if_hilighted');
foreach (@signals) {
    Irssi::signal_add($_, 'notify');
}

if (Irssi::settings_get_bool('notifyudp_auto_start')) {
    Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.');
    notify_load();
} else {
    Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.');
}

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python
# udpsoundserver.py

"""Listen on a UDP port and play a sound when 'M' is received

Starts the server listening on UDP port PORT (3533 by default) on address HOST
(by default all addresses). Valid commands are:
M - play Music
S - Stop the server
"""
try:
    import socketserver
except ImportError:
    import SocketServer as socketserver
from os import system,getpid
import threading
import sys

# leave it empty to listen on all addresses
HOST = ""
PORT = 3533


class UDPSvr(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0]
        if sys.version >= '3':
            data = str(data, "ISO-8859-1")
        data = data.strip()
        if data == "M":
            ding.dong()
        elif data == "S":
            ding.die()

class Worker(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
    def run(self):
        server.serve_forever();

class Handler(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
        self.play = False
        self.must_die = False

    def run(self):
        self.event = threading.Event()
        while True:
            self.event.wait(1.)
            if self.event.isSet():
                if self.play:
                    print("Playing...")
                    system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg")
                # no else if to allow shutdown signals 
                if self.must_die:
                    print("Shutting down...")
                    server.shutdown()
                    break
                self.play = False
                self.event.clear()

    def dong(self):
        self.play = True
        self.event.set()

    def die(self):
        self.must_die = True
        self.event.set()

def ca(num, x):
    print("Caught SIGINT, shutting down...")
    ding.die()

import signal
if __name__ == "__main__":
    print("My PID is: " + str(getpid()))

    if len(sys.argv) > 1:
        HOST = sys.argv[1]
    if len(sys.argv) > 2:
        PORT = int(sys.argv[2])

    print("Host: " + HOST)
    print("Port: " + str(PORT))
    server = socketserver.UDPServer((HOST, PORT), UDPSvr)

    ding = Handler()
    signal.signal(signal.SIGINT, ca)
    worker = Worker()
    ding.start()
    worker.start()
    # might not be the cleanest, but it allows Ctrl + C
    while ding.isAlive():
        ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py
ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7]

screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1
/set notifyudp_port 5355
[d10 ] Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 25 May 2018 в 19:21
  • 1
    Вы сказали, что текстовый индикатор не является требованием - фраза подразумевает, что это было бы хорошо, но не было предпочтительным вариантом. Извиняюсь за редактирование, и вы можете отбросить его назад, если хотите. – jrg♦ 16 September 2011 в 17:48
  • 2
    Нет проблем, хорошо иметь альтернативы. Мое решение, как я сказал, взломан вместе, так что ваш ответ может быть стоит попробовать. – Lekensteyn 17 September 2011 в 00:26

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

## ## Put me in ~/.irssi/scripts, and then execute the following in irssi: ## ## /load perl ## /script load notifyudp ## use strict; use Irssi; use IO::Socket; use vars qw($VERSION %IRSSI); use Time::HiRes qw(time); $VERSION = "0.3.20140930"; %IRSSI = ( authors => 'Lekensteyn', contact => 'lekensteyn@gmail.com', name => 'notifyudp.pl', description => 'Send a UDP signal to a remote machine', license => 'GPLv3+' ); Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', ''); # port 0 = disabled Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0); Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0); my $sock; sub notify_load { if ($sock) { Irssi::print('NotifyUDP: Already connected.'); return; } my $ip = Irssi::settings_get_str('notifyudp_ip_addr'); my $port = Irssi::settings_get_int('notifyudp_port'); if (!$port || !$ip) { Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..'); return; } if ($port < 1024 || $port > 65535) { Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.'); Irssi::settings_set_int('notifyudp_port', 0); return; } $sock = new IO::Socket::INET( PeerAddr => $ip, PeerPort => $port, Proto => 'udp', Timeout => 1 ); Irssi::print("NotifyUDP: IP $ip will be notified on port $port."); } my $last_time = 0; sub notify { if ($sock) { my $now = time; my $notify_delay = 1.3; if (abs($now - $last_time) > $notify_delay) { $last_time = $now; $sock->send("M"); } } } sub notify_if_hilighted { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { notify(); } } sub notify_stop { if ($sock) { Irssi::print("NotifyUDP: Stopping."); $sock->send("S"); $sock = undef; } else { Irssi::print("NotifyUDP: not active."); } } sub cmd_notifyudp { my ($cmd) = @_; if ($cmd eq 'start') { notify_load(); } elsif ($cmd eq 'stop') { notify_stop(); } elsif ($cmd eq 'ping') { notify(); } else { Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]'); } } Irssi::command_bind('notifyudp', 'cmd_notifyudp'); my @signals = ( # Uncomment the following to get notifs for every (channel) message #'message public', 'message private', 'dcc request', 'message irc notice', # NickServ responses and such # whenever the server dies 'server connected', 'server connect failed', 'server disconnected', 'message invite', 'message topic', 'message dcc', 'ctcp msg', 'ctcp reply', ); Irssi::signal_add('print text', 'notify_if_hilighted'); foreach (@signals) { Irssi::signal_add($_, 'notify'); } if (Irssi::settings_get_bool('notifyudp_auto_start')) { Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.'); notify_load(); } else { Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.'); }

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python # udpsoundserver.py """Listen on a UDP port and play a sound when 'M' is received Starts the server listening on UDP port PORT (3533 by default) on address HOST (by default all addresses). Valid commands are: M - play Music S - Stop the server """ try: import socketserver except ImportError: import SocketServer as socketserver from os import system,getpid import threading import sys # leave it empty to listen on all addresses HOST = "" PORT = 3533 class UDPSvr(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] if sys.version >= '3': data = str(data, "ISO-8859-1") data = data.strip() if data == "M": ding.dong() elif data == "S": ding.die() class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run(self): server.serve_forever(); class Handler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True self.play = False self.must_die = False def run(self): self.event = threading.Event() while True: self.event.wait(1.) if self.event.isSet(): if self.play: print("Playing...") system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg") # no else if to allow shutdown signals if self.must_die: print("Shutting down...") server.shutdown() break self.play = False self.event.clear() def dong(self): self.play = True self.event.set() def die(self): self.must_die = True self.event.set() def ca(num, x): print("Caught SIGINT, shutting down...") ding.die() import signal if __name__ == "__main__": print("My PID is: " + str(getpid())) if len(sys.argv) > 1: HOST = sys.argv[1] if len(sys.argv) > 2: PORT = int(sys.argv[2]) print("Host: " + HOST) print("Port: " + str(PORT)) server = socketserver.UDPServer((HOST, PORT), UDPSvr) ding = Handler() signal.signal(signal.SIGINT, ca) worker = Worker() ding.start() worker.start() # might not be the cleanest, but it allows Ctrl + C while ding.isAlive(): ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7] screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1 /set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 25 July 2018 в 21:27

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

## ## Put me in ~/.irssi/scripts, and then execute the following in irssi: ## ## /load perl ## /script load notifyudp ## use strict; use Irssi; use IO::Socket; use vars qw($VERSION %IRSSI); use Time::HiRes qw(time); $VERSION = "0.3.20140930"; %IRSSI = ( authors => 'Lekensteyn', contact => 'lekensteyn@gmail.com', name => 'notifyudp.pl', description => 'Send a UDP signal to a remote machine', license => 'GPLv3+' ); Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', ''); # port 0 = disabled Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0); Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0); my $sock; sub notify_load { if ($sock) { Irssi::print('NotifyUDP: Already connected.'); return; } my $ip = Irssi::settings_get_str('notifyudp_ip_addr'); my $port = Irssi::settings_get_int('notifyudp_port'); if (!$port || !$ip) { Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..'); return; } if ($port < 1024 || $port > 65535) { Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.'); Irssi::settings_set_int('notifyudp_port', 0); return; } $sock = new IO::Socket::INET( PeerAddr => $ip, PeerPort => $port, Proto => 'udp', Timeout => 1 ); Irssi::print("NotifyUDP: IP $ip will be notified on port $port."); } my $last_time = 0; sub notify { if ($sock) { my $now = time; my $notify_delay = 1.3; if (abs($now - $last_time) > $notify_delay) { $last_time = $now; $sock->send("M"); } } } sub notify_if_hilighted { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { notify(); } } sub notify_stop { if ($sock) { Irssi::print("NotifyUDP: Stopping."); $sock->send("S"); $sock = undef; } else { Irssi::print("NotifyUDP: not active."); } } sub cmd_notifyudp { my ($cmd) = @_; if ($cmd eq 'start') { notify_load(); } elsif ($cmd eq 'stop') { notify_stop(); } elsif ($cmd eq 'ping') { notify(); } else { Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]'); } } Irssi::command_bind('notifyudp', 'cmd_notifyudp'); my @signals = ( # Uncomment the following to get notifs for every (channel) message #'message public', 'message private', 'dcc request', 'message irc notice', # NickServ responses and such # whenever the server dies 'server connected', 'server connect failed', 'server disconnected', 'message invite', 'message topic', 'message dcc', 'ctcp msg', 'ctcp reply', ); Irssi::signal_add('print text', 'notify_if_hilighted'); foreach (@signals) { Irssi::signal_add($_, 'notify'); } if (Irssi::settings_get_bool('notifyudp_auto_start')) { Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.'); notify_load(); } else { Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.'); }

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python # udpsoundserver.py """Listen on a UDP port and play a sound when 'M' is received Starts the server listening on UDP port PORT (3533 by default) on address HOST (by default all addresses). Valid commands are: M - play Music S - Stop the server """ try: import socketserver except ImportError: import SocketServer as socketserver from os import system,getpid import threading import sys # leave it empty to listen on all addresses HOST = "" PORT = 3533 class UDPSvr(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] if sys.version >= '3': data = str(data, "ISO-8859-1") data = data.strip() if data == "M": ding.dong() elif data == "S": ding.die() class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run(self): server.serve_forever(); class Handler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True self.play = False self.must_die = False def run(self): self.event = threading.Event() while True: self.event.wait(1.) if self.event.isSet(): if self.play: print("Playing...") system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg") # no else if to allow shutdown signals if self.must_die: print("Shutting down...") server.shutdown() break self.play = False self.event.clear() def dong(self): self.play = True self.event.set() def die(self): self.must_die = True self.event.set() def ca(num, x): print("Caught SIGINT, shutting down...") ding.die() import signal if __name__ == "__main__": print("My PID is: " + str(getpid())) if len(sys.argv) > 1: HOST = sys.argv[1] if len(sys.argv) > 2: PORT = int(sys.argv[2]) print("Host: " + HOST) print("Port: " + str(PORT)) server = socketserver.UDPServer((HOST, PORT), UDPSvr) ding = Handler() signal.signal(signal.SIGINT, ca) worker = Worker() ding.start() worker.start() # might not be the cleanest, but it allows Ctrl + C while ding.isAlive(): ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7] screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1 /set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 2 August 2018 в 03:06

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

## ## Put me in ~/.irssi/scripts, and then execute the following in irssi: ## ## /load perl ## /script load notifyudp ## use strict; use Irssi; use IO::Socket; use vars qw($VERSION %IRSSI); use Time::HiRes qw(time); $VERSION = "0.3.20140930"; %IRSSI = ( authors => 'Lekensteyn', contact => 'lekensteyn@gmail.com', name => 'notifyudp.pl', description => 'Send a UDP signal to a remote machine', license => 'GPLv3+' ); Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', ''); # port 0 = disabled Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0); Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0); my $sock; sub notify_load { if ($sock) { Irssi::print('NotifyUDP: Already connected.'); return; } my $ip = Irssi::settings_get_str('notifyudp_ip_addr'); my $port = Irssi::settings_get_int('notifyudp_port'); if (!$port || !$ip) { Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..'); return; } if ($port < 1024 || $port > 65535) { Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.'); Irssi::settings_set_int('notifyudp_port', 0); return; } $sock = new IO::Socket::INET( PeerAddr => $ip, PeerPort => $port, Proto => 'udp', Timeout => 1 ); Irssi::print("NotifyUDP: IP $ip will be notified on port $port."); } my $last_time = 0; sub notify { if ($sock) { my $now = time; my $notify_delay = 1.3; if (abs($now - $last_time) > $notify_delay) { $last_time = $now; $sock->send("M"); } } } sub notify_if_hilighted { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { notify(); } } sub notify_stop { if ($sock) { Irssi::print("NotifyUDP: Stopping."); $sock->send("S"); $sock = undef; } else { Irssi::print("NotifyUDP: not active."); } } sub cmd_notifyudp { my ($cmd) = @_; if ($cmd eq 'start') { notify_load(); } elsif ($cmd eq 'stop') { notify_stop(); } elsif ($cmd eq 'ping') { notify(); } else { Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]'); } } Irssi::command_bind('notifyudp', 'cmd_notifyudp'); my @signals = ( # Uncomment the following to get notifs for every (channel) message #'message public', 'message private', 'dcc request', 'message irc notice', # NickServ responses and such # whenever the server dies 'server connected', 'server connect failed', 'server disconnected', 'message invite', 'message topic', 'message dcc', 'ctcp msg', 'ctcp reply', ); Irssi::signal_add('print text', 'notify_if_hilighted'); foreach (@signals) { Irssi::signal_add($_, 'notify'); } if (Irssi::settings_get_bool('notifyudp_auto_start')) { Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.'); notify_load(); } else { Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.'); }

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python # udpsoundserver.py """Listen on a UDP port and play a sound when 'M' is received Starts the server listening on UDP port PORT (3533 by default) on address HOST (by default all addresses). Valid commands are: M - play Music S - Stop the server """ try: import socketserver except ImportError: import SocketServer as socketserver from os import system,getpid import threading import sys # leave it empty to listen on all addresses HOST = "" PORT = 3533 class UDPSvr(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] if sys.version >= '3': data = str(data, "ISO-8859-1") data = data.strip() if data == "M": ding.dong() elif data == "S": ding.die() class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run(self): server.serve_forever(); class Handler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True self.play = False self.must_die = False def run(self): self.event = threading.Event() while True: self.event.wait(1.) if self.event.isSet(): if self.play: print("Playing...") system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg") # no else if to allow shutdown signals if self.must_die: print("Shutting down...") server.shutdown() break self.play = False self.event.clear() def dong(self): self.play = True self.event.set() def die(self): self.must_die = True self.event.set() def ca(num, x): print("Caught SIGINT, shutting down...") ding.die() import signal if __name__ == "__main__": print("My PID is: " + str(getpid())) if len(sys.argv) > 1: HOST = sys.argv[1] if len(sys.argv) > 2: PORT = int(sys.argv[2]) print("Host: " + HOST) print("Port: " + str(PORT)) server = socketserver.UDPServer((HOST, PORT), UDPSvr) ding = Handler() signal.signal(signal.SIGINT, ca) worker = Worker() ding.start() worker.start() # might not be the cleanest, but it allows Ctrl + C while ding.isAlive(): ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7] screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1 /set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 4 August 2018 в 18:57

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

## ## Put me in ~/.irssi/scripts, and then execute the following in irssi: ## ## /load perl ## /script load notifyudp ## use strict; use Irssi; use IO::Socket; use vars qw($VERSION %IRSSI); use Time::HiRes qw(time); $VERSION = "0.3.20140930"; %IRSSI = ( authors => 'Lekensteyn', contact => 'lekensteyn@gmail.com', name => 'notifyudp.pl', description => 'Send a UDP signal to a remote machine', license => 'GPLv3+' ); Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', ''); # port 0 = disabled Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0); Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0); my $sock; sub notify_load { if ($sock) { Irssi::print('NotifyUDP: Already connected.'); return; } my $ip = Irssi::settings_get_str('notifyudp_ip_addr'); my $port = Irssi::settings_get_int('notifyudp_port'); if (!$port || !$ip) { Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..'); return; } if ($port < 1024 || $port > 65535) { Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.'); Irssi::settings_set_int('notifyudp_port', 0); return; } $sock = new IO::Socket::INET( PeerAddr => $ip, PeerPort => $port, Proto => 'udp', Timeout => 1 ); Irssi::print("NotifyUDP: IP $ip will be notified on port $port."); } my $last_time = 0; sub notify { if ($sock) { my $now = time; my $notify_delay = 1.3; if (abs($now - $last_time) > $notify_delay) { $last_time = $now; $sock->send("M"); } } } sub notify_if_hilighted { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { notify(); } } sub notify_stop { if ($sock) { Irssi::print("NotifyUDP: Stopping."); $sock->send("S"); $sock = undef; } else { Irssi::print("NotifyUDP: not active."); } } sub cmd_notifyudp { my ($cmd) = @_; if ($cmd eq 'start') { notify_load(); } elsif ($cmd eq 'stop') { notify_stop(); } elsif ($cmd eq 'ping') { notify(); } else { Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]'); } } Irssi::command_bind('notifyudp', 'cmd_notifyudp'); my @signals = ( # Uncomment the following to get notifs for every (channel) message #'message public', 'message private', 'dcc request', 'message irc notice', # NickServ responses and such # whenever the server dies 'server connected', 'server connect failed', 'server disconnected', 'message invite', 'message topic', 'message dcc', 'ctcp msg', 'ctcp reply', ); Irssi::signal_add('print text', 'notify_if_hilighted'); foreach (@signals) { Irssi::signal_add($_, 'notify'); } if (Irssi::settings_get_bool('notifyudp_auto_start')) { Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.'); notify_load(); } else { Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.'); }

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python # udpsoundserver.py """Listen on a UDP port and play a sound when 'M' is received Starts the server listening on UDP port PORT (3533 by default) on address HOST (by default all addresses). Valid commands are: M - play Music S - Stop the server """ try: import socketserver except ImportError: import SocketServer as socketserver from os import system,getpid import threading import sys # leave it empty to listen on all addresses HOST = "" PORT = 3533 class UDPSvr(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] if sys.version >= '3': data = str(data, "ISO-8859-1") data = data.strip() if data == "M": ding.dong() elif data == "S": ding.die() class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run(self): server.serve_forever(); class Handler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True self.play = False self.must_die = False def run(self): self.event = threading.Event() while True: self.event.wait(1.) if self.event.isSet(): if self.play: print("Playing...") system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg") # no else if to allow shutdown signals if self.must_die: print("Shutting down...") server.shutdown() break self.play = False self.event.clear() def dong(self): self.play = True self.event.set() def die(self): self.must_die = True self.event.set() def ca(num, x): print("Caught SIGINT, shutting down...") ding.die() import signal if __name__ == "__main__": print("My PID is: " + str(getpid())) if len(sys.argv) > 1: HOST = sys.argv[1] if len(sys.argv) > 2: PORT = int(sys.argv[2]) print("Host: " + HOST) print("Port: " + str(PORT)) server = socketserver.UDPServer((HOST, PORT), UDPSvr) ding = Handler() signal.signal(signal.SIGINT, ca) worker = Worker() ding.start() worker.start() # might not be the cleanest, but it allows Ctrl + C while ding.isAlive(): ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7] screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1 /set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 6 August 2018 в 03:19

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

## ## Put me in ~/.irssi/scripts, and then execute the following in irssi: ## ## /load perl ## /script load notifyudp ## use strict; use Irssi; use IO::Socket; use vars qw($VERSION %IRSSI); use Time::HiRes qw(time); $VERSION = "0.3.20140930"; %IRSSI = ( authors => 'Lekensteyn', contact => 'lekensteyn@gmail.com', name => 'notifyudp.pl', description => 'Send a UDP signal to a remote machine', license => 'GPLv3+' ); Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', ''); # port 0 = disabled Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0); Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0); my $sock; sub notify_load { if ($sock) { Irssi::print('NotifyUDP: Already connected.'); return; } my $ip = Irssi::settings_get_str('notifyudp_ip_addr'); my $port = Irssi::settings_get_int('notifyudp_port'); if (!$port || !$ip) { Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..'); return; } if ($port < 1024 || $port > 65535) { Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.'); Irssi::settings_set_int('notifyudp_port', 0); return; } $sock = new IO::Socket::INET( PeerAddr => $ip, PeerPort => $port, Proto => 'udp', Timeout => 1 ); Irssi::print("NotifyUDP: IP $ip will be notified on port $port."); } my $last_time = 0; sub notify { if ($sock) { my $now = time; my $notify_delay = 1.3; if (abs($now - $last_time) > $notify_delay) { $last_time = $now; $sock->send("M"); } } } sub notify_if_hilighted { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { notify(); } } sub notify_stop { if ($sock) { Irssi::print("NotifyUDP: Stopping."); $sock->send("S"); $sock = undef; } else { Irssi::print("NotifyUDP: not active."); } } sub cmd_notifyudp { my ($cmd) = @_; if ($cmd eq 'start') { notify_load(); } elsif ($cmd eq 'stop') { notify_stop(); } elsif ($cmd eq 'ping') { notify(); } else { Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]'); } } Irssi::command_bind('notifyudp', 'cmd_notifyudp'); my @signals = ( # Uncomment the following to get notifs for every (channel) message #'message public', 'message private', 'dcc request', 'message irc notice', # NickServ responses and such # whenever the server dies 'server connected', 'server connect failed', 'server disconnected', 'message invite', 'message topic', 'message dcc', 'ctcp msg', 'ctcp reply', ); Irssi::signal_add('print text', 'notify_if_hilighted'); foreach (@signals) { Irssi::signal_add($_, 'notify'); } if (Irssi::settings_get_bool('notifyudp_auto_start')) { Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.'); notify_load(); } else { Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.'); }

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python # udpsoundserver.py """Listen on a UDP port and play a sound when 'M' is received Starts the server listening on UDP port PORT (3533 by default) on address HOST (by default all addresses). Valid commands are: M - play Music S - Stop the server """ try: import socketserver except ImportError: import SocketServer as socketserver from os import system,getpid import threading import sys # leave it empty to listen on all addresses HOST = "" PORT = 3533 class UDPSvr(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] if sys.version >= '3': data = str(data, "ISO-8859-1") data = data.strip() if data == "M": ding.dong() elif data == "S": ding.die() class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run(self): server.serve_forever(); class Handler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True self.play = False self.must_die = False def run(self): self.event = threading.Event() while True: self.event.wait(1.) if self.event.isSet(): if self.play: print("Playing...") system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg") # no else if to allow shutdown signals if self.must_die: print("Shutting down...") server.shutdown() break self.play = False self.event.clear() def dong(self): self.play = True self.event.set() def die(self): self.must_die = True self.event.set() def ca(num, x): print("Caught SIGINT, shutting down...") ding.die() import signal if __name__ == "__main__": print("My PID is: " + str(getpid())) if len(sys.argv) > 1: HOST = sys.argv[1] if len(sys.argv) > 2: PORT = int(sys.argv[2]) print("Host: " + HOST) print("Port: " + str(PORT)) server = socketserver.UDPServer((HOST, PORT), UDPSvr) ding = Handler() signal.signal(signal.SIGINT, ca) worker = Worker() ding.start() worker.start() # might not be the cleanest, but it allows Ctrl + C while ding.isAlive(): ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7] screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1 /set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 7 August 2018 в 21:00

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в редакции 1, он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вас. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'.

## ## Put me in ~/.irssi/scripts, and then execute the following in irssi: ## ## /load perl ## /script load notifyudp ## use strict; use Irssi; use IO::Socket; use vars qw($VERSION %IRSSI); use Time::HiRes qw(time); $VERSION = "0.3.20140930"; %IRSSI = ( authors => 'Lekensteyn', contact => 'lekensteyn@gmail.com', name => 'notifyudp.pl', description => 'Send a UDP signal to a remote machine', license => 'GPLv3+' ); Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', ''); # port 0 = disabled Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0); Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0); my $sock; sub notify_load { if ($sock) { Irssi::print('NotifyUDP: Already connected.'); return; } my $ip = Irssi::settings_get_str('notifyudp_ip_addr'); my $port = Irssi::settings_get_int('notifyudp_port'); if (!$port || !$ip) { Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..'); return; } if ($port < 1024 || $port > 65535) { Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.'); Irssi::settings_set_int('notifyudp_port', 0); return; } $sock = new IO::Socket::INET( PeerAddr => $ip, PeerPort => $port, Proto => 'udp', Timeout => 1 ); Irssi::print("NotifyUDP: IP $ip will be notified on port $port."); } my $last_time = 0; sub notify { if ($sock) { my $now = time; my $notify_delay = 1.3; if (abs($now - $last_time) > $notify_delay) { $last_time = $now; $sock->send("M"); } } } sub notify_if_hilighted { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { notify(); } } sub notify_stop { if ($sock) { Irssi::print("NotifyUDP: Stopping."); $sock->send("S"); $sock = undef; } else { Irssi::print("NotifyUDP: not active."); } } sub cmd_notifyudp { my ($cmd) = @_; if ($cmd eq 'start') { notify_load(); } elsif ($cmd eq 'stop') { notify_stop(); } elsif ($cmd eq 'ping') { notify(); } else { Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]'); } } Irssi::command_bind('notifyudp', 'cmd_notifyudp'); my @signals = ( # Uncomment the following to get notifs for every (channel) message #'message public', 'message private', 'dcc request', 'message irc notice', # NickServ responses and such # whenever the server dies 'server connected', 'server connect failed', 'server disconnected', 'message invite', 'message topic', 'message dcc', 'ctcp msg', 'ctcp reply', ); Irssi::signal_add('print text', 'notify_if_hilighted'); foreach (@signals) { Irssi::signal_add($_, 'notify'); } if (Irssi::settings_get_bool('notifyudp_auto_start')) { Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.'); notify_load(); } else { Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.'); }

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер.

#!/usr/bin/env python # udpsoundserver.py """Listen on a UDP port and play a sound when 'M' is received Starts the server listening on UDP port PORT (3533 by default) on address HOST (by default all addresses). Valid commands are: M - play Music S - Stop the server """ try: import socketserver except ImportError: import SocketServer as socketserver from os import system,getpid import threading import sys # leave it empty to listen on all addresses HOST = "" PORT = 3533 class UDPSvr(socketserver.BaseRequestHandler): def handle(self): data = self.request[0] if sys.version >= '3': data = str(data, "ISO-8859-1") data = data.strip() if data == "M": ding.dong() elif data == "S": ding.die() class Worker(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True def run(self): server.serve_forever(); class Handler(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon = True self.play = False self.must_die = False def run(self): self.event = threading.Event() while True: self.event.wait(1.) if self.event.isSet(): if self.play: print("Playing...") system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg") # no else if to allow shutdown signals if self.must_die: print("Shutting down...") server.shutdown() break self.play = False self.event.clear() def dong(self): self.play = True self.event.set() def die(self): self.must_die = True self.event.set() def ca(num, x): print("Caught SIGINT, shutting down...") ding.die() import signal if __name__ == "__main__": print("My PID is: " + str(getpid())) if len(sys.argv) > 1: HOST = sys.argv[1] if len(sys.argv) > 2: PORT = int(sys.argv[2]) print("Host: " + HOST) print("Port: " + str(PORT)) server = socketserver.UDPServer((HOST, PORT), UDPSvr) ding = Handler() signal.signal(signal.SIGINT, ca) worker = Worker() ding.start() worker.start() # might not be the cleanest, but it allows Ctrl + C while ding.isAlive(): ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py ssh -R 5355:localhost:5355

После входа в систему я запускаю: [ ! d7] screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1 /set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

сделать остановку звукового сервера при отключении разрешить пропуски каналов
9
ответ дан 10 August 2018 в 09:23

Мне не понравилось libnotify, поэтому я создал UDP-сервер в Python и клиентское приложение для irssi. Обратите внимание, что этот ответ относится к исходным требованиям в версии 1 , он не имеет текстового уведомления.

Клиент

Эта версия реагирует на различные сообщения, направленные на вы. Если вы хотите получать уведомления о сообщениях в любом канале, удалите ведущую # в строке #'message public'. Некоторые ограничения скорости реализованы, между уведомлениями будет не менее 1,3 секунд.

##
## Put me in ~/.irssi/scripts, and then execute the following in irssi:
##
##       /load perl
##       /script load notifyudp
##

use strict;
use Irssi;
use IO::Socket;
use vars qw($VERSION %IRSSI);
use Time::HiRes qw(time);

$VERSION = "0.3.20140930";
%IRSSI = (
    authors     => 'Lekensteyn',
    contact     => 'lekensteyn@gmail.com',
    name        => 'notifyudp.pl',
    description => 'Send a UDP signal to a remote machine',
    license     => 'GPLv3+'
);

Irssi::settings_add_str('notifyudp', 'notifyudp_ip_addr', '');
# port 0 = disabled
Irssi::settings_add_int('notifyudp', 'notifyudp_port', 0);
Irssi::settings_add_bool('notifyudp', 'notifyudp_auto_start', 0);

my $sock;

sub notify_load {
    if ($sock) {
        Irssi::print('NotifyUDP: Already connected.');
        return;
    }
    my $ip = Irssi::settings_get_str('notifyudp_ip_addr');
    my $port = Irssi::settings_get_int('notifyudp_port');
    if (!$port || !$ip) {
        Irssi::print('NotifyUDP: No port or host set, /set notifyudp for more information..');
        return;
    }
    if ($port < 1024 || $port > 65535) {
        Irssi::print('NotifyUDP: Invalid port, must be 1024 <= port <= 65535, resetting and ignoring.');
        Irssi::settings_set_int('notifyudp_port', 0);
        return;
    }
    $sock = new IO::Socket::INET(
        PeerAddr => $ip,
        PeerPort => $port,
        Proto => 'udp',
        Timeout => 1
    );
    Irssi::print("NotifyUDP: IP $ip will be notified on port $port.");
}

my $last_time = 0;
sub notify {
    if ($sock) {
        my $now = time;
        my $notify_delay = 1.3;
        if (abs($now - $last_time) > $notify_delay) {
            $last_time = $now;
            $sock->send("M");
        }
    }
}
sub notify_if_hilighted {
    my ($dest, $text, $stripped) = @_;
    if ($dest->{level} & MSGLEVEL_HILIGHT) {
        notify();
    }
}

sub notify_stop {
    if ($sock) {
        Irssi::print("NotifyUDP: Stopping.");
        $sock->send("S");
        $sock = undef;
    } else {
        Irssi::print("NotifyUDP: not active.");
    }
}

sub cmd_notifyudp {
    my ($cmd) = @_;
    if ($cmd eq 'start') {
        notify_load();
    } elsif ($cmd eq 'stop') {
        notify_stop();
    } elsif ($cmd eq 'ping') {
        notify();
    } else {
        Irssi::print('NotifyUDP: Usage: /notifyudp [start|stop|ping]');
    }
}

Irssi::command_bind('notifyudp', 'cmd_notifyudp');

my @signals = (
# Uncomment the following to get notifs for every (channel) message
#'message public',
'message private',
'dcc request',

'message irc notice', # NickServ responses and such

# whenever the server dies
'server connected',
'server connect failed',
'server disconnected',

'message invite',
'message topic',
'message dcc',
'ctcp msg',
'ctcp reply',
);
Irssi::signal_add('print text', 'notify_if_hilighted');
foreach (@signals) {
    Irssi::signal_add($_, 'notify');
}

if (Irssi::settings_get_bool('notifyudp_auto_start')) {
    Irssi::print('NotifyUDP: automatic connection with the sound server is enabled.');
    notify_load();
} else {
    Irssi::print('NotifyUDP: automatic connection with the sound server is disabled.');
}

Сервер

При запуске он прослушивает все адреса, порт 3533. Если это получает UDP-пакет «M», он играет /usr/share/sounds/KDE-Im-Irc-Event.ogg, используя paplay («PulseAudio play»). При получении S он покидает сервер. Поскольку это открытый исходный код, вы можете удалить это.

#!/usr/bin/env python
# udpsoundserver.py

"""Listen on a UDP port and play a sound when 'M' is received

Starts the server listening on UDP port PORT (3533 by default) on address HOST
(by default all addresses). Valid commands are:
M - play Music
S - Stop the server
"""
try:
    import socketserver
except ImportError:
    import SocketServer as socketserver
from os import system,getpid
import threading
import sys

# leave it empty to listen on all addresses
HOST = ""
PORT = 3533


class UDPSvr(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0]
        if sys.version >= '3':
            data = str(data, "ISO-8859-1")
        data = data.strip()
        if data == "M":
            ding.dong()
        elif data == "S":
            ding.die()

class Worker(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
    def run(self):
        server.serve_forever();

class Handler(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
        self.play = False
        self.must_die = False

    def run(self):
        self.event = threading.Event()
        while True:
            self.event.wait(1.)
            if self.event.isSet():
                if self.play:
                    print("Playing...")
                    system("paplay /usr/share/sounds/KDE-Im-Irc-Event.ogg")
                # no else if to allow shutdown signals 
                if self.must_die:
                    print("Shutting down...")
                    server.shutdown()
                    break
                self.play = False
                self.event.clear()

    def dong(self):
        self.play = True
        self.event.set()

    def die(self):
        self.must_die = True
        self.event.set()

def ca(num, x):
    print("Caught SIGINT, shutting down...")
    ding.die()

import signal
if __name__ == "__main__":
    print("My PID is: " + str(getpid()))

    if len(sys.argv) > 1:
        HOST = sys.argv[1]
    if len(sys.argv) > 2:
        PORT = int(sys.argv[2])

    print("Host: " + HOST)
    print("Port: " + str(PORT))
    server = socketserver.UDPServer((HOST, PORT), UDPSvr)

    ding = Handler()
    signal.signal(signal.SIGINT, ca)
    worker = Worker()
    ding.start()
    worker.start()
    # might not be the cleanest, but it allows Ctrl + C
    while ding.isAlive():
        ding.join(3600)

Последовательность запуска удаленного сервера становится:

screen -dm path/to/udpsoundserver.py
ssh -R 5355:localhost:5355

После входа в систему я запускаю:

screen -t irssi irssi

Если вам нужно снова подключиться:

screen -r irssi

После запуска irssi вам нужно установить хост и порт:

/set notifyudp_ip_addr 127.0.0.1
/set notifyudp_port 5355

Чтобы он автоматически подключался при запуске:

/set notifyudp_auto_start 1

В первый раз вам нужно запустить Notify UDP вручную, так как он еще не был запущен автоматически:

/notifyudp start

для проверки уведомления:

/notifyudp ping

To-do:

  • сделать остановку звукового сервера при отключении
  • разрешить пропуски каналов
9
ответ дан 13 August 2018 в 12:46

Я делаю это с libnotify. Я нашел это много лет назад.

Он работает как чемпион. Я использовал его с libnotify в linux (и все еще делаю, когда я на Linux-машине), но большую часть времени я сейчас на macbook, поэтому я использую рычание в качестве замены libnotify на mac.

# todo: grap topic changes

use strict;
use vars qw($VERSION %IRSSI);

use Irssi;
$VERSION = '0.0.3';
%IRSSI = (
    authors     => 'Thorsten Leemhuis',
    contact     => 'fedora@leemhuis.info',
    name        => 'fnotify',
    description => 'Write a notification to a file that shows who is talking to you in which channel.',
    url         => 'http://www.leemhuis.info/files/fnotify/',
    license     => 'GNU General Public License',
    changed     => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $'
);

#--------------------------------------------------------------------
# In parts based on knotify.pl 0.1.1 by Hugo Haas
# http://larve.net/people/hugo/2005/01/knotify.pl
# which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen
# http://www.irssi.org/scripts/scripts/osd.pl
#
# Other parts based on notify.pl from Luke Macken
# http://fedora.feedjack.org/user/918/
#
#--------------------------------------------------------------------

#--------------------------------------------------------------------
# Private message parsing
#--------------------------------------------------------------------

sub priv_msg {
    my ($server,$msg,$nick,$address,$target) = @_;
    filewrite($nick." " .$msg );
}

#--------------------------------------------------------------------
# Printing hilight's
#--------------------------------------------------------------------

sub hilight {
    my ($dest, $text, $stripped) = @_;
    if ($dest->{level} & MSGLEVEL_HILIGHT) {
    filewrite($dest->{target}. " " .$stripped );
    }
}

#--------------------------------------------------------------------
# The actual printing
#--------------------------------------------------------------------

sub filewrite {
    my ($text) = @_;
    # FIXME: there is probably a better way to get the irssi-dir...
        open(FILE,">>$ENV{HOME}/.irssi/fnotify");
    print FILE $text . "\n";
        close (FILE);
}

#--------------------------------------------------------------------
# Irssi::signal_add_last / Irssi::command_bind
#--------------------------------------------------------------------

Irssi::signal_add_last("message private", "priv_msg");
Irssi::signal_add_last("print text", "hilight");

#- end

Чтобы загрузить его в irssi, запустите следующее:

/load perl

/script load fnotify

Тогда мы нужно перенаправить его на libnotify. Для этого сохраните следующее как скрипт оболочки и запустите его при входе в систему:

# yes, we need a way to flush the file on disconnect; i don't know one
# yes, that's flush is not atomic (but good enough for me)
ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message  do  notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse  notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 25 May 2018 в 19:21
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

Я делаю это с libnotify. Я нашел это много лет назад.

Он работает как чемпион. Я использовал его с libnotify в linux (и все еще делаю, когда я на Linux-машине), но большую часть времени я сейчас на macbook, поэтому я использую рычание в качестве замены libnotify на mac.

# todo: grap topic changes use strict; use vars qw($VERSION %IRSSI); use Irssi; $VERSION = '0.0.3'; %IRSSI = ( authors => 'Thorsten Leemhuis', contact => 'fedora@leemhuis.info', name => 'fnotify', description => 'Write a notification to a file that shows who is talking to you in which channel.', url => 'http://www.leemhuis.info/files/fnotify/', license => 'GNU General Public License', changed => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $' ); #-------------------------------------------------------------------- # In parts based on knotify.pl 0.1.1 by Hugo Haas # http://larve.net/people/hugo/2005/01/knotify.pl # which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen # http://www.irssi.org/scripts/scripts/osd.pl # # Other parts based on notify.pl from Luke Macken # http://fedora.feedjack.org/user/918/ # #-------------------------------------------------------------------- #-------------------------------------------------------------------- # Private message parsing #-------------------------------------------------------------------- sub priv_msg { my ($server,$msg,$nick,$address,$target) = @_; filewrite($nick." " .$msg ); } #-------------------------------------------------------------------- # Printing hilight's #-------------------------------------------------------------------- sub hilight { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { filewrite($dest->{target}. " " .$stripped ); } } #-------------------------------------------------------------------- # The actual printing #-------------------------------------------------------------------- sub filewrite { my ($text) = @_; # FIXME: there is probably a better way to get the irssi-dir... open(FILE,">>$ENV{HOME}/.irssi/fnotify"); print FILE $text . "\n"; close (FILE); } #-------------------------------------------------------------------- # Irssi::signal_add_last / Irssi::command_bind #-------------------------------------------------------------------- Irssi::signal_add_last("message private", "priv_msg"); Irssi::signal_add_last("print text", "hilight"); #- end

Чтобы загрузить его в irssi, запустите следующее:

/load perl

/script load fnotify

Тогда мы нужно перенаправить его на libnotify. Для этого сохраните следующее как скрипт оболочки и запустите его при входе в систему:

# yes, we need a way to flush the file on disconnect; i don't know one # yes, that's flush is not atomic (but good enough for me) ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message do notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 25 July 2018 в 21:27
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

Я делаю это с libnotify. Я нашел это много лет назад.

Он работает как чемпион. Я использовал его с libnotify в linux (и все еще делаю, когда я на Linux-машине), но большую часть времени я сейчас на macbook, поэтому я использую рычание в качестве замены libnotify на mac.

# todo: grap topic changes use strict; use vars qw($VERSION %IRSSI); use Irssi; $VERSION = '0.0.3'; %IRSSI = ( authors => 'Thorsten Leemhuis', contact => 'fedora@leemhuis.info', name => 'fnotify', description => 'Write a notification to a file that shows who is talking to you in which channel.', url => 'http://www.leemhuis.info/files/fnotify/', license => 'GNU General Public License', changed => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $' ); #-------------------------------------------------------------------- # In parts based on knotify.pl 0.1.1 by Hugo Haas # http://larve.net/people/hugo/2005/01/knotify.pl # which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen # http://www.irssi.org/scripts/scripts/osd.pl # # Other parts based on notify.pl from Luke Macken # http://fedora.feedjack.org/user/918/ # #-------------------------------------------------------------------- #-------------------------------------------------------------------- # Private message parsing #-------------------------------------------------------------------- sub priv_msg { my ($server,$msg,$nick,$address,$target) = @_; filewrite($nick." " .$msg ); } #-------------------------------------------------------------------- # Printing hilight's #-------------------------------------------------------------------- sub hilight { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { filewrite($dest->{target}. " " .$stripped ); } } #-------------------------------------------------------------------- # The actual printing #-------------------------------------------------------------------- sub filewrite { my ($text) = @_; # FIXME: there is probably a better way to get the irssi-dir... open(FILE,">>$ENV{HOME}/.irssi/fnotify"); print FILE $text . "\n"; close (FILE); } #-------------------------------------------------------------------- # Irssi::signal_add_last / Irssi::command_bind #-------------------------------------------------------------------- Irssi::signal_add_last("message private", "priv_msg"); Irssi::signal_add_last("print text", "hilight"); #- end

Чтобы загрузить его в irssi, запустите следующее:

/load perl

/script load fnotify

Тогда мы нужно перенаправить его на libnotify. Для этого сохраните следующее как скрипт оболочки и запустите его при входе в систему:

# yes, we need a way to flush the file on disconnect; i don't know one # yes, that's flush is not atomic (but good enough for me) ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message do notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 2 August 2018 в 03:06
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

Я делаю это с libnotify. Я нашел это много лет назад.

Он работает как чемпион. Я использовал его с libnotify в linux (и все еще делаю, когда я на Linux-машине), но большую часть времени я сейчас на macbook, поэтому я использую рычание в качестве замены libnotify на mac.

# todo: grap topic changes use strict; use vars qw($VERSION %IRSSI); use Irssi; $VERSION = '0.0.3'; %IRSSI = ( authors => 'Thorsten Leemhuis', contact => 'fedora@leemhuis.info', name => 'fnotify', description => 'Write a notification to a file that shows who is talking to you in which channel.', url => 'http://www.leemhuis.info/files/fnotify/', license => 'GNU General Public License', changed => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $' ); #-------------------------------------------------------------------- # In parts based on knotify.pl 0.1.1 by Hugo Haas # http://larve.net/people/hugo/2005/01/knotify.pl # which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen # http://www.irssi.org/scripts/scripts/osd.pl # # Other parts based on notify.pl from Luke Macken # http://fedora.feedjack.org/user/918/ # #-------------------------------------------------------------------- #-------------------------------------------------------------------- # Private message parsing #-------------------------------------------------------------------- sub priv_msg { my ($server,$msg,$nick,$address,$target) = @_; filewrite($nick." " .$msg ); } #-------------------------------------------------------------------- # Printing hilight's #-------------------------------------------------------------------- sub hilight { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { filewrite($dest->{target}. " " .$stripped ); } } #-------------------------------------------------------------------- # The actual printing #-------------------------------------------------------------------- sub filewrite { my ($text) = @_; # FIXME: there is probably a better way to get the irssi-dir... open(FILE,">>$ENV{HOME}/.irssi/fnotify"); print FILE $text . "\n"; close (FILE); } #-------------------------------------------------------------------- # Irssi::signal_add_last / Irssi::command_bind #-------------------------------------------------------------------- Irssi::signal_add_last("message private", "priv_msg"); Irssi::signal_add_last("print text", "hilight"); #- end

Чтобы загрузить его в irssi, запустите следующее:

/load perl

/script load fnotify

Тогда мы нужно перенаправить его на libnotify. Для этого сохраните следующее как скрипт оболочки и запустите его при входе в систему:

# yes, we need a way to flush the file on disconnect; i don't know one # yes, that's flush is not atomic (but good enough for me) ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message do notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 4 August 2018 в 18:57
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

я делаю это с через libnotify. Я нашел это давным-давно.

это работает как чемпион. Я использовал, чтобы использовать его с через libnotify в Linux (и до сих пор, когда я на машине с Linux), но большую часть времени я на макбук сейчас, поэтому я использую рычать как замена через libnotify на Mac.

# todo: grap topic changes use strict; use vars qw($VERSION %IRSSI); use Irssi; $VERSION = '0.0.3'; %IRSSI = ( authors => 'Thorsten Leemhuis', contact => 'fedora@leemhuis.info', name => 'fnotify', description => 'Write a notification to a file that shows who is talking to you in which channel.', url => 'http://www.leemhuis.info/files/fnotify/', license => 'GNU General Public License', changed => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $' ); #-------------------------------------------------------------------- # In parts based on knotify.pl 0.1.1 by Hugo Haas # http://larve.net/people/hugo/2005/01/knotify.pl # which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen # http://www.irssi.org/scripts/scripts/osd.pl # # Other parts based on notify.pl from Luke Macken # http://fedora.feedjack.org/user/918/ # #-------------------------------------------------------------------- #-------------------------------------------------------------------- # Private message parsing #-------------------------------------------------------------------- sub priv_msg { my ($server,$msg,$nick,$address,$target) = @_; filewrite($nick." " .$msg ); } #-------------------------------------------------------------------- # Printing hilight's #-------------------------------------------------------------------- sub hilight { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { filewrite($dest->{target}. " " .$stripped ); } } #-------------------------------------------------------------------- # The actual printing #-------------------------------------------------------------------- sub filewrite { my ($text) = @_; # FIXME: there is probably a better way to get the irssi-dir... open(FILE,">>$ENV{HOME}/.irssi/fnotify"); print FILE $text . "\n"; close (FILE); } #-------------------------------------------------------------------- # Irssi::signal_add_last / Irssi::command_bind #-------------------------------------------------------------------- Irssi::signal_add_last("message private", "priv_msg"); Irssi::signal_add_last("print text", "hilight"); #- end

, чтобы загрузить его в irssi, выполните следующее:

/load perl

/script load fnotify

тогда нам нужно получить его направляется libnotify. Для этого сохраните следующий скрипт и запустить его на логин:

# yes, we need a way to flush the file on disconnect; i don't know one # yes, that's flush is not atomic (but good enough for me) ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message do notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 6 August 2018 в 03:19
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

Я делаю это с libnotify. Я нашел это много лет назад.

Он работает как чемпион. Я использовал его с libnotify в linux (и все еще делаю, когда я на Linux-машине), но большую часть времени я сейчас на macbook, поэтому я использую рычание в качестве замены libnotify на mac.

# todo: grap topic changes use strict; use vars qw($VERSION %IRSSI); use Irssi; $VERSION = '0.0.3'; %IRSSI = ( authors => 'Thorsten Leemhuis', contact => 'fedora@leemhuis.info', name => 'fnotify', description => 'Write a notification to a file that shows who is talking to you in which channel.', url => 'http://www.leemhuis.info/files/fnotify/', license => 'GNU General Public License', changed => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $' ); #-------------------------------------------------------------------- # In parts based on knotify.pl 0.1.1 by Hugo Haas # http://larve.net/people/hugo/2005/01/knotify.pl # which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen # http://www.irssi.org/scripts/scripts/osd.pl # # Other parts based on notify.pl from Luke Macken # http://fedora.feedjack.org/user/918/ # #-------------------------------------------------------------------- #-------------------------------------------------------------------- # Private message parsing #-------------------------------------------------------------------- sub priv_msg { my ($server,$msg,$nick,$address,$target) = @_; filewrite($nick." " .$msg ); } #-------------------------------------------------------------------- # Printing hilight's #-------------------------------------------------------------------- sub hilight { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { filewrite($dest->{target}. " " .$stripped ); } } #-------------------------------------------------------------------- # The actual printing #-------------------------------------------------------------------- sub filewrite { my ($text) = @_; # FIXME: there is probably a better way to get the irssi-dir... open(FILE,">>$ENV{HOME}/.irssi/fnotify"); print FILE $text . "\n"; close (FILE); } #-------------------------------------------------------------------- # Irssi::signal_add_last / Irssi::command_bind #-------------------------------------------------------------------- Irssi::signal_add_last("message private", "priv_msg"); Irssi::signal_add_last("print text", "hilight"); #- end

Чтобы загрузить его в irssi, запустите следующее:

/load perl

/script load fnotify

Тогда мы нужно перенаправить его на libnotify. Для этого сохраните следующее как скрипт оболочки и запустите его при входе в систему:

# yes, we need a way to flush the file on disconnect; i don't know one # yes, that's flush is not atomic (but good enough for me) ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message do notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 7 August 2018 в 21:00
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

Я делаю это с libnotify. Я нашел это много лет назад.

Он работает как чемпион. Я использовал его с libnotify в linux (и все еще делаю, когда я на Linux-машине), но большую часть времени я сейчас на macbook, поэтому я использую рычание в качестве замены libnotify на mac.

# todo: grap topic changes use strict; use vars qw($VERSION %IRSSI); use Irssi; $VERSION = '0.0.3'; %IRSSI = ( authors => 'Thorsten Leemhuis', contact => 'fedora@leemhuis.info', name => 'fnotify', description => 'Write a notification to a file that shows who is talking to you in which channel.', url => 'http://www.leemhuis.info/files/fnotify/', license => 'GNU General Public License', changed => '$Date: 2007-01-13 12:00:00 +0100 (Sat, 13 Jan 2007) $' ); #-------------------------------------------------------------------- # In parts based on knotify.pl 0.1.1 by Hugo Haas # http://larve.net/people/hugo/2005/01/knotify.pl # which is based on osd.pl 0.3.3 by Jeroen Coekaerts, Koenraad Heijlen # http://www.irssi.org/scripts/scripts/osd.pl # # Other parts based on notify.pl from Luke Macken # http://fedora.feedjack.org/user/918/ # #-------------------------------------------------------------------- #-------------------------------------------------------------------- # Private message parsing #-------------------------------------------------------------------- sub priv_msg { my ($server,$msg,$nick,$address,$target) = @_; filewrite($nick." " .$msg ); } #-------------------------------------------------------------------- # Printing hilight's #-------------------------------------------------------------------- sub hilight { my ($dest, $text, $stripped) = @_; if ($dest->{level} & MSGLEVEL_HILIGHT) { filewrite($dest->{target}. " " .$stripped ); } } #-------------------------------------------------------------------- # The actual printing #-------------------------------------------------------------------- sub filewrite { my ($text) = @_; # FIXME: there is probably a better way to get the irssi-dir... open(FILE,">>$ENV{HOME}/.irssi/fnotify"); print FILE $text . "\n"; close (FILE); } #-------------------------------------------------------------------- # Irssi::signal_add_last / Irssi::command_bind #-------------------------------------------------------------------- Irssi::signal_add_last("message private", "priv_msg"); Irssi::signal_add_last("print text", "hilight"); #- end

Чтобы загрузить его в irssi, запустите следующее:

/load perl

/script load fnotify

Тогда мы нужно перенаправить его на libnotify. Для этого сохраните следующее как скрипт оболочки и запустите его при входе в систему:

# yes, we need a way to flush the file on disconnect; i don't know one # yes, that's flush is not atomic (but good enough for me) ssh remote.system.somewhere "tail -n 10 .irssi/fnotify ; : > .irssi/fnotify ; tail -f .irssi/fnotify " | sed -u 's/[<@&]//g' | while read heading message do notify-send -i gtk-dialog-info -t 300000 -- "${heading}" "${message}"; done # the sed -u 's/[<@&]//g' is needed as those characters might confuse notify-send (FIXME: is that a bug or a feature?)
7
ответ дан 10 August 2018 в 09:23
  • 1
    Lame GROWLer. ;) Я взгляну. – jrg♦ 16 September 2011 в 04:11
  • 2
    Я проверю это позже, через день после публикации этого Q я взломал скрипт perl и python, который я использовал тогда. – Lekensteyn 16 September 2011 в 14:18

Другие вопросы по тегам:

Похожие вопросы: