From f2fd55f38582561453f5ca01d0bf32095588ff06 Mon Sep 17 00:00:00 2001 From: getriot Date: Sat, 18 Jan 2025 04:14:34 +0100 Subject: [PATCH] added callback support and message_type subscriptions --- csbot3.pl | 1 + src/lib/CsBot3/Matrix.pm | 40 ++++++++++++++++++++++++++++++---------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/csbot3.pl b/csbot3.pl index 69580b1..42c0c20 100644 --- a/csbot3.pl +++ b/csbot3.pl @@ -68,5 +68,6 @@ my $login = CsBot3::Matrix::login(\%credentials); if($login) { CsBot3::Matrix::join_room($room); + CsBot3::Matrix::subscribe("m.room.message", \&CsBot3::Matrix::send_message); CsBot3::Matrix->read_events(); } \ No newline at end of file diff --git a/src/lib/CsBot3/Matrix.pm b/src/lib/CsBot3/Matrix.pm index 094e1bf..56f0049 100644 --- a/src/lib/CsBot3/Matrix.pm +++ b/src/lib/CsBot3/Matrix.pm @@ -31,6 +31,9 @@ $lwp->agent('CsMatrix'); our @rooms = (); +our @event_types = ("m.room.message"); +our %events_subscriptions = (); + sub new { my ($server) = @_; @@ -160,15 +163,18 @@ sub long_poll_event { foreach my $room (@CsBot3::Matrix::rooms) { if(defined $json_response->{rooms}->{join}->{$room}->{timeline}->{events}) { $events = $json_response->{rooms}->{join}->{$room}->{timeline}->{events}; + foreach my $event (@$events) { - - if( - $event->{type} eq "m.room.message" && - time() - $event->{origin_server_ts} <= 1000 && - defined $CsBot3::Matrix::user && - $event->{sender} ne $CsBot3::Matrix::user - ) { - send_message($room); + foreach my $subscripted_event_name (keys %CsBot3::Matrix::events_subscriptions) { + if( + $event->{type} eq $subscripted_event_name && + time() - $event->{origin_server_ts} <= 1000 && + defined $CsBot3::Matrix::user && + $event->{sender} ne $CsBot3::Matrix::user + ) { + $event->{room} = $room; + $CsBot3::Matrix::events_subscriptions{$subscripted_event_name}->($event); + } } } } @@ -181,11 +187,11 @@ sub long_poll_event { } sub send_message { - my ($room) = @_; + my ($event) = @_; my $request_url = get_request_url('room_send_message'); - $request_url .= "/$room/send/m.room.message/$CsBot3::Matrix::tnx_id"; + $request_url .= "/$event->{room}/send/m.room.message/$CsBot3::Matrix::tnx_id"; $CsBot3::Matrix::tnx_id += 1; @@ -210,4 +216,18 @@ sub send_message { return 1; } +sub subscribe { + my ($event_type, $callback) = @_; + + foreach my $allowed_event (@CsBot3::Matrix::event_types) { + if($event_type eq $allowed_event) { + $CsBot3::Matrix::events_subscriptions{$event_type} = $callback; + + return 1; + } + } + + return 0; +} + 1; \ No newline at end of file