From 0bc0aa0bf7bf0de1bb1ceb2b9ce87a2f6cb4e2bf Mon Sep 17 00:00:00 2001 From: James Lu Date: Sun, 28 Feb 2016 20:22:14 -0800 Subject: [PATCH] New MCInfo plugin, for showing Minecraft crafting recipes & block info --- MCInfo/README.md | 1 + MCInfo/__init__.py | 68 +++++++++++++++++ MCInfo/config.py | 57 ++++++++++++++ MCInfo/local/__init__.py | 1 + MCInfo/plugin.py | 161 +++++++++++++++++++++++++++++++++++++++ MCInfo/test.py | 38 +++++++++ 6 files changed, 326 insertions(+) create mode 100644 MCInfo/README.md create mode 100644 MCInfo/__init__.py create mode 100644 MCInfo/config.py create mode 100644 MCInfo/local/__init__.py create mode 100644 MCInfo/plugin.py create mode 100644 MCInfo/test.py diff --git a/MCInfo/README.md b/MCInfo/README.md new file mode 100644 index 0000000..cc3fdbc --- /dev/null +++ b/MCInfo/README.md @@ -0,0 +1 @@ +Fetches crafting recipes and other interesting information from the [Minecraft Wiki](http://minecraft.gamepedia.com). diff --git a/MCInfo/__init__.py b/MCInfo/__init__.py new file mode 100644 index 0000000..788d4dc --- /dev/null +++ b/MCInfo/__init__.py @@ -0,0 +1,68 @@ +### +# Copyright (c) 2016, James Lu +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions, and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions, and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the author of this software nor the name of +# contributors to this software may be used to endorse or promote products +# derived from this software without specific prior written consent. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +### + +""" +MCInfo: Fetches crafting recipes and other interesting information from the Minecraft Wiki. +""" + +import supybot +import supybot.world as world + +# Use this for the version of this plugin. You may wish to put a CVS keyword +# in here if you're keeping the plugin in CVS or some similar system. +__version__ = "" + +# XXX Replace this with an appropriate author or supybot.Author instance. +__author__ = supybot.authors.unknown + +# This is a dictionary mapping supybot.Author instances to lists of +# contributions. +__contributors__ = {} + +# This is a url where the most recent plugin package can be downloaded. +__url__ = '' + +from . import config +from . import plugin +from imp import reload +# In case we're being reloaded. +reload(config) +reload(plugin) +# Add more reloads here if you add third-party modules and want them to be +# reloaded when this plugin is reloaded. Don't forget to import them as well! + +if world.testing: + from . import test + +Class = plugin.Class +configure = config.configure + + +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: diff --git a/MCInfo/config.py b/MCInfo/config.py new file mode 100644 index 0000000..b134545 --- /dev/null +++ b/MCInfo/config.py @@ -0,0 +1,57 @@ +### +# Copyright (c) 2016, James Lu +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions, and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions, and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the author of this software nor the name of +# contributors to this software may be used to endorse or promote products +# derived from this software without specific prior written consent. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +### + +import supybot.conf as conf +import supybot.registry as registry +try: + from supybot.i18n import PluginInternationalization + _ = PluginInternationalization('MCInfo') +except: + # Placeholder that allows to run the plugin on a bot + # without the i18n module + _ = lambda x: x + + +def configure(advanced): + # This will be called by supybot to configure this module. advanced is + # a bool that specifies whether the user identified themself as an advanced + # user or not. You should effect your configuration by manipulating the + # registry as appropriate. + from supybot.questions import expect, anything, something, yn + conf.registerPlugin('MCInfo', True) + + +MCInfo = conf.registerPlugin('MCInfo') +# This is where your configuration variables (if any) should go. For example: +# conf.registerGlobalValue(MCInfo, 'someConfigVariableName', +# registry.Boolean(False, _("""Help for someConfigVariableName."""))) + + +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: diff --git a/MCInfo/local/__init__.py b/MCInfo/local/__init__.py new file mode 100644 index 0000000..e86e97b --- /dev/null +++ b/MCInfo/local/__init__.py @@ -0,0 +1 @@ +# Stub so local is a module, used for third-party modules diff --git a/MCInfo/plugin.py b/MCInfo/plugin.py new file mode 100644 index 0000000..ecd128e --- /dev/null +++ b/MCInfo/plugin.py @@ -0,0 +1,161 @@ +### +# Copyright (c) 2016, James Lu +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions, and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions, and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the author of this software nor the name of +# contributors to this software may be used to endorse or promote products +# derived from this software without specific prior written consent. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +### + +import supybot.utils as utils +from supybot.commands import wrap +import supybot.plugins as plugins +import supybot.ircutils as ircutils +import supybot.callbacks as callbacks +try: + from supybot.i18n import PluginInternationalization + _ = PluginInternationalization('MCInfo') +except ImportError: + # Placeholder that allows to run the plugin on a bot + # without the i18n module + _ = lambda x: x + +import sys + +if sys.version_info[0] >= 3: + from urllib.parse import quote +else: + from urllib import quote + +from bs4 import BeautifulSoup + +mcwiki_url = 'http://minecraft.gamepedia.com' + +class MCInfo(callbacks.Plugin): + """Fetches crafting recipes and other interesting information from the Minecraft Wiki.""" + threaded = True + + @wrap(['text']) + def mcwiki(self, irc, msg, args, item): + """ + Gets information from the Minecraft Wiki. This requires the Wikifetch plugin to be loaded. + """ + wf = irc.getCallback("Wikifetch") + + if wf: + # Use the Wikifetch plugin in this repository to lookup the information on the + # item, tool, or thing given. + text = wf._wiki(irc, msg, item, mcwiki_url) + if _('may refer to') in text: + irc.reply('%s seems to be a disambiguation page.' % text.split()[-1]) + else: + irc.reply(text) + else: + irc.error("This command requires the Wikifetch plugin to be loaded.", Raise=True) + + @wrap(['text']) + def craft(self, irc, msg, args, item): + """ + Attempts to lookup crafting information from the Minecraft wiki. + """ + + url = '%s/%s' % (mcwiki_url, quote(item)) + self.log.debug("MCInfo: using url %s", url) + + try: + article = utils.web.getUrl(url) + except utils.web.Error as e: + if '404' in str(e): + irc.error("Unknown item.", Raise=True) + irc.error(e, Raise=True) + + soup = BeautifulSoup(article) + + # Find the "Crafting table" displayed in the Wiki fatch showing how to craft something. + crafting_table = soup.find('table', attrs={"data-description": 'Crafting recipes'}) + if not crafting_table: + irc.error("No crafting information found.", Raise=True) + + for tag in crafting_table.previous_siblings: + # We only want the instructions on how to craft the item, not the items crafted WITH it. + # TODO: maybe this behavior could be a different command? + if tag.name == 'h3': + t = tag.contents[0].get_text().strip() + if t == 'Crafting ingredient': + irc.error("The item '%s' cannot be crafted." % item, Raise=True) + + + + # Get the first crafting result. TODO: optionally show all recipes if there are more than one. + crafting_data = crafting_table.find_all('tr')[1] + + # Shows the text of the ingredients used to craft (e.g. "Glass + Any dye") + ingredients = crafting_data.td.get_text() + ingredients = utils.str.normalizeWhitespace(ingredients.strip()) + + recipe = [] + + # This tracks how long the longest item name is. Used for formatting the crafting table on + # IRC with the right dimensions. + maxitemlength = 0 + + # Now, parse the layout of the 3x3 crafting grid the wiki shows for items. + for rowdata in crafting_data.div.span.span.children: + rowitems = [] + # Iterate over the rows of the crafting grid, and then the items in each. + for itemslot in rowdata.children: + + itemlink = itemslot.a + if itemlink: + # Item exists. Get the name of the item using the caption of its wiki page link. + itemname = itemlink.get('title') + + # Replace spaces with hyphens in the display to make the display monospace. + #itemname = itemname.replace(' ', '-') + + # Update the existing max item length if the length of the current one is + # greater. + if len(itemname) > maxitemlength: + maxitemlength = len(itemname) + + rowitems.append(itemname) + elif itemslot.find('br'): + # Empty square. + rowitems.append('') + if rowitems: + recipe.append(rowitems) + + irc.reply("Recipe for %s uses: %s" % (ircutils.bold(item), ircutils.bold(ingredients))) + for row in recipe: + if any(row): # Only output rows that have filled squares. + # For each item, center its name based on the length of the longest item name in the + # recipe. This gives the grid a more monospace-y feel. + items = [s.center(maxitemlength, '-') for s in row] + irc.reply('|%s|' % '|'.join(items)) + + +Class = MCInfo + + +# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: diff --git a/MCInfo/test.py b/MCInfo/test.py new file mode 100644 index 0000000..7fbb688 --- /dev/null +++ b/MCInfo/test.py @@ -0,0 +1,38 @@ +### +# Copyright (c) 2016, James Lu +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions, and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions, and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the author of this software nor the name of +# contributors to this software may be used to endorse or promote products +# derived from this software without specific prior written consent. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +### + +from supybot.test import * + + +class MCInfoTestCase(PluginTestCase): + plugins = ('MCInfo',) + + +# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79: