aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Leon Sandøy <[email protected]>2018-11-21 13:00:34 +0100
committerGravatar GitHub <[email protected]>2018-11-21 13:00:34 +0100
commit276348d1e6524f895c8427d36b611b27258f369a (patch)
tree7e5e6153b02737624e8b78f932cc15488f3810c4
parentMerge branch 'markylon-gif' (diff)
parentResolve Flake8 (diff)
Merge pull request #69 from python-discord/issue/68-with-typing
Typing context manager for Hacktober cogs
-rw-r--r--bot/cogs/hacktober/hacktoberstats.py13
-rw-r--r--bot/cogs/hacktober/halloweenify.py43
-rw-r--r--bot/cogs/hacktober/monstersurvey.py193
-rw-r--r--bot/cogs/hacktober/scarymovie.py5
-rw-r--r--bot/cogs/hacktober/spookyavatar.py20
-rw-r--r--bot/cogs/hacktober/spookygif.py25
-rw-r--r--bot/resources/halloween/monstersurvey.json3
7 files changed, 169 insertions, 133 deletions
diff --git a/bot/cogs/hacktober/hacktoberstats.py b/bot/cogs/hacktober/hacktoberstats.py
index 0755503c..c473d3d0 100644
--- a/bot/cogs/hacktober/hacktoberstats.py
+++ b/bot/cogs/hacktober/hacktoberstats.py
@@ -148,13 +148,14 @@ class Stats:
Otherwise, post a helpful error message
"""
- prs = await self.get_october_prs(github_username)
+ async with ctx.typing():
+ prs = await self.get_october_prs(github_username)
- if prs:
- stats_embed = self.build_embed(github_username, prs)
- await ctx.send('Here are some stats!', embed=stats_embed)
- else:
- await ctx.send(f"No October GitHub contributions found for '{github_username}'")
+ if prs:
+ stats_embed = self.build_embed(github_username, prs)
+ await ctx.send('Here are some stats!', embed=stats_embed)
+ else:
+ await ctx.send(f"No October GitHub contributions found for '{github_username}'")
def build_embed(self, github_username: str, prs: typing.List[dict]) -> discord.Embed:
"""
diff --git a/bot/cogs/hacktober/halloweenify.py b/bot/cogs/hacktober/halloweenify.py
index 9b93ac99..5d270974 100644
--- a/bot/cogs/hacktober/halloweenify.py
+++ b/bot/cogs/hacktober/halloweenify.py
@@ -21,26 +21,29 @@ class Halloweenify:
"""
Change your nickname into a much spookier one!
"""
- with open(Path('bot', 'resources', 'halloween', 'halloweenify.json'), 'r') as f:
- data = load(f)
-
- # Choose a random character from our list we loaded above and set apart the nickname and image url.
- character = choice(data['characters'])
- nickname = ''.join([nickname for nickname in character])
- image = ''.join([character[nickname] for nickname in character])
-
- # Build up a Embed
- embed = discord.Embed()
- embed.colour = discord.Colour.dark_orange()
- embed.title = 'Not spooky enough?'
- embed.description = (
- f'**{ctx.author.display_name}** wasn\'t spooky enough for you? That\'s understandable, '
- f'{ctx.author.display_name} isn\'t scary at all! Let me think of something better. Hmm... I got it!\n\n '
- f'Your new nickname will be: \n :ghost: **{nickname}** :jack_o_lantern:'
- )
- embed.set_image(url=image)
-
- await ctx.author.edit(nick=nickname)
+ async with ctx.typing():
+ with open(Path('bot', 'resources', 'halloween', 'halloweenify.json'), 'r') as f:
+ data = load(f)
+
+ # Choose a random character from our list we loaded above and set apart the nickname and image url.
+ character = choice(data['characters'])
+ nickname = ''.join([nickname for nickname in character])
+ image = ''.join([character[nickname] for nickname in character])
+
+ # Build up a Embed
+ embed = discord.Embed()
+ embed.colour = discord.Colour.dark_orange()
+ embed.title = 'Not spooky enough?'
+ embed.description = (
+ f'**{ctx.author.display_name}** wasn\'t spooky enough for you? That\'s understandable, '
+ f'{ctx.author.display_name} isn\'t scary at all! '
+ 'Let me think of something better. Hmm... I got it!\n\n '
+ f'Your new nickname will be: \n :ghost: **{nickname}** :jack_o_lantern:'
+ )
+ embed.set_image(url=image)
+
+ await ctx.author.edit(nick=nickname)
+
await ctx.send(embed=embed)
diff --git a/bot/cogs/hacktober/monstersurvey.py b/bot/cogs/hacktober/monstersurvey.py
index 45587fe1..2b78abc6 100644
--- a/bot/cogs/hacktober/monstersurvey.py
+++ b/bot/cogs/hacktober/monstersurvey.py
@@ -23,6 +23,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')
with open(self.registry_location, 'r') as jason:
@@ -35,11 +36,11 @@ class MonsterSurvey:
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:
@@ -65,69 +66,80 @@ class MonsterSurvey:
"""
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)
+ async with ctx.typing():
+ 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())}")
+
+ await ctx.send(embed=default_embed)
@monster_group.command(
name='vote'
)
async def monster_vote(self, ctx: Context, name=None):
- """Casts a vote for a particular monster, or displays a list of monsters that can be voted for
- if one is not given."""
+ """
+ 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())}"
+
+ async with ctx.typing():
+ # Check to see if user used a numeric (leaderboard) index to vote
+ try:
+ idx = int(name)
+ name = self.get_name_by_leaderboard_index(idx)
+ except ValueError:
+ name = name.lower()
+
+ vote_embed = Embed(
+ name='Monster Voting',
+ color=0xFF6800
)
- 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)
+
+ 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())}"
+ )
+ else:
+ 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()
+
+ await ctx.send(embed=vote_embed)
@monster_group.command(
name='show'
@@ -135,26 +147,36 @@ class MonsterSurvey:
async def monster_show(self, ctx: Context, name=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()
+
+ async with ctx.typing():
+ # Check to see if user used a numeric (leaderboard) index to vote
+ try:
+ idx = int(name)
+ name = self.get_name_by_leaderboard_index(idx)
+ except ValueError:
+ 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)
+ if not m:
+ await ctx.send('That monster does not exist.')
+ await ctx.invoke(self.monster_vote)
+ return
+
+ 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}')
+
+ await ctx.send(embed=embed)
@monster_group.command(
name='leaderboard',
@@ -166,23 +188,28 @@ class MonsterSurvey:
: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}' ")
+ async with ctx.typing():
+ vr = self.voter_registry
+ top = sorted(vr, key=lambda k: len(vr[k]['votes']), reverse=True)
+ total_votes = sum(len(m['votes']) for m in self.voter_registry.values())
+
+ embed = Embed(title="Monster Survey Leader Board", color=0xFF6800)
+ 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)
diff --git a/bot/cogs/hacktober/scarymovie.py b/bot/cogs/hacktober/scarymovie.py
index 97e9f424..c2298c65 100644
--- a/bot/cogs/hacktober/scarymovie.py
+++ b/bot/cogs/hacktober/scarymovie.py
@@ -23,8 +23,9 @@ class ScaryMovie:
"""
Randomly select a scary movie and display information about it.
"""
- selection = await self.select_movie()
- movie_details = await self.format_metadata(selection)
+ async with ctx.typing():
+ selection = await self.select_movie()
+ movie_details = await self.format_metadata(selection)
await ctx.send(embed=movie_details)
diff --git a/bot/cogs/hacktober/spookyavatar.py b/bot/cogs/hacktober/spookyavatar.py
index ad8a9242..6ce4471c 100644
--- a/bot/cogs/hacktober/spookyavatar.py
+++ b/bot/cogs/hacktober/spookyavatar.py
@@ -35,15 +35,17 @@ class SpookyAvatar:
if user is None:
user = ctx.message.author
- embed = discord.Embed(colour=0xFF0000)
- embed.title = "Is this you or am I just really paranoid?"
- embed.set_author(name=str(user.name), icon_url=user.avatar_url)
- resp = await self.get(user.avatar_url)
- im = Image.open(BytesIO(resp))
- modified_im = spookifications.get_random_effect(im)
- modified_im.save(str(ctx.message.id)+'.png')
- f = discord.File(str(ctx.message.id)+'.png')
- embed.set_image(url='attachment://'+str(ctx.message.id)+'.png')
+ async with ctx.typing():
+ embed = discord.Embed(colour=0xFF0000)
+ embed.title = "Is this you or am I just really paranoid?"
+ embed.set_author(name=str(user.name), icon_url=user.avatar_url)
+ resp = await self.get(user.avatar_url)
+ im = Image.open(BytesIO(resp))
+ modified_im = spookifications.get_random_effect(im)
+ modified_im.save(str(ctx.message.id)+'.png')
+ f = discord.File(str(ctx.message.id)+'.png')
+ embed.set_image(url='attachment://'+str(ctx.message.id)+'.png')
+
await ctx.send(file=f, embed=embed)
os.remove(str(ctx.message.id)+'.png')
diff --git a/bot/cogs/hacktober/spookygif.py b/bot/cogs/hacktober/spookygif.py
index 1249905d..98a411f6 100644
--- a/bot/cogs/hacktober/spookygif.py
+++ b/bot/cogs/hacktober/spookygif.py
@@ -18,18 +18,19 @@ class SpookyGif:
"""
Fetches a random gif from the GIPHY API and responds with it.
"""
-
- async with aiohttp.ClientSession() as session:
- params = {'api_key': GIPHY_TOKEN, 'tag': 'halloween', 'rating': 'g'}
- # Make a GET request to the Giphy API to get a random halloween gif.
- async with session.get('http://api.giphy.com/v1/gifs/random', params=params) as resp:
- data = await resp.json()
- url = data['data']['image_url']
-
- embed = discord.Embed(colour=0x9b59b6)
- embed.title = "A spooooky gif!"
- embed.set_image(url=url)
- await ctx.send(embed=embed)
+ async with ctx.typing():
+ async with aiohttp.ClientSession() as session:
+ params = {'api_key': GIPHY_TOKEN, 'tag': 'halloween', 'rating': 'g'}
+ # Make a GET request to the Giphy API to get a random halloween gif.
+ async with session.get('http://api.giphy.com/v1/gifs/random', params=params) as resp:
+ data = await resp.json()
+ url = data['data']['image_url']
+
+ embed = discord.Embed(colour=0x9b59b6)
+ embed.title = "A spooooky gif!"
+ embed.set_image(url=url)
+
+ await ctx.send(embed=embed)
def setup(bot):
diff --git a/bot/resources/halloween/monstersurvey.json b/bot/resources/halloween/monstersurvey.json
index 99a3e96f..b430b6c0 100644
--- a/bot/resources/halloween/monstersurvey.json
+++ b/bot/resources/halloween/monstersurvey.json
@@ -24,7 +24,8 @@
"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": [
- 95872159741644800
+ 95872159741644800,
+ 129606635545952258
]
}
} \ No newline at end of file