aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Leon Sandøy <[email protected]>2018-10-11 11:44:28 +0200
committerGravatar Leon Sandøy <[email protected]>2018-10-11 11:44:28 +0200
commita606e483b3a42357778fc3d4979e800e8dd38739 (patch)
treeee2c99f8d7172b87ed2e1dd1b90c09b52fbb26c8
parentMerge pull request #34 from markylon/master (diff)
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.
-rw-r--r--bot/__init__.py19
-rw-r--r--bot/__main__.py (renamed from bot/bot.py)20
-rw-r--r--bot/cogs/hacktoberstats.py9
-rw-r--r--bot/cogs/halloweenify.py4
-rw-r--r--bot/cogs/movie.py33
-rw-r--r--bot/resources/halloweenify.json3
6 files changed, 54 insertions, 34 deletions
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/bot.py b/bot/__main__.py
index a40ed0d4..2c41d2d9 100644
--- a/bot/bot.py
+++ b/bot/__main__.py
@@ -1,23 +1,23 @@
+import logging
from os import environ
from pathlib import Path
-from sys import stderr
-from traceback import print_exc, format_exc
+from traceback import format_exc
from discord.ext import commands
-import logging
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 ./cogs/')
if __name__ == '__main__':
@@ -26,14 +26,14 @@ if __name__ == '__main__':
for extension in cogs:
try:
bot.load_extension(f'cogs.{extension}')
- logging.info(f'Successfully loaded extension: {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!') \ No newline at end of file
+log.info(f'HackBot has been slain!')
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