Skip to content

Instantly share code, notes, and snippets.

@e000
Created January 31, 2011 00:23
Show Gist options
  • Save e000/803467 to your computer and use it in GitHub Desktop.
Save e000/803467 to your computer and use it in GitHub Desktop.
from Core.ZalgoBase.BaseModule import BaseModule
from twisted.web.client import getPage
from twisted.internet.defer import inlineCallbacks
from Core.ZalgoUtil.CmdWraps import command, timeout, needsArg, stripColors
from Core.ZalgoUtil.ModUtil import utf8
from urllib import urlencode
from xml.etree.cElementTree import fromstring
from Core import version
from Core.ZalgoUtil.DeferredCache import deferred_lfu_cache
class Module(BaseModule):
parseCommands = True
appId = x
@command('!wa')
@timeout(10)
@needsArg()
@stripColors()
@inlineCallbacks
def meme(self, cmd, user, channel, line, params):
"""
@description: searches wolframalpha!
"""
try:
(success, results), isCached = yield self.WAQuery(line)
if success is self.error:
self.bot.privmsg(channel, "Error: %s" % utf8(results))
elif not success:
self.bot.privmsg(channel, "Wolfram Alpha did not understand what you were trying to say%s" % (", here's a few hints:" if results else '.'))
for hint in results:
self.bot.privmsg(channel, ' * %s' % utf8(hint))
else:
for title, result in results:
self.bot.privmsg(channel, "\x02%s\x02:" % utf8(title))
for iresult in result:
self.bot.privmsg(channel, ' %s' % utf8(iresult))
if isCached:
self.bot.privmsg(channel, "\x0314result cached.")
except:
from twisted.python import failure
f = failure.Failure()
for line in f.getBriefTraceback().split('\n'):
self.bot.privmsg(channel, line)
def buildWolframAlphaUrl(self, query, format = ('plaintext',)):
return 'http://api.wolframalpha.com/v2/query?%s' % (
urlencode(
{
'appid': self.appId,
'input': query,
'format': ','.join(format)
}
)
)
@staticmethod
def getPage(page):
return getPage(page, agent=str(version))
@deferred_lfu_cache(30)
def WAQuery(self, query):
return getPage(
self.buildWolframAlphaUrl(query)
).addCallback(
self.parseWolframAlphaResponse
)
error = object()
def parseWolframAlphaResponse(self, response, redirected = False):
print response
xmlTree = fromstring(response)
recalculate = xmlTree.get('recalculate')
if recalculate:
if not redirected:
return self.getPage(recalculate).addCallback(self.parseWolframAlphaResponse, True)
else:
return error, 'Too many redirects.'
else:
success = xmlTree.get('success')
if success == 'true':
out = []
for pod in xmlTree.findall('pod'):
title = pod.get('title')
plaintext = pod.find('subpod/plaintext')
if plaintext is not None and plaintext.text:
out.append((title, plaintext.text.split('\n')))
return True, out
else:
return False, [tip.get('text') for tip in xmlTree.findall('tips/tip')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment