Finished Webhooks and Telegram bindings

This commit is contained in:
rodger committed 2026-06-04 15:44:16 -04:00
1 parent c2d300d2f8
commit 74ae914886
7 files changed
+1283 -109

No files matched your search

+71 -6
View File
@@ -4,10 +4,75 @@ use warnings;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
# TODO: Parse --config flag (default: $RealBin/../config/mnemosyne.conf)
# TODO: Load Mnemosyne::Config, Mnemosyne::DB
# TODO: Build Mojolicious::Lite app:
# POST /<webhook_path> => validate secret token, route to Mnemosyne::Webhook
# TODO: Start app on 127.0.0.1:<listen_port> (never bind 0.0.0.0)
# Webhook receiver — Mojolicious::Lite app.
# Binds to 127.0.0.1 only; nginx terminates TLS and proxies inbound updates.
#
# Startup:
# mnemosyne-bot --config /path/to/mnemosyne.conf
# mnemosyne-bot --config /path/to/mnemosyne.conf daemon (same, explicit)
#
# In production (systemd), the unit sets:
# ExecStart=/usr/bin/perl /opt/mnemosyne/bin/mnemosyne-bot --config /etc/mnemosyne/mnemosyne.conf
print "mnemosyne-bot: not yet implemented\n";
use Mnemosyne::Config;
use Mnemosyne::DB;
use Mnemosyne::Telegram;
use Mnemosyne::Webhook;
use Mojolicious::Lite;
# ---- parse --config before Mojolicious sees ARGV ----------------------
my $config_path = "$RealBin/../config/mnemosyne.conf";
my @passthrough;
while (@ARGV) {
my $arg = shift @ARGV;
if ($arg eq '--config' && @ARGV) {
$config_path = shift @ARGV;
} else {
push @passthrough, $arg;
}
}
@ARGV = @passthrough;
# ---- load config & bootstrap ------------------------------------------
die "Config file not found: $config_path\n" unless -f $config_path;
my $config = Mnemosyne::Config->new($config_path);
my $db = Mnemosyne::DB->new($config->get('db', 'path'));
my $token = $config->get('bot', 'token') or die "bot.token missing in config\n";
my $secret = $config->get('bot', 'webhook_secret') or die "bot.webhook_secret missing in config\n";
my $port = $config->get('bot', 'listen_port') // 8443;
my $wh_url = $config->get('bot', 'webhook_url') or die "bot.webhook_url missing in config\n";
my $telegram = Mnemosyne::Telegram->new($token);
# Extract the path component from the webhook URL
# e.g. https://example.com/tghook/abc123 → /tghook/abc123
(my $wh_path = $wh_url) =~ s{^https?://[^/]+}{};
$wh_path ||= '/webhook';
# ---- webhook endpoint -------------------------------------------------
post $wh_path => sub {
my ($c) = @_;
# Gate 1: validate Telegram's secret-token header
my $incoming_secret = $c->req->headers->header('X-Telegram-Bot-Api-Secret-Token') // '';
unless ($incoming_secret eq $secret) {
$c->render(text => 'Forbidden', status => 403);
return;
}
# Respond 200 immediately — Telegram retries on non-2xx or timeouts
$c->render(text => 'ok', status => 200);
# Process the update (synchronous; fast enough for single-user load)
my $update = $c->req->json;
eval {
Mnemosyne::Webhook->handle_update($update, $db, $config, $telegram);
};
warn "Webhook processing error: $@\n" if $@;
};
# ---- start ------------------------------------------------------------
# Default to daemon on localhost; let explicit ARGV override for hypnotoad etc.
push @ARGV, ('daemon', '-l', "http://127.0.0.1:$port") unless @ARGV;
app->start;
+67 -11
View File
@@ -4,16 +4,72 @@ use warnings;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
# Invoked by cron every N minutes (e.g. */5 * * * *).
# Exits immediately unless:
# a) the current local time matches digest_time (within the cron granularity window), AND
# b) last_digest_sent (config table) is not today's date.
# On success, records today's date in last_digest_sent to prevent duplicate sends.
# Invoked by cron every 5 minutes (recommended: */5 * * * *).
# Checks whether it's time to send the morning digest; exits silently otherwise.
# Guards against duplicate sends with last_digest_sent in the config table.
#
# TODO: Load config + DB
# TODO: Read digest_time and last_digest_sent from config table
# TODO: Compare current local time against digest_time (allow ±(cron_interval/2) window)
# TODO: If it's time and not already sent: call Mnemosyne::Digest::send(...)
# TODO: On success: update last_digest_sent to today's ISO date
# Usage:
# mnemosyne-digest [--config /path/to/mnemosyne.conf]
print "mnemosyne-digest: not yet implemented\n";
use Mnemosyne::Config;
use Mnemosyne::DB;
use Mnemosyne::Telegram;
use Mnemosyne::Digest;
use DateTime;
use DateTime::TimeZone;
use constant WINDOW_MINUTES => 5; # half-window each side of digest_time
my $config_path = "$RealBin/../config/mnemosyne.conf";
while (@ARGV) {
my $arg = shift @ARGV;
if ($arg eq '--config' && @ARGV) { $config_path = shift @ARGV }
else { die "Unknown argument: $arg\n" }
}
die "Config file not found: $config_path\n" unless -f $config_path;
my $config = Mnemosyne::Config->new($config_path);
my $db = Mnemosyne::DB->new($config->get('db', 'path'));
# ---- current local time -----------------------------------------------
my $tz_name = $db->config_get('timezone') // 'UTC';
my $now = eval { DateTime->now(time_zone => $tz_name) }
// do { warn "Unknown timezone '$tz_name', falling back to UTC\n";
DateTime->now(time_zone => 'UTC') };
# ---- configured digest time -------------------------------------------
my $digest_time = $db->config_get('digest_time') // '06:30';
my ($dh, $dm) = split /:/, $digest_time;
$dh //= 6; $dm //= 30;
# ---- check window: |now - digest_time| ≤ WINDOW_MINUTES ---------------
my $target = $now->clone->truncate(to => 'day')
->add(hours => $dh + 0, minutes => $dm + 0);
my $diff = abs(($now->epoch - $target->epoch) / 60); # minutes
unless ($diff <= WINDOW_MINUTES) {
exit 0; # not time yet (or already past the window)
}
# ---- guard: already sent today? ---------------------------------------
my $today_str = $now->strftime('%Y-%m-%d');
my $last_sent = $db->config_get('last_digest_sent') // '';
if ($last_sent eq $today_str) {
exit 0; # already sent
}
# ---- send! ------------------------------------------------------------
my $token = $config->get('bot', 'token') or die "bot.token missing\n";
my $chat_id = ($config->allowed_chat_ids)[0] or die "No allowed_chat_ids in config\n";
my $telegram = Mnemosyne::Telegram->new($token);
my $today_dt = $now->clone->truncate(to => 'day');
eval {
Mnemosyne::Digest->send($db, $telegram, $chat_id, $today_dt);
};
if ($@) {
warn "Digest send failed: $@\n";
exit 1;
}
exit 0;
+40 -8
View File
@@ -4,16 +4,48 @@ use warnings;
use FindBin qw($RealBin);
use lib "$RealBin/../lib";
# One-shot helper to register (or remove) the Telegram webhook.
# One-shot helper to register or remove the Telegram webhook.
# Run once after install, and again whenever the webhook URL changes.
# Only one webhook can be active per bot token at a time.
#
# Usage:
# mnemosyne-webhook [--config /path/to/mnemosyne.conf] [--delete]
#
# TODO: Load config
# TODO: --delete: call Mnemosyne::Telegram::delete_webhook()
# TODO: default: call Mnemosyne::Telegram::set_webhook(webhook_url, webhook_secret)
# TODO: Print result (registered URL, or confirmation of deletion)
# mnemosyne-webhook [--config /path] [--delete]
print "mnemosyne-webhook: not yet implemented\n";
use Mnemosyne::Config;
use Mnemosyne::Telegram;
my $config_path = "$RealBin/../config/mnemosyne.conf";
my $do_delete = 0;
while (@ARGV) {
my $arg = shift @ARGV;
if ($arg eq '--config' && @ARGV) { $config_path = shift @ARGV }
elsif ($arg eq '--delete') { $do_delete = 1 }
else { die "Unknown argument: $arg\n" }
}
die "Config file not found: $config_path\n" unless -f $config_path;
my $config = Mnemosyne::Config->new($config_path);
my $token = $config->get('bot', 'token') or die "bot.token missing\n";
my $secret = $config->get('bot', 'webhook_secret') or die "bot.webhook_secret missing\n";
my $wh_url = $config->get('bot', 'webhook_url') or die "bot.webhook_url missing\n";
my $tg = Mnemosyne::Telegram->new($token);
if ($do_delete) {
my $res = $tg->delete_webhook;
if ($res->{ok}) {
print "Webhook deleted.\n";
} else {
print "Error: $res->{description}\n";
exit 1;
}
} else {
my $res = $tg->set_webhook($wh_url, $secret);
if ($res->{ok}) {
print "Webhook registered: $wh_url\n";
} else {
print "Error: $res->{description}\n";
exit 1;
}
}