Wolfram Alpha now uses web.py to shorten URLS

This commit is contained in:
Luke Rogers 2012-04-21 16:03:08 +12:00
parent 3f937dca91
commit ddee3b6ab1
2 changed files with 14 additions and 3 deletions

View file

@ -1,5 +1,6 @@
""" formatting.py - handy functions for formatting text """
def capitalize_first(line):
""" capitalises the first letter of words
(keeps other letters intact)

View file

@ -3,12 +3,18 @@ import urllib
from util import hook, http
from urllib2 import HTTPError
from util.web import bitly, ShortenError
@hook.command('wa')
@hook.command
def wolframalpha(inp, bot=None):
".wa <query> -- Computes <query> using Wolfram Alpha."
api_key = bot.config.get("api_keys", {}).get("wolframalpha", None)
bitly_user = bot.config.get("api_keys", {}).get("bitly_user", None)
bitly_key = bot.config.get("api_keys", {}).get("bitly_api", None)
if not api_key:
return "error: missing api key"
@ -20,6 +26,10 @@ def wolframalpha(inp, bot=None):
# get the URL for a user to view this query in a browser
query_url = "http://www.wolframalpha.com/input/?i=" + \
urllib.quote(inp.encode('utf-8'))
try:
short_url = bitly(query_url, bitly_user, bitly_key)
except (HTTPError, ShortenError):
short_url = query_url
pod_texts = []
for pod in result.xpath("//pod[@primary='true']"):
@ -48,11 +58,11 @@ def wolframalpha(inp, bot=None):
ret = re.sub(r'\\:([0-9a-z]{4})', unicode_sub, ret)
if len(ret) > 380:
ret = ret[:ret.rfind(' ', 0, 380)]
if len(ret) > 410:
ret = ret[:ret.rfind(' ', 0, 410)]
ret = re.sub(r'\W+$', '', ret) + '...'
if not ret:
return 'No results.'
return "%s - %s" % (ret, query_url)
return "%s - %s" % (ret, short_url)