aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Leon Sandøy <[email protected]>2018-11-20 02:09:20 +0100
committerGravatar Leon Sandøy <[email protected]>2018-11-20 02:09:20 +0100
commit2262f684e03d004ad65bf023eca7e649489b891f (patch)
tree235acdd38426c90dc90b2387ede580883292ee49
parentMerge branch 'vote-monster-refactor' of https://github.com/dfitzpatrick/hackt... (diff)
Minor changes
-rw-r--r--bot/__main__.py4
-rw-r--r--bot/cogs/hacktober/monstersurvey.py2
-rw-r--r--bot/cogs/monstersurvey.py192
-rw-r--r--bot/resources/monstersurvey/monstersurvey.json28
4 files changed, 3 insertions, 223 deletions
diff --git a/bot/__main__.py b/bot/__main__.py
index a1484cbc..b2b2c5fd 100644
--- a/bot/__main__.py
+++ b/bot/__main__.py
@@ -22,10 +22,10 @@ log.info('Start loading extensions from ./bot/cogs/evergreen/')
if __name__ == '__main__':
# Scan for files in the /cogs/ directory and make a list of the file names.
- cogs = [file.stem for file in Path('bot', 'cogs', 'evergreen').glob('*.py') if not file.stem.startswith("__")]
+ cogs = [file.stem for file in Path('bot', 'cogs', 'halloween').glob('*.py') if not file.stem.startswith("__")]
for extension in cogs:
try:
- bot.load_extension(f'bot.cogs.evergreen.{extension}')
+ bot.load_extension(f'bot.cogs.halloween.{extension}')
log.info(f'Successfully loaded extension: {extension}')
except Exception as e:
log.error(f'Failed to load extension {extension}: {repr(e)} {format_exc()}')
diff --git a/bot/cogs/hacktober/monstersurvey.py b/bot/cogs/hacktober/monstersurvey.py
index 376ac1fa..9eafcadc 100644
--- a/bot/cogs/hacktober/monstersurvey.py
+++ b/bot/cogs/hacktober/monstersurvey.py
@@ -25,7 +25,7 @@ class MonsterSurvey:
def __init__(self, bot: Bot):
"""Initializes values for the bot to use within the voting commands."""
self.bot = bot
- self.registry_location = os.path.join(os.getcwd(), 'bot', 'resources', 'halloween', 'monstersurvey.json')
+ self.registry_location = os.path.join(os.getcwd(), 'bot', 'resources', 'monstersurvey', 'monstersurvey.json')
with open(self.registry_location, 'r') as jason:
self.voter_registry = json.load(jason)
diff --git a/bot/cogs/monstersurvey.py b/bot/cogs/monstersurvey.py
deleted file mode 100644
index 9eafcadc..00000000
--- a/bot/cogs/monstersurvey.py
+++ /dev/null
@@ -1,192 +0,0 @@
-import json
-import logging
-import os
-from typing import Optional, Union
-
-from discord import Embed
-from discord.ext import commands
-from discord.ext.commands import Bot, Context
-
-log = logging.getLogger(__name__)
-
-EMOJIS = {
- 'SUCCESS': u'\u2705',
- 'ERROR': u'\u274C'
-}
-
-
-class MonsterSurvey:
- """
- Vote for your favorite monster!
- This command allows users to vote for their favorite listed monster.
- Users may change their vote, but only their current vote will be counted.
- """
-
- def __init__(self, bot: Bot):
- """Initializes values for the bot to use within the voting commands."""
- self.bot = bot
- self.registry_location = os.path.join(os.getcwd(), 'bot', 'resources', 'monstersurvey', 'monstersurvey.json')
- with open(self.registry_location, 'r') as jason:
- self.voter_registry = json.load(jason)
-
- def json_write(self):
- log.info("Saved Monster Survey Results")
- with open(self.registry_location, 'w') as jason:
- json.dump(self.voter_registry, jason, indent=2)
-
- def cast_vote(self, id: int, monster: str):
- """
-
- :param id: The id of the person voting
- :param monster: the string key of the json that represents a monster
- :return: None
- """
- vr = self.voter_registry
- for m in vr.keys():
- if id not in vr[m]['votes'] and m == monster:
- vr[m]['votes'].append(id)
- else:
- if id in vr[m]['votes'] and m != monster:
- vr[m]['votes'].remove(id)
-
- def get_name_by_leaderboard_index(self, n):
- n = n - 1
- vr = self.voter_registry
- top = sorted(vr, key=lambda k: len(vr[k]['votes']), reverse=True)
- name = top[n] if n >= 0 else None
- return name
-
- @commands.group(
- name='monster',
- aliases=['ms']
- )
- async def monster_group(self, ctx: Context):
- """
- The base voting command. If nothing is called, then it will return an embed.
- """
-
- if ctx.invoked_subcommand is None:
- default_embed = Embed(
- title='Monster Voting',
- color=0xFF6800,
- description='Vote for your favorite monster!'
- )
- default_embed.add_field(
- name='.monster show monster_name(optional)',
- value='Show a specific monster. If none is listed, it will give you an error with valid choices.',
- inline=False)
- default_embed.add_field(
- name='.monster vote monster_name',
- value='Vote for a specific monster. You get one vote, but can change it at any time.',
- inline=False
- )
- default_embed.add_field(
- name='.monster leaderboard',
- value='Which monster has the most votes? This command will tell you.',
- inline=False
- )
- default_embed.set_footer(text=f"Monsters choices are: {', '.join(self.voter_registry.keys())}")
- return await ctx.send(embed=default_embed)
-
- @monster_group.command(
- name='vote'
- )
- async def monster_vote(self, ctx: Context, name: Optional[Union[int, str]] = None):
- """Casts a vote for a particular monster, or displays a list of monsters that can be voted for
- if one is not given."""
- if name is None:
- await ctx.invoke(self.monster_leaderboard)
- return
- vote_embed = Embed(
- name='Monster Voting',
- color=0xFF6800
- )
- if isinstance(name, int):
- name = self.get_name_by_leaderboard_index(name)
- else:
- name = name.lower()
- m = self.voter_registry.get(name)
- if m is None:
-
- vote_embed.description = f'You cannot vote for {name} because it\'s not in the running.'
- vote_embed.add_field(
- name='Use `.monster show {monster_name}` for more information on a specific monster',
- value='or use `.monster vote {monster}` to cast your vote for said monster.',
- inline=False
- )
- vote_embed.add_field(
- name='You may vote for or show the following monsters:',
- value=f"{', '.join(self.voter_registry.keys())}"
- )
- return await ctx.send(embed=vote_embed)
- self.cast_vote(ctx.author.id, name)
- vote_embed.add_field(
- name='Vote successful!',
- value=f'You have successfully voted for {m["full_name"]}!',
- inline=False
- )
- vote_embed.set_thumbnail(url=m['image'])
- vote_embed.set_footer(text="Please note that any previous votes have been removed.")
- self.json_write()
- return await ctx.send(embed=vote_embed)
-
- @monster_group.command(
- name='show'
- )
- async def monster_show(self, ctx: Context, name: Optional[Union[int, str]] = None):
- """
- Shows the named monster. If one is not named, it sends the default voting embed instead.
- :param ctx:
- :param name:
- :return:
- """
- if name is None:
- await ctx.invoke(self.monster_leaderboard)
- return
- if isinstance(name, int):
- m = self.voter_registry.get(self.get_name_by_leaderboard_index(name))
- else:
- name = name.lower()
- m = self.voter_registry.get(name)
- if not m:
- await ctx.send('That monster does not exist.')
- return await ctx.invoke(self.monster_vote)
- embed = Embed(title=m['full_name'], color=0xFF6800)
- embed.add_field(name='Summary', value=m['summary'])
- embed.set_image(url=m['image'])
- embed.set_footer(text=f'To vote for this monster, type .monster vote {name}')
- return await ctx.send(embed=embed)
-
- @monster_group.command(
- name='leaderboard',
- aliases=['lb']
- )
- async def monster_leaderboard(self, ctx: Context):
- """
- Shows the current standings.
- :param ctx:
- :return:
- """
- vr = self.voter_registry
- top = sorted(vr, key=lambda k: len(vr[k]['votes']), reverse=True)
-
- embed = Embed(title="Monster Survey Leader Board", color=0xFF6800)
- total_votes = sum(len(m['votes']) for m in self.voter_registry.values())
- for rank, m in enumerate(top):
- votes = len(vr[m]['votes'])
- percentage = ((votes / total_votes) * 100) if total_votes > 0 else 0
- embed.add_field(name=f"{rank+1}. {vr[m]['full_name']}",
- value=f"{votes} votes. {percentage:.1f}% of total votes.\n"
- f"Vote for this monster by typing "
- f"'.monster vote {m}'\n"
- f"Get more information on this monster by typing "
- f"'.monster show {m}'",
- inline=False)
-
- embed.set_footer(text="You can also vote by their rank number. '.monster vote {number}' ")
- await ctx.send(embed=embed)
-
-
-def setup(bot):
- bot.add_cog(MonsterSurvey(bot))
- log.debug("MonsterSurvey COG Loaded")
diff --git a/bot/resources/monstersurvey/monstersurvey.json b/bot/resources/monstersurvey/monstersurvey.json
deleted file mode 100644
index 209f1cbb..00000000
--- a/bot/resources/monstersurvey/monstersurvey.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "frankenstein": {
- "full_name": "Frankenstein's Monster",
- "summary": "His limbs were in proportion, and I had selected his features as beautiful. Beautiful! Great God! His yellow skin scarcely covered the work of muscles and arteries beneath; his hair was of a lustrous black, and flowing; his teeth of a pearly whiteness; but these luxuriances only formed a more horrid contrast with his watery eyes, that seemed almost of the same colour as the dun-white sockets in which they were set, his shrivelled complexion and straight black lips.",
- "image": "https://upload.wikimedia.org/wikipedia/commons/a/a7/Frankenstein%27s_monster_%28Boris_Karloff%29.jpg",
- "votes": []
- },
- "dracula": {
- "full_name": "Count Dracula",
- "summary": "Count Dracula is an undead, centuries-old vampire, and a Transylvanian nobleman who claims to be a Sz\u00c3\u00a9kely descended from Attila the Hun. He inhabits a decaying castle in the Carpathian Mountains near the Borgo Pass. Unlike the vampires of Eastern European folklore, which are portrayed as repulsive, corpse-like creatures, Dracula wears a veneer of aristocratic charm. In his conversations with Jonathan Harker, he reveals himself as deeply proud of his boyar heritage and nostalgic for the past, which he admits have become only a memory of heroism, honour and valour in modern times.",
- "image": "https://upload.wikimedia.org/wikipedia/commons/thumb/9/90/Bela_Lugosi_as_Dracula%2C_anonymous_photograph_from_1931%2C_Universal_Studios.jpg/250px-Bela_Lugosi_as_Dracula%2C_anonymous_photograph_from_1931%2C_Universal_Studios.jpg",
- "votes": [
- 224734305581137921
- ]
- },
- "goofy": {
- "full_name": "Goofy in the Monster's INC World",
- "summary": "Pure nightmare fuel.\nThis monster is nothing like its original counterpart. With two different eyes, a pointed nose, fins growing out of its blue skin, and dark spots covering his body, he's a true nightmare come to life.",
- "image": "https://www.dailydot.com/wp-content/uploads/3a2/a8/bf38aedbef9f795f.png",
- "votes": []
- },
- "refisio": {
- "full_name": "Refisio",
- "summary": "Who let this guy write this? That's who the real monster is.",
- "image": "https://avatars0.githubusercontent.com/u/24819750?s=460&v=4",
- "votes": []
- }
-} \ No newline at end of file