.

Wolfram|Alpha IRC script

If you’re hanging out on the same GameSurge channel(s) as me, you probably know about Byte’s tehh6x bot. I’ve recently added a Wolfram|Alpha command to it, allowing it to query W|A and return the results in a somewhat IRC-compatible format. Here’s the code:

#!/usr/bin/perl

use strict;
use warnings;

use URI::Escape;
use LWP::UserAgent;
use HTML::Entities;

sub uhoh {
	print "Timeout.\n";
	exit
}

my $query = <STDIN>;
$query =~ s/\n//;

$SIG{ALRM} = \&uhoh;
alarm(10);

my $url = 'http://www.wolframalpha.com/input/?i=' .
    uri_escape( $query, "^A-Za-z0-9" );

my $ua = LWP::UserAgent->new( agent => 'eggdrop/1.6' );
my $response = $ua->get( $url );

$response->is_success or
    die "$url: ", $response->status_line;

my $content = $response->content;

my @captions = $content =~ m|<h2>(.*?)</h2>|g;
my @results  = $content =~ m|alt="(.*?)"|g;

if ( scalar(@captions) ) {
	@results = map {
		$_ =~ /^link to \/input\/\?i=/ ? () : $_
	} @results[1..$#results];

	my @lines = map { 
		my $result = $results[$_];
		if (length($result) > 300) {
			while (length($result) > 300 && $result =~ /\\n/) {
				$result =~ s/^(.*)\\n.*$/$1/;
			}
			$result .= "\\n(...)"
		}
		(length($result)>0 && length($result)<300) ? 
			"$captions[$_] $result\n" : ()
	} 0..$#captions; 
	#@lines = grep {!/\\n/} @lines; # skip multi-line pods
	if ( scalar(@lines) > 1 ) {
		my $result = join("",@lines);
		$result = decode_entities($result);
		$result =~ s/ \| / - /g;
		$result =~ s/\\n/ | /g;
		$result =~ s/\\(['"])/$1/g;
		$result =~ s/\((open|close) curly quote\)/'/g;
		$result =~ s/\((open|close) curly double quote\)/"/g;
		print $result;
	} else {
		print "$url\n";
	}
} else {
    print "?\n";
}

Comments