Telegram.pm untested

filter: Statementstmt 0.0% 0 / 189 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 42 MC/DCmcdc 0.0% 0 / 24 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 354 CC 26 SCAR 32.7
CC
26
Cov
0%
_process_getUpdates_results
110.0
set_webhook
20.0
start_polling
20.0
CRAP 26.4
1 package Bot::Telegram;
2 # ABSTRACT: a micro^W nano framework for creating Telegram bots based on L<WWW::Telegram::BotAPI>
3 our $VERSION = '1.10'; # VERSION
4  
5 use v5.16.3;
6  
7 use Mojo::Base 'Mojo::EventEmitter';
8 use WWW::Telegram::BotAPI;
9 use Mojo::Promise;
10 use Mojo::Log;
11  
12 use Mojo::JSON 'encode_json';
13 use Mojo::Transaction::HTTP;
14 use Mojo::Message::Response;
15  
16 use Bot::Telegram::X::InvalidArgumentsError;
17 use Bot::Telegram::X::InvalidStateError;
18  
19 use constant ERR_NODETAILS => 'no details available';
20  
21 use constant DEFAULT_POLLING_TIMEOUT => 20;
22 use constant DEFAULT_POLLING_INTERVAL => 0.3;
23  
24 use constant DEFAULT_POLLING_ERROR_CB => sub {
25 my ($self, $tx, $type) = @_;
26  
27 my $message = sub {
28 return $tx -> {error}{msg}
29 unless $self -> is_async;
30  
31 for ($type) {
32 /agent/ and return $tx -> error -> {message};
33 /api/ and return ($tx -> res -> json // {}) -> {description};
34 }
35 } -> () || ERR_NODETAILS;
36  
37 $self -> log -> warn("Polling failed (error type: $type): $message");
38 };
39  
40 use constant DEFAULT_CALLBACK_ERROR_CB => sub {
41 my ($self, undef, $err) = @_;
42 $self -> log -> warn("Update processing failed: $err");
43 };
44  
45 has [qw/api current_update polling_config/];
46 has [qw/_polling
47 _polling_timer
48 _polling_interval
49 _polling_request_id/
50 ];
51  
52 has callbacks => sub { {} };
53 has ioloop => sub { Mojo::IOLoop -> new };
54 has log => sub { Mojo::Log -> new -> level('info') };
55  
56 sub new {
57 my $self = shift -> SUPER::new(@_);
58  
59 $self -> on(polling_error => DEFAULT_POLLING_ERROR_CB);
60 $self -> on(callback_error => DEFAULT_CALLBACK_ERROR_CB);
61  
62 $self
63 }
64  
65 ################################################################################
66 # General
67 ################################################################################
68  
69 sub init_api {
70 my ($self, %args) = @_;
71  
72 Bot::Telegram::X::InvalidArgumentsError
73 -> throw('No token provided')
74 unless exists $args{token};
75  
76 $args{async} //= 1;
77  
78 $self -> api(WWW::Telegram::BotAPI -> new(%args));
79  
80 return $self;
81 }
82  
83 sub is_async {
84 my $self = shift;
85  
86 Bot::Telegram::X::InvalidStateError
87 -> throw('API is not initialized')
88 unless $self -> api;
89  
90 $self -> api -> {async};
91 }
92  
93 sub api_request { shift -> api -> api_request(@_) }
94 sub api_request_p {
95 my ($self, @args) = @_;
96  
97 Mojo::Promise -> new(sub {
98 my ($resolve, $reject) = @_;
99  
100 $self -> api -> api_request(@args, sub {
101 my ($ua, $tx) = @_;
102 my $response = $tx -> res -> json;
103  
104 ((!$tx -> error && ref $response && $$response{ok})
105 ? $resolve
106 : $reject) -> ($ua, $tx);
107 })
108 });
109 }
110  
111 ################################################################################
112 # Callbacks
113 ################################################################################
114  
115 sub set_callbacks {
116 my ($self, %cbs) = @_;
117  
118 while ( my ($key, $val) = each %cbs) {
119 $self -> callbacks -> {$key} = $val;
120 }
121  
122 return $self;
123 }
124  
125 sub remove_callbacks {
126 my ($self, @events) = @_;
127  
128 foreach my $event (@events) {
129 delete $self -> callbacks -> {$event};
130 }
131  
132 return $self;
133 }
134  
135 ################################################################################
136 # Updates
137 ################################################################################
138  
139 sub shift_offset {
140 my $self = shift;
141  
142 for (my $update = $self -> current_update) {
143 $self -> polling_config -> {offset} = $$update{update_id} + 1
144 if $$update{update_id} >= $self -> polling_config -> {offset};
145 }
146  
147 $self
148 }
149  
150 sub process_update {
151 my ($self, $update) = @_;
152  
153 $self -> current_update($update);
154 my $type = $self -> _get_update_type($update);
155  
156 eval {
157 # If update type is recognized, call the appropriate callback
158 if ($type) {
159 $self -> callbacks
160 -> {$type}
161 -> ($self, $update);
162 }
163  
164 # Otherwise report an unknown update
165 else { $self -> emit(unknown_update => $update) }
166 };
167  
168 # Report a callback error if we failed to handle the update
169 $self -> emit(callback_error => $update, $@) if $@;
170  
171 return $self;
172 }
173  
174 # Return the update type if we have a callback for it
175 # Or just return zero, if we don't
176 sub _get_update_type {
177 my ($self, $update) = @_;
178  
179 exists $$update{$_}
180 and return $_
181 for keys %{ $self -> callbacks };
182  
183 return 0;
184 }
185  
186 ################################################################################
187 # Webhook
188 ################################################################################
189  
190 sub set_webhook {
191 my ($self, $config, $cb) = @_;
192  
193 Bot::Telegram::X::InvalidStateError
194 -> throw('Disable long polling first')
195 if $self -> is_polling;
196  
197 Bot::Telegram::X::InvalidArgumentsError
198 -> throw('No config provided')
199 unless ref $config;
200  
201 $self -> api -> api_request(
202 setWebhook => $config,
203 ref $cb eq 'CODE' ? $cb : undef);
204  
205 return $self;
206 }
207  
208 ################################################################################
209 # Long polling
210 ################################################################################
211  
212 sub start_polling {
213 my $self = shift;
214 my $config = $self -> polling_config;
215 if (ref $_[0] eq 'HASH') {
216 $config = shift;
217 $config -> {offset} //= 0; # make sure we won't get any uninitiailzed warnings in shift_offset
218 }
219  
220 my (%opts) = @_;
221  
222 if ($opts{restart}) {
223 $self -> stop_polling;
224 } else {
225 Bot::Telegram::X::InvalidStateError
226 -> throw('Already running')
227 if $self -> is_polling;
228 }
229  
230 $self -> polling_config($config // { timeout => DEFAULT_POLLING_TIMEOUT, offset => 0 });
231  
232 $self -> _polling_interval($opts{interval} // DEFAULT_POLLING_INTERVAL);
233 $self -> _polling(1);
234 $self -> _poll;
235 }
236  
237 sub stop_polling {
238 my $self = shift;
239  
240 return $self unless $self -> is_polling;
241  
242 for (my $agent = $self -> api -> agent) {
243 $self -> _polling(undef);
244  
245 # In synchronous mode, it's enough to simply clear state
246 return $self -> _polling_interval(undef)
247 unless $agent -> isa('Mojo::UserAgent')
248 and $self -> is_async;
249  
250 # In asynchronous mode, we also need to cancel existing timers
251 for (my $loop = Mojo::IOLoop -> singleton) {
252 $loop -> remove($self -> _polling_request_id);
253 $loop -> remove($self -> _polling_timer)
254 if $self -> _polling_timer; # if another request is scheduled, cancel it
255 }
256  
257 # Reset state
258 $self -> _polling_request_id(undef)
259 -> _polling_interval(undef)
260 -> _polling_timer(undef);
261 }
262  
263 $self
264 }
265  
266 sub is_polling { !! shift -> _polling }
267  
268 # In asynchronous mode: process getUpdates response or handle errors, if any
269 # In synchronous mode, WWW::Telegram::BotAPI::parse_error takes care of error handling for us.
270 sub _process_getUpdates_results {
271 my $self = shift;
272 my $async = $self -> is_async;
273 my ($response, $error);
274  
275 $self -> log -> trace('processing getUpdates results');
276  
277 my $retry_after;
278  
279 if ($async) {
280 my ($ua, $tx) = @_;
281 $response = $tx -> res -> json // {};
282  
283 # Error
284 if ($error = ($tx -> error or not $$response{ok})) {
285 my $type = eval {
286 return 'api' if $$response{error_code};
287 return 'agent' if $tx -> error;
288 } // 'unknown';
289  
290 $self -> emit(polling_error => $tx, $type);
291 }
292 } else {
293 ($response, $error) = @_;
294 # NOTE: $response and $error are mutually exclusive - only one is `defined` at a time
295  
296 if ($error) {
297 $error = $self -> api -> parse_error;
298  
299 # no way to access the original $tx in synchronous mode
300 # https://metacpan.org/dist/WWW-Telegram-BotAPI/source/lib/WWW/Telegram/BotAPI.pm#L228
301 $self -> emit(polling_error => { error => $error }, $$error{type});
302 }
303 }
304  
305 # Handle rate limits
306 if (exists $response -> {parameters}{retry_after}) {
307 $retry_after = $response -> {parameters}{retry_after};
308 $self -> log -> info("Rate limit exceeded, waiting ${retry_after}s before polling again");
309 }
310  
311 # Process the updates we have retrieved (if any) and poll for more
312 # (unless someone or something has disabled the polling loop in the meantime)
313 unless ($error) {
314 for my $result ($$response{result}) {
315 # last unless ref $result eq 'ARRAY'; # nothing to process
316  
317 $self -> process_update($_)
318 -> shift_offset
319 for @$result;
320 }
321 }
322  
323 return unless $self -> is_polling;
324 $self -> log -> trace('still polling, scheduling another iteration...');
325  
326 if ($async) {
327 my $tid = Mojo::IOLoop -> timer(
328 $retry_after // $self -> _polling_interval,
329 sub { $self -> tap(sub { $self -> log -> trace("it's polling time!") })
330 -> _poll });
331  
332 $self -> _polling_timer($tid);
333 } else {
334 my $d = $retry_after // $self -> _polling_interval;
335  
336 # Sleep
337 $self -> ioloop -> timer($d, sub { $self -> ioloop -> stop });
338 $self -> ioloop -> start;
339 $self -> log -> trace("it's polling time!");
340  
341 $self -> _poll;
342 }
343 }
344  
345 sub _poll {
346 my $self = shift;
347  
348 $self -> log -> trace('polling');
349  
350 if ($self -> is_async) {
351 my $id = $self -> api -> api_request(
352 getUpdates => $self -> polling_config,
353 sub { $self -> _process_getUpdates_results(@_) }
354 );
355  
356 # Assuming api_request always returns a valid ioloop connection ID when in asynchronous mode...
357 $self -> _polling_request_id($id);
358 } else {
359 my $response = eval {
360 $self -> api -> api_request(
361 getUpdates => $self -> polling_config)
362 };
363  
364 $self -> _process_getUpdates_results($response, $@);
365 }
366 }
367  
368 1
369  
370 __END__