This repository has been archived on 2023-04-13. You can view files and clone it, but you cannot make any changes to it's state, such as pushing and creating new issues, pull requests or comments.
CloudBot/disabled_stuff/minecraft_wiki.py

52 lines
1.5 KiB
Python
Raw Normal View History

import re
2014-02-14 16:36:57 +13:00
from util import hook, http, text
2014-02-13 10:10:34 +13:00
api_url = "http://minecraft.gamepedia.com/api.php?action=opensearch"
mc_url = "http://minecraft.gamepedia.com/"
@hook.command
def mcwiki(inp):
2013-09-04 18:30:04 +08:00
"""mcwiki <phrase> -- Gets the first paragraph of
the Minecraft Wiki article on <phrase>."""
2014-02-13 10:54:20 +13:00
try:
j = http.get_json(api_url, search=inp)
except (http.HTTPError, http.URLError) as e:
return "Error fetching search results: {}".format(e)
except ValueError as e:
return "Error reading search results: {}".format(e)
2013-02-07 00:35:03 +13:00
if not j[1]:
return "No results found."
# we remove items with a '/' in the name, because
2014-02-13 15:09:22 +13:00
# gamepedia uses sub-pages for different languages
# for some stupid reason
items = [item for item in j[1] if not "/" in item]
if items:
article_name = items[0].replace(' ', '_').encode('utf8')
else:
# there are no items without /, just return a / one
article_name = j[1][0].replace(' ', '_').encode('utf8')
2013-02-07 00:35:03 +13:00
url = mc_url + http.quote(article_name, '')
2014-02-13 10:54:20 +13:00
try:
page = http.get_html(url)
except (http.HTTPError, http.URLError) as e:
return "Error fetching wiki page: {}".format(e)
for p in page.xpath('//div[@class="mw-content-ltr"]/p'):
if p.text_content():
summary = " ".join(p.text_content().splitlines())
summary = re.sub("\[\d+\]", "", summary)
2013-08-20 10:55:58 +12:00
summary = text.truncate_str(summary, 200)
2014-02-13 09:36:28 +13:00
return u"{} :: {}".format(summary, url)
# this shouldn't happen
return "Unknown Error."