2011-11-20 22:23:31 +13:00
import re
2012-10-13 11:49:42 +13:00
from util import hook , http , text , web
2012-04-21 16:03:08 +12:00
2013-11-11 10:01:45 +13:00
@hook.command ( ' math ' )
@hook.command ( ' calc ' )
2011-11-20 22:23:31 +13:00
@hook.command ( ' wa ' )
@hook.command
2012-02-16 07:01:41 +13:00
def wolframalpha ( inp , bot = None ) :
2013-09-04 18:30:04 +08:00
""" wa <query> -- Computes <query> using Wolfram Alpha. """
2012-02-16 07:01:41 +13:00
api_key = bot . config . get ( " api_keys " , { } ) . get ( " wolframalpha " , None )
2012-04-22 04:26:24 +12:00
2012-04-21 03:36:06 +12:00
if not api_key :
return " error: missing api key "
2011-11-20 22:23:31 +13:00
2012-02-16 07:01:41 +13:00
url = ' http://api.wolframalpha.com/v2/query?format=plaintext '
2011-11-20 22:23:31 +13:00
2012-02-16 07:01:41 +13:00
result = http . get_xml ( url , input = inp , appid = api_key )
2012-04-22 04:26:24 +12:00
2012-04-21 03:36:06 +12:00
# get the URL for a user to view this query in a browser
query_url = " http://www.wolframalpha.com/input/?i= " + \
2012-10-13 11:49:42 +13:00
http . quote_plus ( inp . encode ( ' utf-8 ' ) )
2013-09-05 10:33:03 +12:00
short_url = web . try_isgd ( query_url )
2011-11-20 22:23:31 +13:00
pod_texts = [ ]
2012-04-21 03:36:06 +12:00
for pod in result . xpath ( " //pod[@primary= ' true ' ] " ) :
2012-02-16 07:01:41 +13:00
title = pod . attrib [ ' title ' ]
if pod . attrib [ ' id ' ] == ' Input ' :
2011-11-20 22:23:31 +13:00
continue
results = [ ]
2012-02-16 07:01:41 +13:00
for subpod in pod . xpath ( ' subpod/plaintext/text() ' ) :
subpod = subpod . strip ( ) . replace ( ' \\ n ' , ' ; ' )
subpod = re . sub ( r ' \ s+ ' , ' ' , subpod )
if subpod :
results . append ( subpod )
2011-11-20 22:23:31 +13:00
if results :
2013-11-30 19:19:04 +13:00
pod_texts . append ( title + u ' : ' + u ' , ' . join ( results ) )
2011-11-20 22:23:31 +13:00
2013-11-30 19:19:04 +13:00
ret = u ' - ' . join ( pod_texts )
2011-11-20 22:23:31 +13:00
if not pod_texts :
2012-02-16 07:18:56 +13:00
return ' No results. '
2011-11-20 22:23:31 +13:00
ret = re . sub ( r ' \\ (.) ' , r ' \ 1 ' , ret )
def unicode_sub ( match ) :
return unichr ( int ( match . group ( 1 ) , 16 ) )
ret = re . sub ( r ' \\ :([0-9a-z] {4} ) ' , unicode_sub , ret )
2012-10-13 11:49:42 +13:00
ret = text . truncate_str ( ret , 250 )
2011-11-20 22:23:31 +13:00
if not ret :
2012-02-16 07:18:56 +13:00
return ' No results. '
2011-11-20 22:23:31 +13:00
2013-11-30 19:19:04 +13:00
return u " {} - {} " . format ( ret , short_url )