#!/usr/bin/env perl # # Author: Guillermo Ramos (2019) # # Run `tgsend -h` for quick help, or `tgsend -h -v` for full manual. # # Dependencies: HTTP-Message, JSON ################################################################################ $main::VERSION = "0.1.0"; use Getopt::Long qw(:config auto_version); use Pod::Usage qw; use LWP::UserAgent; use Data::Dumper; use HTTP::Request; use JSON qw; # Local modules use FindBin; use lib "$FindBin::Bin/lib"; use TgLib qw; use TgLib::Env qw<$HOME $CONFIG_HOME $CACHE_HOME>; my $TOKEN; my $PRETEND; my $VERBOSE = 0; my $HELP; GetOptions("token=s" => \$TOKEN, "pretend" => \$PRETEND, "verbose+" => \$VERBOSE, "help" => \$HELP); pod2usage(-verbose => $VERBOSE+1) if $HELP or ! @ARGV; # If token was not specified in CLI, get it from 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 = ; 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) { print STDERR "Sending to $chat_id:\n====\n$TEXT\n====\n"; print STDERR "Request:\n", Dumper($req), "\n" if $VERBOSE > 1; } unless ($PRETEND) { my $resp = $ua->request($req); print STDERR "Response:\n", Dumper($resp), "\n" if $VERBOSE > 1; if ($resp->is_error()) { die $resp->message; } } } send_message($_) foreach @ARGV; __END__ =head1 NAME tgsend - Send message to a Telegram chat using a bot token =head1 SYNOPSIS tgsend [-h | --help] tgsend [options] [chatid1 chatid2 ...] =head1 OPTIONS --pretend | -p Do not actually do anything --token | -t Bot token (see AUTHENTICATION) --version Show version --verbose | -v Show more information (combine with -h to see full manual) --help | -h Show this message =head1 DESCRIPTION This program sends its standard input to the Telegram chats whose IDs are passed as arguments, using the given bot token. =head1 AUTHENTICATION To get the bot token, this program will check (in order): - The "--token" CLI argument - The "TGUTILS_TOKEN" environment variable - The contents of "$XDG_CONFIG_HOME/tgutils_token" (usually ~/.config/tgutils_token) =cut