1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
|
#!/usr/bin/env perl
#
# Author: Guillermo Ramos <gramos@gramos.me> (2019)
#
# Dependencies: Try-Tiny, HTTP-Message, libwww-perl
#
# Run `tgserver -h` for quick help, or `tgserver -h -v` for full manual.
################################################################################
use strict;
use warnings;
use Try::Tiny;
$main::VERSION = "0.1.1";
use Getopt::Long qw(:config auto_version);
use Pod::Usage qw<pod2usage>;
use Data::Dumper;
use MIME::Base64 qw<decode_base64>;
use JSON qw<decode_json>;
use FindBin;
use lib "$FindBin::Bin/lib";
use TgLib qw<fetch_token>;
require TgLib::Api;
require TgLib::Cache;
require TgLib::Logger;
my $TOKEN;
my $VERBOSE = 0;
my $HELP;
GetOptions("token=s" => \$TOKEN,
"verbose+" => \$VERBOSE,
"help" => \$HELP);
pod2usage(-verbose => $VERBOSE+1) if $HELP or not @ARGV;
my $logger = TgLib::Logger->new($VERBOSE);
# 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");
my $cache = TgLib::Cache->new($logger);
my $api = TgLib::Api->new($TOKEN, $logger);
my $sleep_exp = 1;
while (1) {
# FIXME magic timeout
my @updates = eval { @{$api->get_updates(3600, $cache->offset)} };
if ($@) {
chomp $@;
print "ERROR: $@\n";
sleep($sleep_exp);
$sleep_exp *= 2 unless $sleep_exp >= 32;
} else {
$sleep_exp = 1;
};
foreach my $update (@updates) {
# Cache current offset
$cache->offset($update->{'update_id'}+1);
$logger->debug(sprintf "Update %s", Dumper($update));
if ($update->{'message'}) {
my $msg = $update->{'message'};
$ENV{'TGUTILS_CHAT_ID'} = $msg->{'chat'}{'id'};
$ENV{'TGUTILS_FROM_ID'} = $msg->{'from'}{'id'};
$ENV{'TGUTILS_FROM_USERNAME'} = $msg->{'from'}{'username'};
if (exists $msg->{'photo'}) {
handle_photo($msg);
} else {
handle_text($msg);
}
} elsif ($update->{'edited_message'}) {
my $msg = $update->{'edited_message'};
# TODO
$logger->info("Received edited message, ignoring...");
} else {
$logger->warn("Received unknown update type (ignoring): $update\n");
}
}
}
sub handle_photo {
my $msg = shift;
my $photos = $msg->{'photo'};
my $chat_id = $msg->{'chat'}{'id'};
my $photo = (sort { $b->{'width'} <=> $a->{'width'} } @$photos)[0];
$logger->info(sprintf "%s: [Photo %s (size=%d)] -> 🤖\n",
$chat_id, $photo->{'file_id'}, $photo->{'file_size'});
my $file = $api->get_file($photo->{'file_id'});
$ENV{'TGUTILS_TYPE'} = 'IMAGE';
my $response = pipe_send($file, @ARGV);
reply($chat_id, $response);
}
sub handle_text {
my $msg = shift;
my $text = $msg->{'text'};
my $chat_id = $msg->{'chat'}{'id'};
$logger->info("$chat_id: '$text' -> 🤖\n");
$ENV{'TGUTILS_TYPE'} = 'TEXT';
my $response = pipe_send($text, @ARGV);
reply($chat_id, $response);
}
sub reply {
my $chat_id = shift;
my $response = shift;
my $type = ref $response eq 'HASH' ? $response->{'type'} : 'TEXT';
if ($type eq 'DOCUMENT') {
my $caption = $response->{'caption'};
$logger->info("🤖: [Document '$caption'] -> $chat_id\n");
$api->send_document($chat_id, decode_base64 $response->{'content'},
$response->{'filename'}, $caption);
} elsif ($type eq 'PHOTO') {
my $caption = $response->{'caption'};
$logger->info("🤖: [Photo '$caption'] -> $chat_id\n");
$api->send_photo($chat_id, decode_base64 $response->{'content'},
$response->{'filename'}, $caption);
} elsif ($type eq 'TEXT' and $response) {
$logger->info("🤖: '$response' -> $chat_id\n");
$api->send_message($chat_id, $response);
} else {
$logger->debug("Empty response, skipping\n");
}
}
sub pipe_send {
my ($content, @cmd) = @_;
$SIG{PIPE} = sub {
$logger->debug("SIGPIPE received (@_), ignoring\n");
};
use IPC::Open2 qw<open2>;
my $pid = open2(my $progr, my $progw, @cmd);
print $progw $content;
close($progw);
# Don't read a single line
my $oldsep = $/;
$/ = undef;
binmode($progr);
my $response = <$progr>;
close($progr);
$/ = $oldsep;
waitpid $pid, 0; # collect the child process
chomp $response;
return try { decode_json $response } catch { $response };
}
__END__
=head1 NAME
tgserver - Interact with a Telegram Bot
=head1 SYNOPSIS
B<tgserver> [B<-h> | B<--help>] [B<-v>]
B<tgserver> [I<options>] -- I<prog>
=head1 OPTIONS
=over
=item B<--token>=I<token>, B<-t> I<token>
Bot token (see B<AUTHENTICATION>)
=item B<--version>
Show version
=item B<--verbose>, B<-v>
Show more information (combine with B<-h> to see full manual)
=item B<--help>, B<-h>
Show this message
=back
=head1 DESCRIPTION
This program waits for Telegram updates from the bot identified by I<token>. For
every update it runs I<prog> with stdin piped to the update, and sending stdout
back as response.
=head1 EXAMPLE
tgserver --token 123456789:abcdefghijklmnopqrstuvwxyzABCDEFGHI -- \
cowsay -f moofasa
=head1 AUTHENTICATION
To get the bot token, this program will check (in order):
=over 2
=item -
The B<--token> CLI argument
=item -
The B<TGUTILS_TOKEN> environment variable
=item -
The contents of I<$XDG_CONFIG_HOME>B</tgutils_token> (usually B<~/.config/tgutils_token>)
=back
=cut
|