aboutsummaryrefslogtreecommitdiff
path: root/tgsend
diff options
context:
space:
mode:
authorGuillermo Ramos2019-06-25 12:19:59 +0200
committerGuillermo Ramos2019-06-25 12:44:04 +0200
commit16cd42e6fbfbf6fff06fd50926ac374b771e3f97 (patch)
tree8427a9f4afceacaffb4cd5594524678ccbf7060a /tgsend
parentd7f4ee6f0f86f462c26a27eb8d267abd592f01af (diff)
downloadtgutils-16cd42e6fbfbf6fff06fd50926ac374b771e3f97.tar.gz
Move Telegram comm logic to TgLib::Api
Diffstat (limited to 'tgsend')
-rwxr-xr-xtgsend42
1 files changed, 12 insertions, 30 deletions
diff --git a/tgsend b/tgsend
index 9b239e2..e9100b7 100755
--- a/tgsend
+++ b/tgsend
@@ -7,28 +7,24 @@
# Dependencies: HTTP-Message, JSON
################################################################################
-$main::VERSION = "0.1.0";
+$main::VERSION = "0.1.1";
use Getopt::Long qw(:config auto_version);
use Pod::Usage qw<pod2usage>;
-use LWP::UserAgent;
-use Data::Dumper;
-
-use HTTP::Request;
-use JSON qw<encode_json>;
# Local modules
use FindBin;
use lib "$FindBin::Bin/lib";
use TgLib qw<fetch_token>;
-use TgLib::Env qw<$HOME $CONFIG_HOME $CACHE_HOME>;
require TgLib::Logger;
+require TgLib::Api;
my $TOKEN;
my $PRETEND;
my $VERBOSE = 0;
my $HELP;
+# Parse CLI options
GetOptions("token=s" => \$TOKEN,
"pretend" => \$PRETEND,
"verbose+" => \$VERBOSE,
@@ -37,37 +33,23 @@ pod2usage(-verbose => $VERBOSE+1) if $HELP or ! @ARGV;
my $logger = TgLib::Logger->new($VERBOSE);
-# If token was not specified in CLI, get it from ENV/file
+# Fetch token: CLI || env || file
$TOKEN ||= fetch_token() or
pod2usage(-message => "ERROR: Unable to get bot token ($!).\n",
-verbose => 99, -sections => "AUTHENTICATION");
# Read text from stdin
undef $/;
-my $TEXT = <STDIN>;
-
-my $ua = LWP::UserAgent->new;
-my $URI = "https://api.telegram.org/bot$TOKEN/sendMessage";
-sub send_message {
- my $chat_id = shift;
- my $content = encode_json {'chat_id' => $chat_id, 'text' => $TEXT};
- my $req = HTTP::Request->new("POST", $URI,
- ["Content-Type", "application/json"], $content);
- if ($VERBOSE || $PRETEND) {
- $logger->info("Sending to $chat_id:\n====\n$TEXT\n====\n");
- $logger->debug(sprintf "Request:\n%s\n", Dumper($req));
- }
- unless ($PRETEND) {
- my $resp = $ua->request($req);
- print STDERR "Response:\n", Dumper($resp), "\n" if $VERBOSE > 1;
- if ($resp->is_error()) {
- die $resp->message;
- }
- }
+my $text = <STDIN>;
+
+# Send message to chats (or pretend to)
+if ($PRETEND) {
+ $logger->info("(prentend) Sending to $_:\n====\n$text\n====\n") foreach @ARGV;
+} else {
+ my $api = TgLib::Api->new($TOKEN, $logger);
+ $api->send_message($_, $text) foreach @ARGV;
}
-send_message($_) foreach @ARGV;
-
__END__