| 1 | #!/usr/bin/env perl | ||
| 2 | |||
| 3 | # ABSTRACT: Telegram bot that send you a snapshot from IP camera using ffmpeg (don't forget to install it!) | ||
| 4 | |||
| 5 | |||
| 6 | package Telegram::CamshotBot; | ||
| 7 | $Telegram::CamshotBot::VERSION = '0.03'; | ||
| 8 | use Telegram::CamshotBot::Util qw(first_existing_file random_caption abs_path_of_sample_mojo_conf fev); | ||
| 9 | use Mojolicious::Lite; | ||
| 10 | use Mojolicious::Plugin::JSONConfig; | ||
| 11 | use Mojolicious::Plugin::Webtail; | ||
| 12 | use WWW::Telegram::BotAPI; | ||
| 13 | use Date::Format; | ||
| 14 | use Telegram::Bot::Message; | ||
| 15 | use feature 'say'; | ||
| 16 | use Data::Dumper; | ||
| 17 | use Data::Printer; | ||
| 18 | use Cwd; | ||
| 19 | use Net::Ping; | ||
| 20 | use Regexp::Common qw /net/; | ||
| 21 | |||
| 22 | my $config_file_path = first_existing_file( | ||
| 23 | $ENV{"CAMSHOTBOT_CONFIG"}, | ||
| 24 | $ENV{"HOME"}.'/.camshotbot', | ||
| 25 | getcwd.'/camshotbot.conf.json', | ||
| 26 | abs_path_of_sample_mojo_conf(__PACKAGE__), | ||
| 27 | ); | ||
| 28 | |||
| 29 | print "Using config: ".$config_file_path."\n"; | ||
| 30 | |||
| 31 | my $config_values = plugin 'JSONConfig' => { file => $config_file_path }; | ||
| 32 | |||
| 33 | plugin( 'Webtail', file => $ENV{CAMSHOTBOT_WEBTAIL_LOG_FILE} || $config_values->{log_file} ); # https://metacpan.org/pod/Mojolicious::Plugin::Webtail | ||
| 34 | |||
| 35 | # BEGIN { $ENV{TELEGRAM_BOTAPI_DEBUG}=1 }; | ||
| 36 | |||
| 37 | my $api; | ||
| 38 | my $bot_name = ''; | ||
| 39 | my $telegram_token = $ENV{CAMSHOTBOT_TELEGRAM_API_TOKEN} || $config_values->{telegram_api_token}; | ||
| 40 | my $screenshot_file = $ENV{CAMSHOTBOT_LAST_SHOT_FILENAME} || $config_values->{last_shot_filename} || 'latest.jpg'; # name of last screenshot or env | ||
| 41 | my $stream_url = $ENV{CAMSHOTBOT_STREAM_URL} || $config_values->{stream_url}; | ||
| 42 | my $ffmpeg_cmd = 'ffmpeg -hide_banner -loglevel panic -i '.$stream_url.' -f image2 -vframes 1 '.$screenshot_file if ($stream_url); | ||
| 43 | my ($camera_ip) = ($stream_url =~ /($RE{net}{IPv4})/) if ($stream_url); | ||
| 44 | my $bot_domain = $ENV{VIRTUAL_HOST} || $ENV{LETSENCRYPT_HOST} || $ENV{CAMSHOTBOT_DOMAIN} || $config_values->{bot_domain}; | ||
| 45 | my $polling_flag = $ENV{CAMSHOTBOT_POLLING} || $config_values->{polling}; # 0 or not set -> webhook, 1 -> polling | ||
| 46 | my $polling_timeout = 3; # default | ||
| 47 | if ($polling_flag) { | ||
| 48 | $polling_timeout = $ENV{CAMSHOTBOT_POLLING_TIMEOUT} || $config_values->{polling_timeout}; | ||
| 49 | } else { | ||
| 50 | $polling_timeout = undef; | ||
| 51 | } | ||
| 52 | my $docker_flag = $ENV{CAMSHOTBOT_FFMPEG_DOCKER} || $config_values->{ffmpeg_docker}; # any value to send cached image | ||
| 53 | |||
| 54 | if ($telegram_token) { # maybe add | ||
| 55 | $api = WWW::Telegram::BotAPI->new ( | ||
| 56 | token => $telegram_token | ||
| 57 | ); | ||
| 58 | $bot_name = $api->getMe->{result}{username}; | ||
| 59 | } else { | ||
| 60 | say "Attention! Telegram API token isn't specified. Please edit ".$config_file_path." or CAMSHOTBOT_TELEGRAM_API_TOKEN"; | ||
| 61 | } | ||
| 62 | |||
| 63 | |||
| 64 | helper answer => sub { | ||
| 65 | my ($c, $update) = @_; | ||
| 66 | |||
| 67 | app->log->info("Processing new update..."); | ||
| 68 | my $mo = Telegram::Bot::Message->create_from_hash($update->{message}); | ||
| 69 | |||
| 70 | my $msg = $mo->text; | ||
| 71 | my $chat_id = $mo->chat->id; | ||
| 72 | my $from_id = $mo->from->id; | ||
| 73 | my $date = $mo->date; | ||
| 74 | my $date_str = time2str("%R %a %o %b %Y" ,$mo->date); # 11:59 Sun 29th Jan 2017 | ||
| 75 | |||
| 76 | |||
| 77 | ###### Loggging | ||
| 78 | if ($ENV{CAMSHOTBOT_TELEGRAM_DEBUG} || $config_values->{debug}) { | ||
| 79 | # full log, convenient if you need to restict chat_id's and check what's wrong | ||
| 80 | app->log->info("Update from Telegram API: ".Dumper $update); | ||
| 81 | app->log->info("Update parsed by Telegram::Bot::Message: ".Dumper $mo); | ||
| 82 | } else { | ||
| 83 | my $from_str = ''; | ||
| 84 | my $username = $mo->from->username; | ||
| 85 | if ($username) { | ||
| 86 | $from_str = $username; | ||
| 87 | } else { | ||
| 88 | $from_str = $mo->from->first_name." ".$mo->from->first_name." (id ".$from_id.")"; | ||
| 89 | } | ||
| 90 | app->log->info($msg." from ".$from_str." sent at ".$date_str); | ||
| 91 | }; | ||
| 92 | ###### end loggging | ||
| 93 | |||
| 94 | if ($docker_flag) { | ||
| 95 | app->log->info("Sending a screenshot generated by ffmpeg docker container some time ago"); | ||
| 96 | } else { | ||
| 97 | `rm -f $screenshot_file`; # remove old screenshot | ||
| 98 | my $o = `$ffmpeg_cmd`; | ||
| 99 | app->log->info("Screenshot got with command: ".$ffmpeg_cmd.', result : '.$o); | ||
| 100 | } | ||
| 101 | |||
| 102 | if ( ($msg eq "/shot") || ($msg eq '/shot@'.$bot_name )) { | ||
| 103 | |||
| 104 | $api->sendPhoto ({ | ||
| 105 | chat_id => $chat_id, | ||
| 106 | photo => { | ||
| 107 | file => $screenshot_file | ||
| 108 | }, | ||
| 109 | caption => random_caption(), | ||
| 110 | reply_to_message_id => $mo->message_id | ||
| 111 | }); | ||
| 112 | } | ||
| 113 | |||
| 114 | if ($msg eq "/help") { | ||
| 115 | |||
| 116 | $api->sendMessage ({ | ||
| 117 | chat_id => $chat_id, | ||
| 118 | text => '/shot - Get online camera shot', | ||
| 119 | reply_to_message_id => $mo->message_id | ||
| 120 | }); | ||
| 121 | } | ||
| 122 | |||
| 123 | }; | ||
| 124 | |||
| 125 | # for local testing purposes. also shows how many unprocessed updates in queue on server | ||
| 126 | helper check_for_updates => sub { | ||
| 127 | my $c = shift; | ||
| 128 | my $res = $api->deleteWebhook() ; # disable webhooks | ||
| 129 | # warn Dumper $res; | ||
| 130 | my $updates = $api->getUpdates(); | ||
| 131 | my $h = { | ||
| 132 | updates_in_queue => {} | ||
| 133 | }; | ||
| 134 | $h->{updates_in_queue}{count} = scalar @{$updates->{result}}; | ||
| 135 | $h->{updates_in_queue}{details} = \@{$updates->{result}}; | ||
| 136 | |||
| 137 | my @u_ids; | ||
| 138 | for (@{$updates->{result}}) { | ||
| 139 | push @u_ids, $_->{update_id}; | ||
| 140 | } | ||
| 141 | |||
| 142 | $h->{updates_in_queue}{update_ids} = \@u_ids; | ||
| 143 | |||
| 144 | $c->setWebhook() if !($polling_flag); # set Webhook again if needed | ||
| 145 | |||
| 146 | return $h; | ||
| 147 | }; | ||
| 148 | |||
| 149 | helper setWebhook => sub { | ||
| 150 | my $c = shift; | ||
| 151 | return $api->setWebhook({ url => 'https://'.$bot_domain.'/'.$telegram_token }); | ||
| 152 | }; | ||
| 153 | |||
| 154 | |||
| 155 | post '/'.$telegram_token => sub { | ||
| 156 | my $c = shift; | ||
| 157 | my $update = $c->req->json; | ||
| 158 | $c->answer($update); | ||
| 159 | $c->render(json => "ok"); | ||
| 160 | }; | ||
| 161 | |||
| 162 | get '/' => sub { | ||
| 163 | shift->render(text => 'bot is running'); | ||
| 164 | }; | ||
| 165 | |||
| 166 | get '/status' => sub { | ||
| 167 | my $c = shift; | ||
| 168 | my $status = {}; | ||
| 169 | $status->{telegram_api} = eval { $api->getMe } or $status->{telegram_api} = $api->parse_error->{msg}; | ||
| 170 | $status->{stream_url} = $stream_url; | ||
| 171 | $status->{ffmpeg_docker} = $docker_flag; | ||
| 172 | my $p = Net::Ping->new(); | ||
| 173 | $status->{vpn_status} = 'down'; | ||
| 174 | $status->{vpn_status} = 'up' if $p->ping($camera_ip); | ||
| 175 | $status->{WebhookInfo} = $api->getWebhookInfo; | ||
| 176 | $p->close(); | ||
| 177 | $c->render(json => $status); | ||
| 178 | }; | ||
| 179 | |||
| 180 | get '/setwebhook' => sub { | ||
| 181 | my $c = shift; | ||
| 182 | my $res = $c->setWebhook(); | ||
| 183 | $c->render( json => $res ); | ||
| 184 | }; | ||
| 185 | |||
| 186 | # shows info about unprocessed updates on server | ||
| 187 | get '/debug' => sub { | ||
| 188 | my $c = shift; # $c = Mojolicious::Controller object | ||
| 189 | $c->render( json => $c->check_for_updates() ); | ||
| 190 | }; | ||
| 191 | |||
| 192 | |||
| 193 | |||
| 194 | |||
| 195 | if ($telegram_token && $polling_flag) { | ||
| 196 | |||
| 197 | my $res = $api->deleteWebhook(); | ||
| 198 | app->log->info("Webhook was deleted. Starting polling with ".$polling_timeout."secs timeout ...") if $res; | ||
| 199 | |||
| 200 | Mojo::IOLoop->recurring($polling_timeout => sub { | ||
| 201 | |||
| 202 | my @updates = @{$api->getUpdates->{result}}; | ||
| 203 | |||
| 204 | if (@updates) { | ||
| 205 | for my $u (@updates) { | ||
| 206 | #app->build_controller->answer($u); # Mojolicious::Lite -> Mojolicious::Controller -> Mojolicious::Helper | ||
| 207 | app->answer($u); # Mojolicious::Lite -> Mojolicious::Controller -> Mojolicious::Helper | ||
| 208 | $api->getUpdates({ offset => $u->{update_id} + 1.0 }); # clear buffer | ||
| 209 | } | ||
| 210 | } | ||
| 211 | |||
| 212 | }); | ||
| 213 | } | ||
| 214 | |||
| 215 | # my $queue = app->build_controller->check_for_updates()->{updates_in_queue}; | ||
| 216 | # if ne daemon | ||
| 217 | |||
| 218 | if ($telegram_token) { | ||
| 219 | my $queue = app->check_for_updates()->{updates_in_queue}; | ||
| 220 | app->log->info('Starting bot @'.$bot_name."..."); | ||
| 221 | app->log->info("Having ".$queue->{count}." stored Updates at Telegram server"); | ||
| 222 | app->log->info("Unprocessed update ids (for offset debug): ".join(',', @{$queue->{update_ids}}) ); | ||
| 223 | } | ||
| 224 | |||
| 225 | push @{app->commands->namespaces}, 'Telegram::CamshotBot::Command'; | ||
| 226 | app->start; | ||
| 227 | |||
| 228 | 1; | ||
| 229 | |||
| 230 | __END__ |