-
Notifications
You must be signed in to change notification settings - Fork 1
/
send_message.pl
executable file
·120 lines (95 loc) · 2.51 KB
/
send_message.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#!/usr/bin/perl
use strict;
use warnings;
# Unicode
use utf8;
binmode(STDIN, ":encoding(UTF-8)");
binmode(STDOUT, ":encoding(UTF-8)");
binmode(STDERR, ":encoding(UTF-8)");
our $version = '1.2.0';
# core modules
use Getopt::Std;
use FindBin qw($Bin);
use lib $Bin.'/lib';
# CPAN modules
use LWP;
use Mojo::JSON qw(decode_json encode_json);
# debug
#use warnings;
#use diagnostics;
# debug
use Env;
my $opts={};
getopts('sdc:', $opts);
usage() if !defined $opts->{c};
die "Can't read config $opts->{c}!"
if !-r $opts->{c};
my $message = join "", <STDIN>;
die 'Not message is specified! Specify your message via STDIN.'
if !defined $message;
my $config = read_config($opts->{c});
# disable SSL cert verification
# if this doesn't work you need to install the following packages:
# IO::Socket::SSL LWP LWP::Protocol::https
$ENV{PERL_NET_HTTPS_SSL_SOCKET_CLASS} = 'IO::Socket::SSL'
if $opts->{s};
exit(main());
sub usage{
print <<EOF;
Icinga matrix notifier version $version
Usage:
echo 'Message text (also <strong>bold</strong>).' | $0 -c config.cfg [-ds]
-c config file
-d debug
-s disable SSL cert verification
EOF
exit 1;
}
sub read_config{
my $handle;
my $config_name=pop;
my $config = {};
open $handle, "<:encoding(utf8)", $config_name;
while (<$handle>) {
chomp; # no newline
s/#.*//; # no comments
s/^\s+//; # no leading white
s/\s+$//; # no trailing white
next unless length; # anything left?
#my ($var, $value) = split(/\s*=\s*/, $_, 2);
/([^=\s]+)\s*=\s*([^#]+)(\s*|#).*/;
my ($var, $value) = ($1, $2);
$config->{$var} = $value;
}
close $handle;
return $config;
}
sub main{
# build URL
$config->{url} = join '', $config->{server_url},
'/_matrix/client/r0/rooms/',
$config->{room},
'/send/m.room.message/',
int(rand(10000)),
'?access_token=',
$config->{access_token};
# create new LWC object
my $browser = LWP::UserAgent->new;
$browser = LWP::UserAgent->new(ssl_opts => { SSL_verify_mode => 0x00 })
if $opts->{s};
my $data = {
"msgtype" => "m.text",
"format" => "org.matrix.custom.html",
"formatted_body" => $message,
"body" => $message
};
# encode data to JSON and send via put request
my $response = $browser->put( $config->{url}, [], Content => encode_json($data) );
# error reporting
die "Error: ",$response->content unless $response->is_success;
if ($opts->{d}) {
print 'Content type is ', $response->content_type, $/;
print 'Content is:', $response->content, $/;
}
return 0;
}