Skip to content
This repository has been archived by the owner on Nov 24, 2019. It is now read-only.

Commit

Permalink
Black & Flake8 Pass
Browse files Browse the repository at this point in the history
  • Loading branch information
sco1 committed Oct 28, 2018
1 parent 53e6669 commit 279f358
Show file tree
Hide file tree
Showing 14 changed files with 61 additions and 51 deletions.
20 changes: 11 additions & 9 deletions bot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import logging
import time

# Force UTC Timestamps
# From the logging cookbook: https://docs.python.org/3/howto/logging-cookbook.html
class UTCFormatter(logging.Formatter):
converter = time.gmtime

logformat = '%(asctime)s %(levelname)s:%(module)s:%(message)s'
dateformat = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(filename='./log/wumbot.log', filemode='a', level=logging.INFO,
format=logformat, datefmt=dateformat
)
logging.Formatter.converter = time.gmtime # Force UTC

logformat = "%(asctime)s %(levelname)s:%(module)s:%(message)s"
dateformat = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(
filename="./log/wumbot.log",
filemode="a",
level=logging.INFO,
format=logformat,
datefmt=dateformat,
)
22 changes: 13 additions & 9 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,25 @@ def __init__(self, *args, **kwargs):

async def on_ready(self):
self.launch_time = datetime.utcnow()
logging.info(f'Logged in as {self.user}')
print(f'Logged in as {self.user}') # Keep print statement for dev debugging
logging.info(f"Logged in as {self.user}")
print(f"Logged in as {self.user}") # Keep print statement for dev debugging


def loadCredentials(credentialJSON) -> str:
"""
Load login credentials from the input JSON file
"""
with open(credentialJSON, mode='r') as fID:
with open(credentialJSON, mode="r") as fID:
credentials = json.load(fID)

return credentials['DiscordToken']
return credentials["DiscordToken"]


credentialpath = './credentials.JSON'
credentialpath = "./credentials.JSON"
credentials = loadCredentials(credentialpath)
if credentials:
client = WumbotClient(command_prefix='~')
client = WumbotClient(command_prefix="~")

# Load cogs
client.load_extension("bot.cogs.bot")
client.load_extension("bot.cogs.reddit")
Expand All @@ -40,12 +42,14 @@ def loadCredentials(credentialJSON) -> str:
client.load_extension("bot.cogs.rocketleague")

# Setup event loops
client.loop.create_task(wumbopresence.randWumboTimer(client, wumboJSON='./bot/wumbolist.JSON'))
client.loop.create_task(
wumbopresence.randWumboTimer(client, wumboJSON="./bot/wumbolist.JSON")
)
patchchecks = (
overwatch.PatchRundownParser(client),
overwatch.PatchNotesParser(client),
mhw.MHWNewsParser(client),
rocketleague.RLNewsParser(client)
rocketleague.RLNewsParser(client),
)
client.loop.create_task(patchchecktimer(client, patchchecks))

Expand Down
22 changes: 14 additions & 8 deletions bot/cogs/amazon.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
import logging
import re

import discord
from discord.ext import commands


class Amazon():
class Amazon:
def __init__(self, bot):
self.bot = bot

Expand All @@ -15,9 +11,19 @@ async def on_message(self, message):
return

# Check for "regular" Amazon link, capture full link & ASIN
testAmazonASIN = re.search(r'https?.*\/\/.+\.amazon\..+\/([A-Z0-9]{10})\/\S*', message.content, flags=re.IGNORECASE)
testAmazonASIN = re.search(
r"https?.*\/\/.+\.amazon\..+\/([A-Z0-9]{10})\/\S*",
message.content,
flags=re.IGNORECASE,
)
# Check for shortened Amazon link (https://a.co/*), capture full link
testAmazonShort = re.search(r'https?:\/\/a\.co\S*', message.content, flags=re.IGNORECASE)
testAmazonShort = re.search(
r"https?:\/\/a\.co\S*", message.content, flags=re.IGNORECASE
)

if testAmazonASIN or testAmazonShort:
raise NotImplementedError


def setup(bot):
bot.add_cog(Amazon(bot))
bot.add_cog(Amazon(bot))
7 changes: 4 additions & 3 deletions bot/cogs/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async def ver(self, ctx: commands.Context):
repoGit = currRepo.git
try:
await ctx.message.channel.send(f"Current Version: {repoGit.describe()}")
except git.GitCommandError as err:
except git.GitCommandError:
await ctx.send("No tags found on current branch")

