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
|
#!/usr/bin/env perl6
use v6;
use lib "lib";
use JSON::Tiny;
use Matrix::Client;
class Bot {
has $!name = "!d";
has $!username is required;
has Bool $!register = False;
has @!room-ids;
has $!on-event;
has Matrix::Client $!client;
submethod BUILD(:$username!, :$password!, :$home-server!, :@room-ids!, :$on-event!) {
$!client = Matrix::Client.new(:home-server($home-server));
$!username = $username;
@!room-ids = @room-ids;
$!on-event = $on-event;
$!client.login($!username, $password);
}
method join-rooms() {
@!room-ids.map: { $!client.join-room($_) }
}
method shutdown() {
$!client.save-auth-data;
}
method listen() {
say "Listening";
my $since = "";
loop {
my $sync = { room => timeline => limit => 1 };
my $data = from-json($!client.sync(sync-filter => $sync, since => $since).content);
$since = $data<next_batch>;
for $data<rooms><join>.kv -> $room-id, $d {
for @($d<timeline><events>) -> $ev {
if $ev<type> eq "m.room.message" {
if $ev<content><body>.match($!name) {
my $bot-msg = $!on-event($ev);
if so $bot-msg {
say "Sending message $bot-msg";
my $res = $!client.send($room-id, ~$bot-msg);
if $res.is-success {
say $res.content;
} else {
warn $res.content;
die $res.status-line;
}
}
}
}
}
}
sleep(10);
}
}
}
sub MAIN(Str:D $username, Str:D $password, :$home-server = "https://matrix.deprecated.org") {
my @rooms = "!bpHGYOiCGlvCZarfMH:matrix.deprecated.org";
my $bot = Bot.new:
username => $username,
password => $password,
home-server => $home-server,
room-ids => @rooms,
on-event => -> $ev {
given $ev<content><body> {
when /"say hi"/ {
say "Someone is saying hi!";
"Hello @ {DateTime.now}"
}
default { say "Dunno what's telling me"; Str }
}
};
signal(SIGINT).tap({
say "Bye";
$bot.shutdown;
exit 0;
});
my $ress = $bot.join-rooms;
for @($ress) -> $res {
if !$res.is-success {
warn $res.status-line;
warn $res.content;
die "Error joinig to rooms";
}
}
$bot.listen;
}
|