minetestbot-modules/search.py

73 lines
2.1 KiB
Python
Raw Normal View History

2013-01-07 10:00:44 -08:00
#!/usr/bin/env python
"""
search.py - Phenny Web Search Module
Copyright 2008-9, Sean B. Palmer, inamidst.com
Modified by sfan5 2012
2013-01-07 10:00:44 -08:00
Licensed under the Eiffel Forum License 2.
http://inamidst.com/phenny/
"""
2014-07-20 07:13:59 -07:00
import web
import re
2013-01-07 10:00:44 -08:00
def google_ajax(query):
2013-01-07 10:00:44 -08:00
"""Search using AjaxSearch, and return its JSON."""
uri = 'http://ajax.googleapis.com/ajax/services/search/web'
2014-07-20 07:13:59 -07:00
args = '?v=1.0&safe=off&q=' + web.urlencode(query)
data, sc = web.get(uri + args)
data = str(data, 'utf-8')
return web.json(data)
2013-01-07 10:00:44 -08:00
def google_search(query):
2013-01-07 10:00:44 -08:00
results = google_ajax(query)
try: return results['responseData']['results'][0]['unescapedUrl']
except IndexError: return None
except TypeError:
2013-01-07 10:00:44 -08:00
return False
def g(phenny, input):
2013-01-07 10:00:44 -08:00
"""Queries Google for the specified input."""
query = input.group(2)
if not query:
2013-01-07 10:00:44 -08:00
return phenny.reply('.g what?')
2014-07-20 07:13:59 -07:00
log.log("event", "%s searched Google for '%s'" % (log.fmt_user(input), query), phenny)
2013-01-07 10:00:44 -08:00
uri = google_search(query)
if uri:
2013-01-07 10:00:44 -08:00
phenny.reply(uri)
phenny.bot.last_seen_uri = uri
2013-01-07 10:00:44 -08:00
elif uri is False: phenny.reply("Problem getting data from Google.")
else: phenny.reply("No results found for '%s'." % query)
g.commands = ['g']
g.priority = 'high'
g.example = '.g minetest'
def gc(phenny, input):
2014-07-20 07:13:59 -07:00
query = input.group(2)
if not query:
2013-01-07 10:00:44 -08:00
return phenny.reply("No query term.")
2014-07-20 07:13:59 -07:00
log.log("event", "%s searched Google for '%s'" % (log.fmt_user(input), query), phenny)
2013-01-07 10:00:44 -08:00
result = new_gc(query)
if result:
phenny.say(query + ": " + result)
else: phenny.reply("Sorry, couldn't get a result.")
2013-01-07 10:00:44 -08:00
def new_gc(query):
uri = 'https://www.google.com/search?hl=en&q='
2014-07-20 07:13:59 -07:00
uri = uri + web.urlencode(query).replace('+', '%2B')
2013-01-07 10:00:44 -08:00
if '"' in query: uri += '&tbs=li:1'
2014-07-20 07:13:59 -07:00
data, sc = web.get(uri)
data = str(data, 'utf-8')
if "did not match any documents" in data:
2013-01-07 10:00:44 -08:00
return "0"
2014-07-20 07:13:59 -07:00
for result in re.compile(r'(?ims)([0-9,]+) results?').findall(data):
2013-01-07 10:00:44 -08:00
return result
return None
gc.commands = ['gc']
gc.priority = 'high'
gc.example = '.gc minetest'
if __name__ == '__main__':
2014-07-20 07:13:59 -07:00
print(__doc__.strip())