diff options
author | 2018-10-12 15:43:34 -0700 | |
---|---|---|
committer | 2018-10-12 15:43:34 -0700 | |
commit | d6051c5e8ef1a20b0833e67f75c5367df12e5622 (patch) | |
tree | 92ec894452eb4068a0553d531ac1515fb2d41ca8 /bot | |
parent | Fixed linting: Multiple imports on single line. (diff) | |
parent | The app was logging to the wrong directory. This is now fixed. Also silenced ... (diff) |
Merge branch 'master' of https://github.com/discord-python/hacktoberbot into vote-monster-refactor
Diffstat (limited to 'bot')
-rw-r--r-- | bot/__init__.py | 22 | ||||
-rw-r--r-- | bot/__main__.py | 21 | ||||
-rw-r--r-- | bot/cogs/hacktoberstats.py | 7 | ||||
-rw-r--r-- | bot/cogs/halloweenify.py | 7 | ||||
-rw-r--r-- | bot/cogs/movie.py | 83 | ||||
-rw-r--r-- | bot/cogs/spookyreact.py | 31 | ||||
-rw-r--r-- | bot/cogs/template.py | 2 | ||||
-rw-r--r-- | bot/resources/halloweenify.json | 3 |
8 files changed, 129 insertions, 47 deletions
diff --git a/bot/__init__.py b/bot/__init__.py index 1d320245..c411deb6 100644 --- a/bot/__init__.py +++ b/bot/__init__.py @@ -1,11 +1,11 @@ import logging.handlers import os +from pathlib import Path # set up logging - -log_dir = 'log' -log_file = log_dir + os.sep + 'hackbot.log' +log_dir = Path("bot", "log") +log_file = log_dir / "hackbot.log" os.makedirs(log_dir, exist_ok=True) # file handler sets up rotating logs every 5 MB @@ -23,9 +23,15 @@ 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.getLogger("websockets").setLevel(logging.ERROR) -logging.info('Logging Process Started') +# 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 index c40836c5..ccd69b0b 100644 --- a/bot/__main__.py +++ b/bot/__main__.py @@ -5,34 +5,35 @@ 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 - logging.info(f'Bot token loaded: {HACKTOBERBOT_TOKEN[:token_dl]}...{HACKTOBERBOT_TOKEN[-token_dl:]}') + log.info(f'Bot token loaded: {HACKTOBERBOT_TOKEN[:token_dl]}...{HACKTOBERBOT_TOKEN[-token_dl:]}') else: - logging.error(f'Bot token not found: {HACKTOBERBOT_TOKEN}') + 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)) -logging.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}') - logging.info(f'Successfully loaded extension: {extension}') + bot.load_extension(f'bot.cogs.{extension}') + log.info(f'Successfully loaded extension: {extension}') except Exception as e: - logging.error(f'Failed to load extension {extension}: {repr(e)} {format_exc()}') + log.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...') +log.info(f'Spooky Launch Sequence Initiated...') bot.run(HACKTOBERBOT_TOKEN) -logging.info(f'HackBot has been slain!') +log.info(f'HackBot has been slain!') diff --git a/bot/cogs/hacktoberstats.py b/bot/cogs/hacktoberstats.py index 0a280443..ac81b887 100644 --- a/bot/cogs/hacktoberstats.py +++ b/bot/cogs/hacktoberstats.py @@ -96,7 +96,12 @@ class Stats: 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}" + 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"} diff --git a/bot/cogs/halloweenify.py b/bot/cogs/halloweenify.py index 201f6b95..a5fe45ef 100644 --- a/bot/cogs/halloweenify.py +++ b/bot/cogs/halloweenify.py @@ -2,14 +2,12 @@ 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! """ @@ -20,7 +18,10 @@ class Halloweenify: @commands.cooldown(1, 300, BucketType.user) @commands.command() async def halloweenify(self, ctx): - with open(Path('../bot/resources', 'halloweenify.json'), 'r') as f: + """ + Change your nickname into a much spookier one! + """ + with open(Path('./bot/resources', '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. diff --git a/bot/cogs/movie.py b/bot/cogs/movie.py index 647ee22a..925f813f 100644 --- a/bot/cogs/movie.py +++ b/bot/cogs/movie.py @@ -1,7 +1,7 @@ import random from os import environ -import requests +import aiohttp from discord import Embed from discord.ext import commands @@ -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) @@ -42,19 +45,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): @@ -62,36 +70,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 diff --git a/bot/cogs/spookyreact.py b/bot/cogs/spookyreact.py new file mode 100644 index 00000000..2652a60e --- /dev/null +++ b/bot/cogs/spookyreact.py @@ -0,0 +1,31 @@ +SPOOKY_TRIGGERS = { + 'spooky': "\U0001F47B", + 'skeleton': "\U0001F480", + 'doot': "\U0001F480", + 'pumpkin': "\U0001F383", + 'halloween': "\U0001F383", + 'jack-o-lantern': "\U0001F383", + 'danger': "\U00002620" +} + + +class SpookyReact: + + """ + A cog that makes the bot react to message triggers. + """ + + def __init__(self, bot): + self.bot = bot + + async def on_message(self, ctx): + """ + A command to send the hacktoberbot github project + """ + for trigger in SPOOKY_TRIGGERS.keys(): + if trigger in ctx.content.lower(): + await ctx.add_reaction(SPOOKY_TRIGGERS[trigger]) + + +def setup(bot): + bot.add_cog(SpookyReact(bot)) 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. 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 |