Created
April 25, 2020 21:33
-
-
Save hoelzro/b143fc51115713a48710da2dbf7222c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use feature qw(say); | |
use experimental qw(signatures); | |
use JSON::MaybeXS qw(decode_json); | |
die "SLACK_API_TOKEN must be set\n" unless $ENV{'SLACK_API_TOKEN'}; | |
my $SLACK_API_TOKEN = $ENV{'SLACK_API_TOKEN'}; | |
while(<>) { | |
chomp; | |
if(my ( $channel, $timestamp ) = m{https://\w+[.]slack[.]com/archives/([^/]+)/p(\d+)}) { | |
$timestamp = substr($timestamp, 0, -6) . '.' . substr($timestamp, -6); | |
my $api_url = "https://slack.com/api/conversations.history?token=$SLACK_API_TOKEN&channel=$channel&inclusive=1&limit=1&latest=$timestamp"; | |
open my $pipe, '-|', 'curl', '-s', $api_url; | |
my $json = do { | |
local $/; | |
<$pipe>; | |
}; | |
close $pipe; | |
die "Unable to run curl" unless $? == 0; | |
chomp $json; | |
my $doc = decode_json($json); | |
for my $msg (@{ $doc->{'messages'} }) { | |
my $blocks = $msg->{'blocks'}; | |
my $attachments = $msg->{'attachments'}; | |
for my $block (@$blocks) { | |
if($block->{'type'} eq 'rich_text') { | |
for my $element (@{ $block->{'elements'} }) { | |
if($element->{'type'} eq 'rich_text_section') { | |
for my $sub_element (@{ $element->{'elements'} }) { | |
my $type = $sub_element->{'type'}; | |
if($type eq 'user') { # no-op | |
} elsif($type eq 'text') { | |
say $sub_element->{'text'}; | |
} elsif($type eq 'link') { | |
my $url = $sub_element->{'url'}; | |
my ( $matching_attachment ) = grep { $_->{'from_url'} eq $url } @$attachments; | |
if($matching_attachment) { | |
my $text = $matching_attachment->{'fallback'}; | |
say "[$text]($url)"; | |
} else { | |
say $url; | |
} | |
} else { | |
die "Don't know how to handle sub-element of type '$sub_element->{'type'}'"; | |
} | |
} | |
} else { | |
die "Don't know how to handle element of type '$element->{'type'}'"; | |
} | |
} | |
} else { | |
die "Don't know how to handle block of type '$block->{'type'}'"; | |
} | |
} | |
} | |
# XXX wrap it in markdown quotes? | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment