From a606e483b3a42357778fc3d4979e800e8dd38739 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Thu, 11 Oct 2018 11:44:28 +0200 Subject: Adding Pale Man, fixing all flake8 issues, converting halloweenify to use aiohttp, fixing broken logging, ignoring irrelevant loggers, and turning the script into a valid module script. --- bot/cogs/movie.py | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) (limited to 'bot/cogs/movie.py') diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py index bb6f8df8..51529bc9 100644 --- a/bot/cogs/movie.py +++ b/bot/cogs/movie.py @@ -1,8 +1,10 @@ -import requests import random from os import environ -from discord.ext import commands + +import aiohttp from discord import Embed +from discord.ext import commands + TMDB_API_KEY = environ.get('TMDB_API_KEY') TMDB_TOKEN = environ.get('TMDB_TOKEN') @@ -40,19 +42,24 @@ class Movie: } # Get total page count of horror movies - response = requests.get(url=url, params=params, headers=headers) - total_pages = response.json().get('total_pages') + async with aiohttp.ClientSession() as session: + response = await session.get(url=url, params=params, headers=headers) + total_pages = await response.json() + total_pages = total_pages.get('total_pages') - # Get movie details from one random result on a random page - params['page'] = random.randint(1, total_pages) - response = requests.get(url=url, params=params, headers=headers) - selection_id = random.choice(response.json().get('results')).get('id') + # Get movie details from one random result on a random page + params['page'] = random.randint(1, total_pages) + response = await session.get(url=url, params=params, headers=headers) + response = await response.json() + selection_id = random.choice(response.get('results')).get('id') - # Get full details and credits - selection = requests.get(url='https://api.themoviedb.org/3/movie/' + str(selection_id), - params={'api_key': TMDB_API_KEY, 'append_to_response': 'credits'}) + # Get full details and credits + selection = await session.get( + url='https://api.themoviedb.org/3/movie/' + str(selection_id), + params={'api_key': TMDB_API_KEY, 'append_to_response': 'credits'} + ) - return selection.json() + return await selection.json() @staticmethod async def format_metadata(movie): @@ -72,7 +79,7 @@ class Movie: rating_count = movie.get('vote_average') / 2 rating = '' - for i in range(int(rating_count)): + for _ in range(int(rating_count)): rating += ':skull:' if (rating_count % 1) >= .5: -- cgit v1.2.3 From 5e2abfd06ebe5d3011fbbcc818d85e215f358969 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Thu, 11 Oct 2018 12:12:32 +0200 Subject: Made the movie formatter less naïve. It no longer crashes if TMDB's return data is incomplete. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot/cogs/movie.py | 51 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 12 deletions(-) (limited to 'bot/cogs/movie.py') diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py index 51529bc9..82b9c682 100644 --- a/bot/cogs/movie.py +++ b/bot/cogs/movie.py @@ -67,36 +67,63 @@ class Movie: Formats raw TMDb data to be embedded in discord chat """ - tmdb_url = 'https://www.themoviedb.org/movie/' + str(movie.get('id')) - poster = 'https://image.tmdb.org/t/p/original' + movie.get('poster_path') + # Build the relevant URLs. + movie_id = movie.get("id") + poster_path = movie.get("poster_path") + tmdb_url = f'https://www.themoviedb.org/movie/{movie_id}' if movie_id else None + poster = f'https://image.tmdb.org/t/p/original{poster_path}' if poster_path else None + # Get cast names cast = [] - for actor in movie.get('credits').get('cast')[:3]: + for actor in movie.get('credits', {}).get('cast', [])[:3]: cast.append(actor.get('name')) - director = movie.get('credits').get('crew')[0].get('name') + # Get director name + director = movie.get('credits', {}).get('crew', []) + if director: + director = director[0].get('name') - rating_count = movie.get('vote_average') / 2 + # Determine the spookiness rating rating = '' + rating_count = movie.get('vote_average', 0) + + if rating_count: + rating_count /= 2 for _ in range(int(rating_count)): rating += ':skull:' - if (rating_count % 1) >= .5: rating += ':bat:' + # Try to get year of release and runtime + year = movie.get('release_date', [])[:4] + runtime = movie.get('runtime') + runtime = f"{runtime} minutes" if runtime else None + + # Not all these attributes will always be present + movie_attributes = { + "Directed by": director, + "Starring": ', '.join(cast), + "Running time": runtime, + "Release year": year, + "Spookiness rating": rating, + } + embed = Embed( colour=0x01d277, title='**' + movie.get('title') + '**', url=tmdb_url, description=movie.get('overview') ) - embed.set_image(url=poster) - embed.add_field(name='Starring', value=', '.join(cast)) - embed.add_field(name='Directed by', value=director) - embed.add_field(name='Year', value=movie.get('release_date')[:4]) - embed.add_field(name='Runtime', value=str(movie.get('runtime')) + ' min') - embed.add_field(name='Spooky Rating', value=rating) + + if poster: + embed.set_image(url=poster) + + # Add the attributes that we actually have data for, but not the others. + for name, value in movie_attributes.items(): + if value: + embed.add_field(name=name, value=value) + embed.set_footer(text='powered by themoviedb.org') return embed -- cgit v1.2.3 From 79dc1d87824b6ab1afc2832f4e40c981ac8f0e20 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Fri, 12 Oct 2018 00:27:22 +0200 Subject: improving the .help docstrings, and making the bot load cogs from the correct path. (#43) * Improving some docstrings and making it look in ./bot/cogs for cogs. * Removing pointless stuff from a docstring --- bot/__main__.py | 6 +++--- bot/cogs/halloweenify.py | 3 +++ bot/cogs/movie.py | 5 ++++- bot/cogs/template.py | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) (limited to 'bot/cogs/movie.py') diff --git a/bot/__main__.py b/bot/__main__.py index 2c41d2d9..ccd69b0b 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -17,15 +17,15 @@ else: ghost_unicode = "\N{GHOST}" bot = commands.Bot(command_prefix=commands.when_mentioned_or(".", f"{ghost_unicode} ", ghost_unicode)) -log.info('Start loading extensions from ./cogs/') +log.info('Start loading extensions from ./bot/cogs/') 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('cogs').glob('*.py')] + cogs = [file.stem for file in Path('bot', 'cogs').glob('*.py')] for extension in cogs: try: - bot.load_extension(f'cogs.{extension}') + bot.load_extension(f'bot.cogs.{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/halloweenify.py b/bot/cogs/halloweenify.py index ddd96bc6..3bd04b80 100644 --- a/bot/cogs/halloweenify.py +++ b/bot/cogs/halloweenify.py @@ -18,6 +18,9 @@ class Halloweenify: @commands.cooldown(1, 300, BucketType.user) @commands.command() async def halloweenify(self, ctx): + """ + Change your nickname into a much spookier one! + """ with open(Path('../bot/resources', 'halloweenify.json'), 'r') as f: data = load(f) diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py index 82b9c682..925f813f 100644 --- a/bot/cogs/movie.py +++ b/bot/cogs/movie.py @@ -18,8 +18,11 @@ class Movie: def __init__(self, bot): self.bot = bot - @commands.command(name='movie', alias=['tmdb'], brief='Pick a scary movie') + @commands.command(name='movie', alias=['tmdb']) async def random_movie(self, ctx): + """ + Randomly select a scary movie and display information about it. + """ selection = await self.select_movie() movie_details = await self.format_metadata(selection) diff --git a/bot/cogs/template.py b/bot/cogs/template.py index b3f4da21..aa01432c 100644 --- a/bot/cogs/template.py +++ b/bot/cogs/template.py @@ -17,7 +17,7 @@ class Template: """ await ctx.send('https://github.com/discord-python/hacktoberbot') - @commands.group(name='git', invoke_without_command=True) + @commands.group(name='git', invoke_without_command=True, brief="A link to resources for learning Git") async def github(self, ctx): """ A command group with the name git. You can now create sub-commands such as git commit. -- cgit v1.2.3