Created
September 8, 2016 16:07
-
-
Save malles/a98a53f78aa4adbc4bc98248832f224c to your computer and use it in GitHub Desktop.
Lookup Ingress Wikia facts via your Hangups bot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio, json, re | |
import urllib | |
import plugins | |
TAG_RE = re.compile(r'<[^>]+>') | |
ELLIP_RE = re.compile(r'…') | |
def _initialise(bot): | |
plugins.register_user_command(["wikia"]) | |
def wikia(bot, event, *args): | |
"""lookup a term on Wikia""" | |
wiki = "ingress" | |
if bot.get_config_suboption(event.conv.id_, 'wikia_wiki'): | |
wiki = bot.get_config_suboption(event.conv.id_, 'wikia_wiki') | |
term = " ".join(args) | |
if not term: | |
return | |
html_text = yield from search_wikia(wiki, term) | |
yield from bot.coro_send_message(event.conv, html_text) | |
@asyncio.coroutine | |
def search_wikia(wiki, term): | |
html_text = "" | |
try: | |
f = urllib.request.urlopen("http://{}.wikia.com/api/v1/Search/List/?query={}".format(wiki, term)) | |
res = json.loads(f.read().decode('utf-8')) | |
if res["total"] > 0: | |
item = res["items"].pop(0) | |
html_text = "<b>{}</b><br/>".format(item["title"]) | |
html_text += ELLIP_RE.sub('...', remove_tags(item["snippet"])) | |
html_text += '<br/><br/><i>source: <a href="{}">{}</a></i>'.format(item["url"], item["url"]) | |
if res["total"] > 1: | |
html_text += '<br/><br/><a href="http://{}.wikia.com/wiki/Special:Search?search={}&fulltext=Search">' \ | |
'Total of {} results found</a>'\ | |
.format(wiki, term, res["total"]) | |
except urllib.request.HTTPError as e: | |
if e.code == 404: | |
html_text = "<i>No entry found in {} for {}</i>".format(wiki, term) | |
else: | |
html_text = "<i>Error in looking up {} in {} </i>".format(term, wiki) | |
except ValueError: | |
html_text = "<i>Error in format {} in {} </i>".format(term, wiki) | |
return html_text | |
def remove_tags(text): | |
return TAG_RE.sub('', text) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment