| 1 | package Telebot::Plugin::Telegram; | ||
| 2 | |||
| 3 | use Mojo::Base 'Mojolicious::Plugin', -signatures; | ||
| 4 | use Mojo::UserAgent; | ||
| 5 | use Carp 'croak'; | ||
| 6 | use Mojo::Util qw(camelize); | ||
| 7 | use Mojo::Collection qw(c); | ||
| 8 | use Mojo::JSON qw(to_json); | ||
| 9 | use Scalar::Util qw(blessed); | ||
| 10 | use Mojo::Loader qw(load_class load_classes); | ||
| 11 | |||
| 12 | has ['app', 'ua', 'config'] => undef; | ||
| 13 | has allowed_updates => sub {c(qw( | ||
| 14 | message edited_message | ||
| 15 | channel_post edited_channel_post | ||
| 16 | inline_query chosen_inline_result | ||
| 17 | callback_query shipping_query pre_checkout_query | ||
| 18 | poll poll_answer | ||
| 19 | my_chat_member chat_member chat_join_request | ||
| 20 | ))}; | ||
| 21 | has handlers => sub {{}}; | ||
| 22 | |||
| 23 | sub register { | ||
| 24 | my ($self, $app, $config) = @_; | ||
| 25 | |||
| 26 | $self->app($app); | ||
| 27 | $self->ua(Mojo::UserAgent->new->inactivity_timeout(0)); | ||
| 28 | $self->config($app->config->{telegram} ? $app->config->{telegram} : $config || {}); | ||
| 29 | $self->config->{token} ||= $ENV{TEST_TELEBOT_TOKEN}; | ||
| 30 | croak 'Setup bot token in config' if !$self->config->{token}; | ||
| 31 | $self->allowed_updates( | ||
| 32 | c(@{$self->config->{allowed_updates}}) | ||
| 33 | ) if $self->config->{allowed_updates}; | ||
| 34 | |||
| 35 | # Handlers | ||
| 36 | load_classes("Telebot::Handler"); | ||
| 37 | for ($self->allowed_updates->each, 'update') { | ||
| 38 | my $mod = "@{[ ref($app) ]}::Handler::@{[ camelize($_) ]}"; | ||
| 39 | if (my $e = load_class($mod)) { | ||
| 40 | if (ref $e) { | ||
| 41 | $app->log->error("Loading $mod exception: $e"); | ||
| 42 | } | ||
| 43 | else { | ||
| 44 | $self->handlers->{$_} = "Telebot::Handler::@{[ camelize($_) ]}"; | ||
| 45 | $app->log->info("$mod not found, Telebot::Handler::@{[ camelize($_) ]} loaded"); | ||
| 46 | } | ||
| 47 | } | ||
| 48 | else { | ||
| 49 | $app->log->info("$mod loaded"); | ||
| 50 | $self->handlers->{$_} = $mod; | ||
| 51 | } | ||
| 52 | } | ||
| 53 | |||
| 54 | # $app->tg->config() | ||
| 55 | $app->helper('tg.config' => sub ($c) { $self->config }); | ||
| 56 | |||
| 57 | # $app->tg->handlers() | ||
| 58 | $app->helper('tg.handlers' => sub ($c) { $self->handlers }); | ||
| 59 | |||
| 60 | # $app->tg->handler('message') | ||
| 61 | $app->helper('tg.handler' => sub ($c, $type) { $self->handlers->{$type} }); | ||
| 62 | |||
| 63 | # $app->tg->gentoken() | ||
| 64 | $app->helper('tg.gentoken' => sub ($c) { _gentoken() }); | ||
| 65 | |||
| 66 | # $app->tg->url('getMe') | ||
| 67 | $app->helper('tg.url' => sub ($c, $method) { | ||
| 68 | sprintf('%s/bot%s/%s', | ||
| 69 | $self->config->{api_server} || 'https://api.telegram.org', | ||
| 70 | $self->config->{token}, | ||
| 71 | $method) | ||
| 72 | }); | ||
| 73 | |||
| 74 | # $app->tg->request() | ||
| 75 | $app->helper('tg.request' => sub ($c, $method, $payload) { | ||
| 76 | $self->app->log->info("Request $method"); | ||
| 77 | my $tx = $self->ua->build_tx( | ||
| 78 | POST => $self->app->tg->url($method), | ||
| 79 | _prepare_payload($payload, $app), | ||
| 80 | ); | ||
| 81 | $tx = $self->ua->start($tx); | ||
| 82 | if ($tx->res->code == 200) { | ||
| 83 | return $tx->res->json; | ||
| 84 | } | ||
| 85 | else { | ||
| 86 | $self->app->dump($tx->res); | ||
| 87 | return $tx->res->json || { | ||
| 88 | ok => 0, | ||
| 89 | description => sprintf('Error %s during request', $tx->res->code), | ||
| 90 | }; | ||
| 91 | } | ||
| 92 | }); | ||
| 93 | |||
| 94 | # $app->tg->allowed_updates | ||
| 95 | $app->helper('tg.allowed_updates' => sub ($c) { | ||
| 96 | $self->allowed_updates; | ||
| 97 | }); | ||
| 98 | |||
| 99 | # $app->tg->extract_commands($text, $entities) | ||
| 100 | $app->helper('tg.extract_commands' => sub ($c, $text, $entities) { | ||
| 101 | my @commands; | ||
| 102 | for (grep {$_->{type} eq 'bot_command'} @{$entities||[]}) { | ||
| 103 | my $cmd = substr($text, $_->{offset}+1, $_->{length}); | ||
| 104 | $cmd =~ /^([^@]+)@?([^@]+)?$/; | ||
| 105 | push @commands, { | ||
| 106 | command => $1, | ||
| 107 | bot => $2, | ||
| 108 | } | ||
| 109 | } | ||
| 110 | return c(@commands); | ||
| 111 | }); | ||
| 112 | |||
| 113 | # Minion task | ||
| 114 | $app->minion->add_task(update => 'Telebot::Task::Update'); | ||
| 115 | $app->minion->add_task($_ => 'Telebot::Task::UpdateField') for $self->allowed_updates->each; | ||
| 116 | |||
| 117 | } | ||
| 118 | |||
| 119 | sub _gentoken { | ||
| 120 | join('', map {[0..9, 'a'..'z', 'A'..'Z']->[rand(62)]} (1..24)) | ||
| 121 | } | ||
| 122 | |||
| 123 | sub _find_files { | ||
| 124 | my ($var, $files) = @_; | ||
| 125 | $files ||= {}; | ||
| 126 | if (ref $var eq 'HASH') { | ||
| 127 | $var = {map { | ||
| 128 | $_ => scalar _find_files($var->{$_}, $files) | ||
| 129 | } keys %$var}; | ||
| 130 | } | ||
| 131 | elsif (ref $var eq 'ARRAY') { | ||
| 132 | $var = [map { | ||
| 133 | scalar _find_files($_, $files) | ||
| 134 | } @$var]; | ||
| 135 | } | ||
| 136 | elsif (blessed $var && $var->isa('Mojo::Asset')) { | ||
| 137 | my $name = _gentoken(); | ||
| 138 | $name = _gentoken() while exists $files->{$name}; | ||
| 139 | $files->{$name} = {file => $var}; | ||
| 140 | $var = "attach://$name"; | ||
| 141 | } | ||
| 142 | return wantarray ? ($var, $files) : $var; | ||
| 143 | } | ||
| 144 | |||
| 145 | sub _prepare_payload { | ||
| 146 | my ($payload) = @_; | ||
| 147 | my ($data, $files) = _find_files($payload); | ||
| 148 | if (keys %$files) { | ||
| 149 | return ( | ||
| 150 | {'Content-Type' => 'multipart/form-data'}, | ||
| 151 | form => { | ||
| 152 | (map { | ||
| 153 | $_ => ref $data->{$_} ? to_json($data->{$_}) : $data->{$_}; | ||
| 154 | } keys %$data), | ||
| 155 | %$files, | ||
| 156 | }, | ||
| 157 | ); | ||
| 158 | } | ||
| 159 | else { | ||
| 160 | return ( | ||
| 161 | {'Content-Type' => 'application/json'}, | ||
| 162 | json => $data || {}, | ||
| 163 | ); | ||
| 164 | } | ||
| 165 | } | ||
| 166 | |||
| 167 | 1; | ||
| 168 | |||
| 169 | =pod | ||
| 170 | |||
| 171 | =encoding utf8 | ||
| 172 | |||
| 173 | =head1 NAME | ||
| 174 | |||
| 175 | Telebot::Plugin::Telegram - Telegram API plugin | ||
| 176 | |||
| 177 | =head1 SYNOPSIS | ||
| 178 | |||
| 179 | # { | ||
| 180 | # message => 'Telebot::Handler::Message', | ||
| 181 | # poll => 'My::Bot::Handler::Poll', | ||
| 182 | # } | ||
| 183 | my $handlers = $app->tg->handlers(); | ||
| 184 | |||
| 185 | # 'Telebot::Handler::Message' | ||
| 186 | my $message_handler = $app->tg->handler('message'); | ||
| 187 | |||
| 188 | # 'z8HcRt7Z6wj3E7bwk2pOZx4s' | ||
| 189 | my $token = $app->tg->gentoken(); | ||
| 190 | |||
| 191 | # 'https://api.telegram.org/botTOKEN/getMe' | ||
| 192 | my $url = $app->tg->url('getMe'); | ||
| 193 | |||
| 194 | # Requests to API | ||
| 195 | my $response = $app->tg->request(getMe => {}); | ||
| 196 | my $response = $app->tg->request(sendMessage => { | ||
| 197 | chat_id => 777, | ||
| 198 | text => 'Hello, Telegram', | ||
| 199 | }); | ||
| 200 | |||
| 201 | # c('message', 'poll') | ||
| 202 | my $allowed_updates = $app->tg->allowed_updates; | ||
| 203 | |||
| 204 | # c({ | ||
| 205 | # command => 'start', | ||
| 206 | # bot => 'megabot', | ||
| 207 | # }, { | ||
| 208 | # command => 'stop', | ||
| 209 | # bot => undef, | ||
| 210 | # }) | ||
| 211 | $app->tg->extract_commands( | ||
| 212 | 'Please /start@megabot and /stop', | ||
| 213 | [{ | ||
| 214 | type => 'command', | ||
| 215 | offset => 7, | ||
| 216 | length => 14, | ||
| 217 | }, { | ||
| 218 | type => 'command', | ||
| 219 | offset => 26, | ||
| 220 | length => 5, | ||
| 221 | }] | ||
| 222 | ); | ||
| 223 | |||
| 224 | =head1 DESCRIPTION | ||
| 225 | |||
| 226 | L<Telebot::Plugin::Telegram> - plugin for working with Telegram API. | ||
| 227 | |||
| 228 | =head1 HELPERS | ||
| 229 | |||
| 230 | L<Telebot::Plugin::Telegram> implements the following helpers. | ||
| 231 | |||
| 232 | =head2 tg->handlers | ||
| 233 | |||
| 234 | Returns hash of registered handlers of update and it's parts. | ||
| 235 | Key - update or name of update field, value - name of handler module. | ||
| 236 | |||
| 237 | =head2 tg->handler | ||
| 238 | |||
| 239 | Returns name of handler module for update or update part. | ||
| 240 | |||
| 241 | =head2 tg->gentoken | ||
| 242 | |||
| 243 | Returns generated token (random string from alphabet symbols and digits) | ||
| 244 | |||
| 245 | =head2 tg->url | ||
| 246 | |||
| 247 | Returns URL for requesting Telegram API method | ||
| 248 | |||
| 249 | =head2 tg->request | ||
| 250 | |||
| 251 | Performs request to Telegram API | ||
| 252 | |||
| 253 | =head2 tg->allowed_updates | ||
| 254 | |||
| 255 | Return L<Mojo::Collection> of allowed updates (set of updates which Telegram sends to bot's webhook). | ||
| 256 | |||
| 257 | =head2 tg->extract_commands | ||
| 258 | |||
| 259 | Extract from text bot commands and return them as L<Mojo::Collection> | ||
| 260 | |||
| 261 | =head2 tg->config | ||
| 262 | |||
| 263 | Returns config of plugin. | ||
| 264 | |||
| 265 | =head1 METHODS | ||
| 266 | |||
| 267 | L<Telebot::Plugin::Telegram> inherits all methods from L<Mojolicious::Plugin> and implements the following new ones. | ||
| 268 | |||
| 269 | =head2 register | ||
| 270 | |||
| 271 | my $tg = $plugin->register(Mojolicious->new); | ||
| 272 | |||
| 273 | Register plugin in Mojolicious application and define helpers. | ||
| 274 | |||
| 275 | =head1 COPYRIGHT AND LICENSE | ||
| 276 | |||
| 277 | Copyright (C) 2022, Igor Lobanov. | ||
| 278 | This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version | ||
| 279 | 2.0. | ||
| 280 | |||
| 281 | =head1 SEE ALSO | ||
| 282 | |||
| 283 | L<https://github.com/igorlobanov/telebot>, L<Mojolicious::Guides>, L<https://mojolicious.org>, | ||
| 284 | L<https://core.telegram.org/bots/api>. | ||
| 285 | |||
| 286 | =cut |