added callback support and message_type subscriptions

This commit is contained in:
getriot 2025-01-18 04:14:34 +01:00
parent 00967c7637
commit f2fd55f385
2 changed files with 31 additions and 10 deletions

View file

@ -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();
}

View file

@ -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;