diff options
author | 2018-10-11 14:22:30 -0700 | |
---|---|---|
committer | 2018-10-11 14:22:30 -0700 | |
commit | bea7d364e957e2f3f1d71cbfb00c306588861ec6 (patch) | |
tree | b91c95a905c36ef7fea9dc8274fb9e6b73ab4f8a /bot/cogs/monstersurvey.py | |
parent | Merge branch 'deploy' of https://github.com/dfitzpatrick/hacktoberbot into 31... (diff) |
Merge branch 'deploy' of https://github.com/dfitzpatrick/hacktoberbot into 31-vote-for-favorite-monster
# Conflicts:
# Pipfile
Diffstat (limited to 'bot/cogs/monstersurvey.py')
-rw-r--r-- | bot/cogs/monstersurvey.py | 86 |
1 files changed, 58 insertions, 28 deletions
diff --git a/bot/cogs/monstersurvey.py b/bot/cogs/monstersurvey.py index 5e94b8a5..46ab2485 100644 --- a/bot/cogs/monstersurvey.py +++ b/bot/cogs/monstersurvey.py @@ -3,66 +3,96 @@ import json from discord.ext import commands from discord.ext.commands import Bot, Context import discord -from typing import Optional +from typing import Optional, Tuple import aiohttp from http import HTTPStatus log = logging.getLogger(__name__) +EMOJIS = { + 'SUCCESS': u"\u2705", + 'ERROR': u"\u274C", +} + class MonsterSurvey: def __init__(self, bot: Bot): self.bot = Bot self._monsters = None - async def monster_summary(self, monster): - monster = monster.replace(' ', '_') - wiki_url = "http://en.wikipedia.org/w/api.php" \ - "?format=json" \ - "&action=query" \ - "&prop=extracts" \ - "&prop=pageimages" \ - "&explaintext&exintro" \ - "&redirects=1" \ - f"&titles={monster}" - print(wiki_url) - async with aiohttp.ClientSession() as session: - response = await session.get(wiki_url) + @property + def monsters(self) -> dict: + """Always get the most up to date version""" + path = '../bot/resources/monstersurvey/monstersurvey.json' + with open(path, 'r') as f: + self._monsters = json.load(f) + return self._monsters + + async def monster_info(self, monster) -> Tuple[Optional[str], Optional[str]]: + """Gets information relating to each monster. This first checks if there + are 'summary' and 'image' keys in the json file. If this fails, it will + attempt to pull summary information from Wikipedia. + """ + async def fetch_url(session: aiohttp.ClientSession, url: str) -> dict: + """Use wikipedia api url calls""" + response = await session.get(url) if response.status == HTTPStatus.OK: result = json.loads(await response.text()) - return next(iter(result['query']['pages'].values()))['extract'] - - @property - def survey_data(self) -> dict: - """Get an updated instance of the survey data at all times""" - with open('../bot/resources/monstersurvey.json', 'r') as f: - self.monsters = json.load(f) - return self.monsters + return next(iter(result['query']['pages'].values())) + summary_url = "http://en.wikipedia.org/w/api.php" \ + "?format=json" \ + "&action=query" \ + "&prop=extracts" \ + "&explaintext&exintro" \ + "&redirects=1" \ + f"&titles={monster}" + image_url = "http://en.wikipedia.org/w/api.php" \ + "?action=query" \ + "&prop=pageimages" \ + "&format=json" \ + "&piprop=original" \ + f"&titles={monster}" + async with aiohttp.ClientSession() as s: + summary = self.monsters[monster].get('summary') \ + or (await fetch_url(s, summary_url)).get('extract') + + image = self.monsters[monster].get('image') \ + or (await fetch_url(s, image_url)).get('original', {}).get('source') + return summary, image @commands.group(name='monster', aliases=('ms',), invoke_without_command=True) async def monster_group(self, ctx: Context): - await ctx.invoke(self.bot.get_command(name="help"), 'monstersurvey') + pass @monster_group.command(name='vote') async def monster_vote(self, ctx: Context, name: Optional[str] = None): + """Casts a vote for a particular monster, or displays a list of all + monsters that are available for voting. + """ embed = discord.Embed(name='Vote for your favorite monster') if not name: for k,v in self.monsters.items(): - msg = f"`!monster show {k}` for more information\n" \ - f"`!monster vote {k}` to cast your vote for this monster." + msg = f"`.monster show {k}` for more information\n" \ + f"`.monster vote {k}` to cast your vote for this monster." embed.add_field(name=f"{k}", value=f"{msg}", inline=False) - + # TODO: Add logic for voting await ctx.send(embed=embed) @monster_group.command(name='show') async def monster_show(self, ctx: Context, *monster: str): + """Display a detailed description for the monster, and image.""" monster = ' '.join(monster) if self.monsters.get(monster, None): - summary = await self.monster_summary(monster) + summary, image = await self.monster_info(monster) embed = discord.Embed(name=monster) - embed.add_field(name=f"About {monster}", value=summary) + embed.add_field(name=f"About {monster}", value=summary or "No information") + if image: + embed.set_image(url=image) + embed.set_footer(text=f"To vote for {monster}, type `.monster vote {monster}`") await ctx.send(embed=embed) + else: + await ctx.message.add_reaction(EMOJIS['ERROR']) def setup(bot: Bot): |