Bot-BasicBot-Pluggable-Module-WWWShorten

 view release on metacpan or  search on metacpan

lib/Bot/BasicBot/Pluggable/Module/WWWShorten.pm  view on Meta::CPAN

package Bot::BasicBot::Pluggable::Module::WWWShorten;

use warnings;
use strict;
use parent 'Bot::BasicBot::Pluggable::Module';
use URI::Find::Rule;
use Try::Tiny;
use Module::Load;
use LWP::UserAgent;

our $VERSION = '0.03';

sub init {
    my $self = shift;
    $self->config(
        {
            user_service    => 'TinyURL',
            user_min_length => 0,
            user_addressed  => 0,
        }
    );
}

sub admin {
    my ( $self, $message ) = @_;

    my $body = $message->{body};
    return if !$body;
    return if $self->get('user_addressed') && ! $message->{address};

    my @uris = map { $_->[1] } URI::Find::Rule->http->in($body);
    return if !@uris;

    my $service = $self->get('user_service');
    my $module  = "WWW::Shorten::$service";
    try { load $module } catch { die "Can't load service $service: $@" };

    $module->import('makeashorterlink');
    for my $uri (@uris) {
        next if length $uri < $self->get('user_min_length');
        my ( $short_link, $title );
        try {
            $short_link = makeashorterlink($uri);

            my $ua = LWP::UserAgent->new(
                env_proxy => 1,
                timeout   => 30,    # seconds
                max_size =>
                  8192,    # bytes ... lets hope title is in the first bytes
            );

            my $response = $ua->get($uri);
            if (   $response->is_success
                && $response->content_type eq 'text/html' )
            {
                $title = $response->title;
            }

        }
        catch {
            die "Can't generate short link: $_";
        };

        my $reply = $short_link;
        $reply .= " [ $title ]" if $title;
        $self->reply( $message, $reply );
    }



( run in 1.714 second using v1.01-cache-2.11-cpan-39bf76dae61 )