From 9af16d77de893245a98ddb7c91825dd54bd6b106 Mon Sep 17 00:00:00 2001 From: Ryan Gables Date: Sat, 6 Oct 2018 18:21:12 -0700 Subject: made apikey env var + formatted omdb response --- bot/cogs/movie.py | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 bot/cogs/movie.py (limited to 'bot/cogs/movie.py') diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py new file mode 100644 index 00000000..45714005 --- /dev/null +++ b/bot/cogs/movie.py @@ -0,0 +1,65 @@ +import requests +import random +from discord.ext import commands +from os import environ + +OMDB_API_KEY = environ.get('OMDB_API_KEY') + + +class Movie: + """ + Prints the details of a random scary movie to discord chat + """ + + def __init__(self, bot): + self.bot = bot + + @commands.command(name='movie', aliases=['scary_movie'], brief='Pick me a scary movie') + async def random_movie(self, ctx): + selection = await self.select_movie() + movie_details = await self.format_metadata(selection) + + await ctx.send(movie_details) + + @staticmethod + async def select_movie(): + """ + Selects a random movie and returns a json of movie details from omdb + """ + + # TODO: Come up w/ a scary movie list to select from. Currently returns random Halloween movie + omdb_params = { + 'apikey': OMDB_API_KEY, + 'type': 'movie', + 's': 'halloween' + } + response = requests.get('http://www.omdbapi.com/', omdb_params) + + movies = [] + for movie in response.json().get('Search'): + movie_id = movie.get('imdbID') + movies.append(movie_id) + + selection = random.choice(movies) + + omdb_params = { + 'apikey': OMDB_API_KEY, + 'i': selection + } + response = requests.get('http://www.omdbapi.com/', omdb_params) + + return response.json() + + @staticmethod + async def format_metadata(movie): + """ + Formats raw omdb data to be displayed in discord chat + """ + display_text = f"You should watch {movie.get('Title')} ({movie.get('Year')})\n" \ + f"https://www.imdb.com/title/{movie.get('imdbID')}" + + return display_text + + +def setup(bot): + bot.add_cog(Movie(bot)) -- cgit v1.2.3 From eee33d3d294686a99e6410ad9d43ff155ee763dd Mon Sep 17 00:00:00 2001 From: Ryan Gables Date: Tue, 9 Oct 2018 01:16:38 -0700 Subject: Embeds movie data from TMDb --- bot/cogs/movie.py | 88 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 61 insertions(+), 27 deletions(-) (limited to 'bot/cogs/movie.py') diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py index 45714005..65c96075 100644 --- a/bot/cogs/movie.py +++ b/bot/cogs/movie.py @@ -1,64 +1,98 @@ import requests import random -from discord.ext import commands from os import environ +from discord.ext import commands +from discord import Embed -OMDB_API_KEY = environ.get('OMDB_API_KEY') +TMDB_API_KEY = environ.get('TMDB_API_KEY') +TMDB_TOKEN = environ.get('TMDB_TOKEN') class Movie: """ - Prints the details of a random scary movie to discord chat + Selects a random scary movie and embeds info into discord chat """ def __init__(self, bot): self.bot = bot - @commands.command(name='movie', aliases=['scary_movie'], brief='Pick me a scary movie') + @commands.command(name='movie', alias=['tmdb'], brief='Pick a scary movie') async def random_movie(self, ctx): selection = await self.select_movie() movie_details = await self.format_metadata(selection) - await ctx.send(movie_details) + await ctx.send(embed=movie_details) @staticmethod async def select_movie(): """ - Selects a random movie and returns a json of movie details from omdb + Selects a random movie and returns a json of movie details from TMDb """ - # TODO: Come up w/ a scary movie list to select from. Currently returns random Halloween movie - omdb_params = { - 'apikey': OMDB_API_KEY, - 'type': 'movie', - 's': 'halloween' + url = 'https://api.themoviedb.org/4/discover/movie' + params = { + 'with_genres': '27', + 'vote_count.gte': '5' + } + headers = { + 'Authorization': 'Bearer ' + TMDB_TOKEN, + 'Content-Type': 'application/json;charset=utf-8' } - response = requests.get('http://www.omdbapi.com/', omdb_params) - movies = [] - for movie in response.json().get('Search'): - movie_id = movie.get('imdbID') - movies.append(movie_id) + # Get total page count of horror movies + response = requests.get(url=url, params=params, headers=headers) + total_pages = response.json().get('total_pages') - selection = random.choice(movies) + # 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') - omdb_params = { - 'apikey': OMDB_API_KEY, - 'i': selection - } - response = requests.get('http://www.omdbapi.com/', omdb_params) + # 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'}) - return response.json() + return selection.json() @staticmethod async def format_metadata(movie): """ - Formats raw omdb data to be displayed in discord chat + Formats raw TMDb data to be embedded in discord chat """ - display_text = f"You should watch {movie.get('Title')} ({movie.get('Year')})\n" \ - f"https://www.imdb.com/title/{movie.get('imdbID')}" - return display_text + tmdb_url = 'https://www.themoviedb.org/movie/' + str(movie.get('id')) + poster = 'https://image.tmdb.org/t/p/original' + movie.get('poster_path') + + cast = [] + for actor in movie.get('credits').get('cast')[:3]: + cast.append(actor.get('name')) + + director = movie.get('credits').get('crew')[0].get('name') + + rating_count = movie.get('vote_average') / 2 + rating = '' + + for i in range(int(rating_count)): + rating += ':skull:' + + if (rating_count % 1) >= .5: + rating += ':bat:' + + embed = Embed( + colour=0x01d277, + title='**' + movie.get('title') + '**', + url=tmdb_url, + description=movie.get('overview') + ) + embed.set_image(url=poster) + embed.add_field(name='Staring', 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')) + 'm') + embed.add_field(name='Spooky Rating', value=rating) + embed.set_footer(text='powered by themoviedb.org') + + return embed def setup(bot): -- cgit v1.2.3 From 9f4065bcc720857564498d526c88bcc0a8c51881 Mon Sep 17 00:00:00 2001 From: Ryan Gables Date: Tue, 9 Oct 2018 01:40:39 -0700 Subject: spelling --- bot/cogs/movie.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot/cogs/movie.py') diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py index 65c96075..bb6f8df8 100644 --- a/bot/cogs/movie.py +++ b/bot/cogs/movie.py @@ -85,10 +85,10 @@ class Movie: description=movie.get('overview') ) embed.set_image(url=poster) - embed.add_field(name='Staring', value=', '.join(cast)) + 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')) + 'm') + embed.add_field(name='Runtime', value=str(movie.get('runtime')) + ' min') embed.add_field(name='Spooky Rating', value=rating) embed.set_footer(text='powered by themoviedb.org') -- cgit v1.2.3 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/__init__.py | 19 ++++++++++++------- bot/__main__.py | 39 +++++++++++++++++++++++++++++++++++++++ bot/bot.py | 39 --------------------------------------- bot/cogs/hacktoberstats.py | 9 ++++++++- bot/cogs/halloweenify.py | 4 +--- bot/cogs/movie.py | 33 ++++++++++++++++++++------------- bot/resources/halloweenify.json | 3 +++ 7 files changed, 83 insertions(+), 63 deletions(-) create mode 100644 bot/__main__.py delete mode 100644 bot/bot.py (limited to 'bot/cogs/movie.py') diff --git a/bot/__init__.py b/bot/__init__.py index 8cbcd121..c2ea4ba0 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -1,8 +1,8 @@ -import os import logging.handlers +import os -# set up logging +# set up logging log_dir = 'log' log_file = log_dir + os.sep + 'hackbot.log' os.makedirs(log_dir, exist_ok=True) @@ -22,9 +22,14 @@ if root.handlers: for handler in root.handlers: root.removeHandler(handler) -# setup new logging configuration -logging.basicConfig(format='%(asctime)s - %(name)s %(levelname)s: %(message)s', datefmt="%D %H:%M:%S", - level=logging.DEBUG, - handlers=[console_handler, file_handler]) +# Silence irrelevant loggers +logging.getLogger("discord").setLevel(logging.ERROR) -logging.info('Logging Process Started') \ No newline at end of file +# setup new logging configuration +logging.basicConfig( + format='%(asctime)s - %(name)s %(levelname)s: %(message)s', + datefmt="%D %H:%M:%S", + level=logging.DEBUG, + handlers=[console_handler, file_handler] +) +logging.getLogger().info('Logging initialization complete') diff --git a/bot/__main__.py b/bot/__main__.py new file mode 100644 index 00000000..2c41d2d9 --- /dev/null +++ b/bot/__main__.py @@ -0,0 +1,39 @@ +import logging +from os import environ +from pathlib import Path +from traceback import format_exc + +from discord.ext import commands + +HACKTOBERBOT_TOKEN = environ.get('HACKTOBERBOT_TOKEN') +log = logging.getLogger() + +if HACKTOBERBOT_TOKEN: + token_dl = len(HACKTOBERBOT_TOKEN) // 8 + log.info(f'Bot token loaded: {HACKTOBERBOT_TOKEN[:token_dl]}...{HACKTOBERBOT_TOKEN[-token_dl:]}') +else: + log.error(f'Bot token not found: {HACKTOBERBOT_TOKEN}') + +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/') + + +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')] + for extension in cogs: + try: + bot.load_extension(f'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()}') + # print(f'Failed to load extension {extension}.', file=stderr) + # print_exc() + +log.info(f'Spooky Launch Sequence Initiated...') + +bot.run(HACKTOBERBOT_TOKEN) + +log.info(f'HackBot has been slain!') diff --git a/bot/bot.py b/bot/bot.py deleted file mode 100644 index a40ed0d4..00000000 --- a/bot/bot.py +++ /dev/null @@ -1,39 +0,0 @@ -from os import environ -from pathlib import Path -from sys import stderr -from traceback import print_exc, format_exc - -from discord.ext import commands -import logging - -HACKTOBERBOT_TOKEN = environ.get('HACKTOBERBOT_TOKEN') - -if HACKTOBERBOT_TOKEN: - token_dl = len(HACKTOBERBOT_TOKEN) // 8 - logging.info(f'Bot token loaded: {HACKTOBERBOT_TOKEN[:token_dl]}...{HACKTOBERBOT_TOKEN[-token_dl:]}') -else: - logging.error(f'Bot token not found: {HACKTOBERBOT_TOKEN}') - -ghost_unicode = "\N{GHOST}" -bot = commands.Bot(command_prefix=commands.when_mentioned_or(".", f"{ghost_unicode} ", ghost_unicode)) - -logging.info('Start loading extensions from ./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')] - for extension in cogs: - try: - bot.load_extension(f'cogs.{extension}') - logging.info(f'Successfully loaded extension: {extension}') - except Exception as e: - logging.error(f'Failed to load extension {extension}: {repr(e)} {format_exc()}') - # print(f'Failed to load extension {extension}.', file=stderr) - # print_exc() - -logging.info(f'Spooky Launch Sequence Initiated...') - -bot.run(HACKTOBERBOT_TOKEN) - -logging.info(f'HackBot has been slain!') \ No newline at end of file diff --git a/bot/cogs/hacktoberstats.py b/bot/cogs/hacktoberstats.py index 4e896ae9..ac81b887 100644 --- a/bot/cogs/hacktoberstats.py +++ b/bot/cogs/hacktoberstats.py @@ -95,7 +95,14 @@ class Stats: is_query = f"public+author:{username}" date_range = "2018-10-01..2018-10-31" per_page = "300" - query_url = f"{base_url}-label:{not_label}+type:{action_type}+is:{is_query}+created:{date_range}&per_page={per_page}" + query_url = ( + f"{base_url}" + f"-label:{not_label}" + f"+type:{action_type}" + f"+is:{is_query}" + f"+created:{date_range}" + f"&per_page={per_page}" + ) headers = {"user-agent": "Discord Python Hactoberbot"} async with aiohttp.ClientSession() as session: diff --git a/bot/cogs/halloweenify.py b/bot/cogs/halloweenify.py index 8a9db3df..ddd96bc6 100644 --- a/bot/cogs/halloweenify.py +++ b/bot/cogs/halloweenify.py @@ -1,15 +1,13 @@ -from pathlib import Path from json import load +from pathlib import Path from random import choice - import discord from discord.ext import commands from discord.ext.commands.cooldowns import BucketType class Halloweenify: - """ A cog to change a invokers nickname to a spooky one! """ 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: diff --git a/bot/resources/halloweenify.json b/bot/resources/halloweenify.json index 458f9342..88c46bfc 100644 --- a/bot/resources/halloweenify.json +++ b/bot/resources/halloweenify.json @@ -74,6 +74,9 @@ }, { "Chatterer": "https://c-5uwzmx78pmca09x24quoqfx2ezivsmzx2ekwu.g00.ranker.com/g00/3_c-5eee.zivsmz.kwu_/c-5UWZMXPMCA09x24pbbx78ax3ax2fx2fquoqf.zivsmz.kwux2fvwlm_quox2f14x2f586061x2fwzqoqvitx2fkpibbmzmz-nqtu-kpizikbmza-x78pwbw-9x3fex3d438x26yx3d48x26nux3drx78ox26nqbx3dkzwx78x26kzwx78x3dnikmax22x26q98k.uizsx3dquiom_$/$/$/$/$/$" + }, + { + "Pale Man": "https://i2.wp.com/macguff.in/wp-content/uploads/2016/10/Pans-Labyrinth-Movie-Header-Image.jpg?fit=630%2C400&ssl=1" } ] } \ No newline at end of file -- 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