From c393976ab1a2a93f2376f603497e67eabcd30dd7 Mon Sep 17 00:00:00 2001 From: Pragmatic Software Date: Sun, 25 Jul 2021 18:43:35 -0700 Subject: [PATCH] Add RunCommand plugin --- lib/PBot/Plugin/RunCommand.pm | 58 +++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 lib/PBot/Plugin/RunCommand.pm diff --git a/lib/PBot/Plugin/RunCommand.pm b/lib/PBot/Plugin/RunCommand.pm new file mode 100644 index 00000000..ba1093f1 --- /dev/null +++ b/lib/PBot/Plugin/RunCommand.pm @@ -0,0 +1,58 @@ +# File: RunCommand.pm +# +# Purpose: Runs a command, streaming each line of output in real-time. + +# SPDX-FileCopyrightText: 2021 Pragmatic Software +# SPDX-License-Identifier: MIT + +package PBot::Plugin::RunCommand; +use parent 'PBot::Plugin::Base'; + +use PBot::Imports; + +use IPC::Run qw/start pump/; + +sub initialize { + my ($self, %conf) = @_; + + $self->{pbot}->{commands}->register(sub { $self->cmd_runcmd(@_) }, "runcmd", 1); +} + +sub unload { + my $self = shift; + $self->{pbot}->{commands}->unregister("runcmd"); +} + +sub cmd_runcmd { + my ($self, $context) = @_; + + my @args = $self->{pbot}->{interpreter}->split_line($context->{arguments}, strip_quotes => 1); + + my ($in, $out, $err); + + my $h = start \@args, \$in, \$out, \$err; + + my $lines = 0; + + while (pump $h) { + if ($out =~ s/^(.*?)\n//) { + $self->{pbot}->{conn}->privmsg($context->{from}, $1); + $lines++; + } + } + + finish $h; + + if (length $out) { + my @lines = split /\n/, $out; + + foreach my $line (@lines) { + $self->{pbot}->{conn}->privmsg($context->{from}, $line); + $lines++; + } + } + + return "No output." if not $lines; +} + +1;