@commands.command()
Expand Down Expand Up @@ -75,7 +75,8 @@ async def reactmessage(
Command and any feedback are deleted after selfdestructdelay seconds
"""
# Assume last entry in args is the message ID and concatenate everything else into the message
# Assume last entry in args is the message ID
# Concatenate everything else into the message
continueflag = False
try:
messageID = int(args[0])
Expand Down Expand Up @@ -144,7 +145,7 @@ def _buildletterunicode():
Return a dictionary mapping of alphabetical characters to their
Unicode Regional Indicator Symbol Equivalent (1F1E6..1F1FF)
See:
See:
https://en.wikipedia.org/wiki/Regional_Indicator_Symbol
https://www.unicode.org/charts/PDF/U1F100.pdf
"""
Expand Down
3 changes: 0 additions & 3 deletions bot/cogs/mhw.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import json
import logging
import typing
from datetime import datetime
from pathlib import Path

import aiohttp
import discord
from discord.ext import commands
from yarl import URL
Expand Down
4 changes: 1 addition & 3 deletions bot/cogs/overwatch.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import json
import logging
import re
import typing
from pathlib import Path

Expand Down Expand Up @@ -55,7 +53,7 @@ async def getpatchrundowns(self, jsonURL: URL = None):

async def postembed(self, postobj: RedditPost = None, channelID: int = None):
"""
Generate & send an embed for the input RedditPost object, built from
Generate & send an embed for the input RedditPost object, built from
/u/itsjieyang's Reddit submissions.
There are 2 message formats:
Expand Down
7 changes: 3 additions & 4 deletions bot/cogs/reddit.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import json
import logging
import re
import typing

import discord
import requests
from discord.ext import commands
from yarl import URL


Expand Down Expand Up @@ -97,7 +96,7 @@ async def on_message(self, message: discord.Message):
def _isvalidsubreddit(subreddit: str) -> bool:
"""
Return True if subreddit resolves to a valid Reddit subreddit, else return False
If the JSON request times out or is API throttled, True is returned as a fallback
"""
baseURL = URL("https://old.reddit.com/")
Expand All @@ -113,7 +112,7 @@ def _isvalidsubreddit(subreddit: str) -> bool:
else:
logging.info(f"Unhandled Reddit response: '{msg}'")
return True
except KeyError as e:
except KeyError:
return True


Expand Down
1 change: 0 additions & 1 deletion bot/cogs/rocketleague.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import json
import logging
import typing
from pathlib import Path
Expand Down
1 change: 0 additions & 1 deletion bot/models/NewsParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json
import logging
import typing
from pathlib import Path


class NewsParser:
Expand Down
7 changes: 4 additions & 3 deletions bot/models/Overwatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,13 @@ def _parseOWpatchHTML(inHTML: str) -> typing.List:
for patch in patches:
# Get patch reference ID
patchref = patch.get("id")
patchref_num = patchref.split("-")[-1] # Get numeric reference to build BlizzTrack link later
# Get numeric reference to build BlizzTrack link later
patchref_num = patchref.split("-")[-1]

# Get version number from sidebar using patch reference ID
sidebaritem = soup.select_one(f"a[href=#{patchref}]").parent
ver = sidebaritem.find("h3").get_text().split()[-1]

# Generate full reference from version number & patch reference because
# Blizzard reuses version numbers for some patches
# e.g. 1.29.0.1.51948 and 1.29.0.1.51575
Expand Down Expand Up @@ -138,7 +139,7 @@ def _parseOWpatchHTML(inHTML: str) -> typing.List:
def getblizztrack(patchref: str = None) -> URL:
"""
Return BlizzTrack URL to patch notes, built using Blizzard's patchref
e.g. https://blizztrack.com/patch_notes/overwatch/50148
"""
if not patchref:
Expand Down
6 changes: 3 additions & 3 deletions bot/models/Reddit.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ def __init__(self, credentialJSON: Path = Path("./credentials.JSON")):
# Try to get some submissions to check for correct authentication
self.isauthenticated = True
try:
_ = self.session.subreddit("python").hot(limit=1)
except praw.exceptions.ResponseException as e:
self.session.subreddit("python").hot(limit=1)
except praw.exceptions.ResponseException:
self.isauthenticated = False

if self.isauthenticated:
Expand Down Expand Up @@ -243,7 +243,7 @@ def _validateURL(inURL: typing.Union[URL, str], checkJSON: bool = True) -> URL:
Perform some rudimentary Reddit URL validation for the class' methods
Raises a ValueError if a URL is not provided or if a Reddit user link is provided that
is not the user's submissions. The checkJSON flag can be set to check whether the URL
is not the user's submissions. The checkJSON flag can be set to check whether the URL
suffix is .json
Returns a yarl.URL if the checks pass
Expand Down
5 changes: 2 additions & 3 deletions bot/models/Steam.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import re
import typing
from datetime import datetime
Expand Down Expand Up @@ -45,7 +44,7 @@ def __repr__(self):

@staticmethod
async def asyncgetnewsforapp(
appID: int = 582010,
appID: int = 582_010,
count: int = 10,
maxlength: int = 300,
format: str = "json",
Expand Down Expand Up @@ -77,7 +76,7 @@ async def asyncgetnewsforapp(

@staticmethod
def getnewsforapp(
appID: int = 582010,
appID: int = 582_010,
count: int = 10,
maxlength: int = 300,
format: str = "json",
Expand Down
5 changes: 4 additions & 1 deletion bot/utils/Helpers.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import discord


def isOwner(user: discord.User) -> bool:
"""
Check to see if the input User's ID matches the Owner ID
"""
ownerID = 129606635545952258
return user.id == ownerID


def isDM(channel: discord.TextChannel) -> bool:
"""
Check to see if a channel is a DM
Expand All @@ -15,8 +17,9 @@ def isDM(channel: discord.TextChannel) -> bool:
"""
return isinstance(channel, (discord.DMChannel, discord.GroupChannel))


def isWumbologist(member: discord.Member) -> bool:
"""
Check to see if a discord.Member has the 'Wumbologists' role
"""
return 'Wumbologists' in [str(role) for role in member.roles]
return "Wumbologists" in [str(role) for role in member.roles]
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[flake8]
ignore = E501 # Ignore line length, mostly taken care of by rulers in the editor

0 comments on commit 279f358

Please sign in to comment.