130 lines
2.6 KiB
Plaintext
Raw Normal View History

2017-02-15 22:26:27 +10:30
#!/usr/bin/env perl
use strict;
use warnings;
use feature 'say';
use IO::Socket::SSL
2017-02-15 22:26:27 +10:30
use Mojo::UserAgent;
use Getopt::Long qw/GetOptions/;
use Data::Dumper qw/Dumper/;
my $webhook_url;
my $directory = "./";
my $username;
my $watch = 10;
my $help;
my $debug;
my $now = time();
my $error_count = 0;
my $error_max = 10;
2017-02-16 22:09:02 +10:30
my $version = '0.1';
2017-02-15 22:26:27 +10:30
GetOptions(
"webhook=s" => \$webhook_url,
"directory=s" => \$directory,
"username=s" => \$username,
"watch=i" => \$watch,
"help" => \$help,
"debug" => \$debug,
) || die usage();
usage() if $help;
if (! $webhook_url) {
usage("--webhook must be supplied");
}
sub usage {
my $error = shift || "";
2017-02-16 22:09:02 +10:30
my $indent = " " x length($0);
say "dau $version - https://github.com/tardisx/discord-auto-upload\n";
say "$0 --webhook <url> [--directory </some/path>]";
say "$indent [--username <\"custom username\">] [--watch <n>]\n";
say "The current directory will be used if no directory is specified.\n";
2017-02-15 22:26:27 +10:30
say "error: $error" if $error;
exit defined $error ? 1 : 0;
}
chdir $directory || die "cannot chdir to $directory: $!\n";
watch_dir();
sub watch_dir {
while (1) {
my @files = glob("*");
@files = grep { qualifies($_) } @files;
foreach my $file (sort { mtime($a) <=> mtime($b) } @files) {
debug("examining $file");
if (mtime($file) > $now) {
$now = mtime($file);
upload($file);
}
}
sleep $watch;
}
}
sub mtime {
my $f = shift;
return (stat($f))[9];
}
sub qualifies {
my $filename = shift;
return 1 if ($filename =~ /\.jpg$|\.gif$|\.png$/i);
return;
}
sub info {
say "- " . shift;
2017-02-15 22:26:27 +10:30
}
sub debug {
return unless $debug;
say "! " . shift;
}
sub error {
say "* " . shift;
2017-02-15 22:26:27 +10:30
}
sub upload {
my $file = shift;
info("uploading $file");
my $ua = Mojo::UserAgent->new;
my $data = {
upload => { file => $file },
$username ? ( username => $username ) : ()
};
my $tx = $ua->post($webhook_url, form => $data);
if (my $res = $tx->success) {
debug(Dumper($res->json));
my $url = $res->json->{attachments}->[0]->{url};
my $size = $res->json->{attachments}->[0]->{size};
my $width = $res->json->{attachments}->[0]->{width};
my $height = $res->json->{attachments}->[0]->{height};
2017-02-16 22:46:29 +10:30
info("uploaded ${width}x${height} $size byte image to $url");
2017-02-15 22:26:27 +10:30
}
else {
debug(Dumper($tx));
my $err = $tx->error;
if ($err->{code}) {
error("$err->{code} response: $err->{message}");
}
else {
error("Connection error: $err->{message}");
}
$error_count++;
if ($error_count >= $error_max) {
error("Sorry - too many errors - quitting");
}
}
}