Stream logs to Slack in Perl

I want to stream my logs on my home RPi3b to a Slack channel for my vacation side project. With some searches I found an article including a simple shell script to implement this function: "Stream Any Log File to Slack Using curl".

However it's a little tricky as the script replaces " to ' as escaping mechanism. I would prefer to use more formal way to implement this, also, I haven't written Perl for a while, so I have decided to implement this function in Perl:

#!/usr/bin/perl
use v5.14;
use strict;
use warnings;
use IO::File;
use JSON::PP;
use WWW::Mechanize;
sub main() {
my $webhook_url = $ARGV[0] or die 'no webhook_url';
my $filename = $ARGV[1] or die 'no filename';
my $filter = $ARGV[2] // '';
my $fh = IO::File->new("tail -F -n0 ${filename} |");
my $ua = WWW::Mechanize->new;
while (my $line = <$fh>) {
next unless $line =~ $filter;
my $payload = {text => $line, type => 'plain_text'};
$ua->post(
$webhook_url,
'Content-Type' => 'application/json',
Content => encode_json($payload),
);
}
$fh->close;
}
&main;
__END__

In this script there are some notes:

  • Choosing tail -F instead of File::Tail is because File::Tail is quite old and no inotify implementation. On the other side, tail performs well in this section.
  • Choosing JSON::PP (pure perl version) is because it's built-in in Perl 5.14+, and that's also why I have added use v5.14 requirement in the beginning.
  • Choosing WWW::Mechanize for API calling is because there is no built-in module able to handle HTTPS connections, therefore I have decided to install a familiar one (for me).

btw, // operator has been introduced in Perl 5.10, and I didn't think it last there for such a long time...