3
0
mirror of https://github.com/pragma-/pbot.git synced 2024-11-17 09:29:30 +01:00
pbot/lib/PBot/Plugin/Date.pm
Pragmatic Software 54ef6b14ce
Plugin/Date: use existing context when launching date applet
This preserves the pipe/cmd-substitution/etc to allow post-processing
of the `date` output.

Interpreter: Reset `interpreted` contextual metadata when handling
result to allow recursion for continued command processing.
2024-11-05 23:57:48 -08:00

94 lines
2.8 KiB
Perl

# File: Date.pm
#
# Purpose: Adds command to display time and date for timezones.
# SPDX-FileCopyrightText: 2020-2023 Pragmatic Software <pragma78@gmail.com>
# SPDX-License-Identifier: MIT
package PBot::Plugin::Date;
use parent 'PBot::Plugin::Base';
use PBot::Imports;
sub initialize($self, %conf) {
# add default registry entry for default timezone
# this can be overridden via arguments or user metadata
$self->{pbot}->{registry}->add_default('text', 'date', 'default_timezone', 'UTC');
# register `date` bot command
$self->{pbot}->{commands}->add(
name => 'date',
help => 'Show date and time',
subref => sub { $self->cmd_date(@_) },
);
}
sub unload($self) {
$self->{pbot}->{commands}->remove('date');
}
sub cmd_date($self, $context) {
my $usage = "Usage: date [-u <user account>] [timezone]";
my %opts;
my ($opt_args, $opt_error) = $self->{pbot}->{interpreter}->getopt(
$context->{arguments},
\%opts,
['bundling'],
'u=s',
'h',
);
return $usage if $opts{h};
return "/say $opt_error -- $usage" if $opt_error;
$context->{arguments} = "@$opt_args";
my $user_override = $opts{u};
my $tz_override;
# check for user timezone metadata
if (defined $user_override) {
my $userdata = $self->{pbot}->{users}->{storage}->get_data($user_override);
if (not defined $userdata) {
return "No such user account $user_override. They may use the `my` command to create a user account and set their `timezone` user metadata."
}
if (not exists $userdata->{timezone}) {
return "User account does not have `timezone` set. They may use the `my` command to set their `timezone` user metadata."
}
$tz_override = $userdata->{timezone};
} else {
$tz_override = $self->{pbot}->{users}->get_user_metadata($context->{from}, $context->{hostmask}, 'timezone') // '';
}
# set default timezone
my $timezone = $self->{pbot}->{registry}->get_value('date', 'default_timezone') // 'UTC';
# override timezone with user metadata
$timezone = $tz_override if $tz_override;
# override timezone with bot command arguments
$timezone = $context->{arguments} if length $context->{arguments};
if (defined $user_override and not length $tz_override) {
return "No timezone set or user account does not exist.";
}
# override command fields to execute date_applet
$context->{keyword} = "date_applet";
$context->{command} = "date_applet $timezone";
$context->{arguments} = $timezone;
# tell Interpreter::interpret() that this command has been interpreted
$context->{interpreted} = 1;
# fork to execute applet
$self->{pbot}->{applets}->execute_applet($context);
}
1;