From 88a1865f01f8849140fab0735eeffee99e34d7cf Mon Sep 17 00:00:00 2001 From: Matias Linares Date: Tue, 13 Feb 2018 20:56:26 -0300 Subject: Update example to use the new Response --- examples/bot.p6 | 53 +++++++++++++++++------------------------------------ 1 file changed, 17 insertions(+), 36 deletions(-) diff --git a/examples/bot.p6 b/examples/bot.p6 index 2656770..24ab1e6 100755 --- a/examples/bot.p6 +++ b/examples/bot.p6 @@ -3,30 +3,25 @@ use v6; use lib "lib"; use JSON::Tiny; use Matrix::Client; +use Matrix::Client::Exception; 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!) { + submethod BUILD(:$username!, :$password!, :$home-server!,:$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; } @@ -37,23 +32,20 @@ class Bot { loop { my $sync = { room => timeline => limit => 1 }; - my $data = from-json($!client.sync(sync-filter => $sync, since => $since).content); - $since = $data; + my $response = $!client.sync(sync-filter => $sync, since => $since); + $since = $response.next-batch; - for $data.kv -> $room-id, $d { - for @($d) -> $ev { - if $ev eq "m.room.message" { - if $ev.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; - } + for $response.joined-rooms -> $room { + for $room.timeline + .events + .grep(*.type eq 'm.room.message') -> $msg { + if $msg.content.match($!name) { + my $bot-msg = $!on-event($msg); + if so $bot-msg { + say "Sending message $bot-msg"; + try { + CATCH { when X::Matrix::Response { .message }} + my $res = $!client.send($room.room-id, ~$bot-msg); } } } @@ -65,16 +57,14 @@ class Bot { } 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 { + given $ev.content { when /"say hi"/ { - say "Someone is saying hi!"; + say "Someone says {$ev.content}"; "Hello @ {DateTime.now}" } default { say "Dunno what's telling me"; Str } @@ -87,14 +77,5 @@ sub MAIN(Str:D $username, Str:D $password, :$home-server = "https://matrix.depre 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; } -- cgit v1.2.3-70-g09d2