3
0
mirror of https://github.com/pragma-/pbot.git synced 2024-11-16 17:09:33 +01:00
pbot/lib/PBot/Plugin/Spinach/update_seent.pl

101 lines
2.5 KiB
Perl
Raw Normal View History

#!/usr/bin/perl
use warnings;
use strict;
use JSON;
use Time::Piece;
my $self = {};
sub load_questions {
2020-02-15 23:38:32 +01:00
my ($filename) = @_;
2020-02-15 23:38:32 +01:00
if (not defined $filename) { $filename = $ENV{HOME} . "/pbot/data/spinach/trivia.json"; }
2020-02-15 23:38:32 +01:00
$self->{loaded_filename} = $filename;
2020-02-15 23:38:32 +01:00
my $contents = do {
open my $fh, '<', $filename or do {
print "Spinach: Failed to open $filename: $!\n";
return "Failed to load $filename";
};
local $/;
<$fh>;
};
2020-02-15 23:38:32 +01:00
$self->{questions} = decode_json $contents;
$self->{categories} = ();
2020-02-15 23:38:32 +01:00
my $questions;
foreach my $key (keys %{$self->{questions}}) {
foreach my $question (@{$self->{questions}->{$key}}) {
$question->{category} = uc $question->{category};
$self->{categories}{$question->{category}}{$question->{id}} = $question;
2020-02-15 23:38:32 +01:00
if (not exists $question->{seen_timestamp}) { $question->{seen_timestamp} = 0; }
2020-02-15 23:38:32 +01:00
$questions++;
}
}
2020-02-15 23:38:32 +01:00
my $categories;
foreach my $category (sort { keys %{$self->{categories}{$b}} <=> keys %{$self->{categories}{$a}} } keys %{$self->{categories}}) {
my $count = keys %{$self->{categories}{$category}};
print "Category [$category]: $count\n";
$categories++;
}
2020-02-15 23:38:32 +01:00
print "Spinach: Loaded $questions questions in $categories categories.\n";
return "Loaded $questions questions in $categories categories.";
}
sub save_questions {
2020-02-15 23:38:32 +01:00
my $json = encode_json $self->{questions};
my $filename = exists $self->{loaded_filename} ? $self->{loaded_filename} : $self->{questions_filename};
open my $fh, '>', $filename or do {
print "Failed to open Spinach file $filename: $!\n";
return;
};
print $fh "$json\n";
close $fh;
}
load_questions;
open my $fh, '<', 'seent' or do {
2020-02-15 23:38:32 +01:00
print "Failed to open seent file: $!\n";
die;
};
my $nr = 0;
foreach my $line (<$fh>) {
2020-02-15 23:38:32 +01:00
++$nr;
my ($date, $id) = $line =~ m/^(.*?) :: .*? question:.*?\s(\d+,?\d*)\)/;
2020-02-15 23:38:32 +01:00
if (not defined $date or not defined $id) {
print "Parse error at line $nr\n";
die;
}
2020-02-15 23:38:32 +01:00
$id =~ s/,//g;
2020-02-15 23:38:32 +01:00
print "matched [$date] and [$id]\n";
2020-02-15 23:38:32 +01:00
my $time = Time::Piece->strptime($date, "%a %b %e %H:%M:%S %Y");
print "epoch: ", $time->epoch, "\n";
2020-02-15 23:38:32 +01:00
foreach my $q (@{$self->{questions}->{questions}}) {
if ($q->{id} == $id) {
print "question: $q->{question}\n";
$q->{seen_timestamp} = $time->epoch;
last;
}
}
}
close $fh;
save_questions;