WikiLinker.pm


#!/usr/local/bin/perl

package Bot::BasicBot::Pluggable::Module::WikiLinker;
use Bot::BasicBot::Pluggable::Module;
use base qw(Bot::BasicBot::Pluggable::Module);

use strict;
use warnings;
use MediaWiki::API;
use HTML::TreeBuilder 5 -weak;
use Data::Dumper;

# Secondary variables.
my $mw = MediaWiki::API->new();
$mw->{config}->{api_url} = 'https://en.wikinews.org/w/api.php';

sub told{
    process_message(@_);
}

sub emoted {
    process_message(@_);
}

sub process_message{
    my ($self, $msg, $pri) = @_;
    my $body = $msg->{body};
    my $who  = $msg->{who};
    my $channel  = $msg->{channel};
    my @urls;
    while ($body =~ m{\[\[(.*?)\]\]}g){
        push @urls, get_url_by_text($1);
    }
    while ($body =~ m{\{\{(.*?)\}\}}g){
        push @urls, get_url_by_text("Template:$1");
    }
    return join " ", @urls;
}

sub get_url_by_text(){
  my $wiki_text = shift;
  # wiki text to html
  my $info_ref = $mw->api ( {
    action      => 'parse',
    prop        => 'text',
    text        => '{{fullurl:'.$wiki_text.'}}',
  } ) or die $mw->{error}->{code} . ': ' . $mw->{error}->{details};
  my $html = $info_ref->{parse}{text}{'*'};
  # parse html
  my $tree = HTML::TreeBuilder->new_from_content($html);
  return 'https:'.$tree->look_down('_tag','p')->content_array_ref->[0];
}

sub help{
return "parser for [[*]] in messages";
}

1;

#_ _END_ _