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

Commit

Permalink
Reorganize file structure
Browse files Browse the repository at this point in the history
  • Loading branch information
sco1 committed Sep 28, 2018
1 parent 1d13e86 commit 85d243d
Show file tree
Hide file tree
Showing 17 changed files with 125 additions and 114 deletions.
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ RUN pip install -r requirements.txt

RUN apk del .pynacl_deps

CMD ["python", "wumbotLogin.py"]
CMD ["python", "-m", "bot"]
13 changes: 13 additions & 0 deletions bot/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
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
)
25 changes: 7 additions & 18 deletions wumbotLogin.py → bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,8 @@

from discord.ext import commands

from cogs import overwatch, mhw, wumbopresence, rocketleague
from .cogs import overwatch, mhw, wumbopresence, rocketleague


# 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
)
class WumbotClient(commands.Bot):
def __init__(self, *args, **kwargs):
super(WumbotClient, self).__init__(*args, **kwargs)
Expand All @@ -42,14 +31,14 @@ def loadCredentials(credentialJSON) -> str:
client = WumbotClient(command_prefix='~')

# Load cogs
client.load_extension("cogs.bot")
client.load_extension("cogs.reddit")
client.load_extension("cogs.overwatch")
client.load_extension("cogs.mhw")
client.load_extension("cogs.rocketleague")
client.load_extension("bot.cogs.bot")
client.load_extension("bot.cogs.reddit")
client.load_extension("bot.cogs.overwatch")
client.load_extension("bot.cogs.mhw")
client.load_extension("bot.cogs.rocketleague")

# Setup event loops
client.loop.create_task(wumbopresence.randWumboTimer(client, wumboJSON='wumbolist.JSON'))
client.loop.create_task(wumbopresence.randWumboTimer(client, wumboJSON='./bot/wumbolist.JSON'))
client.loop.create_task(overwatch.patchchecktimer(client))
client.loop.create_task(mhw.patchchecktimer(client))
client.loop.create_task(rocketleague.patchchecktimer(client))
Expand Down
File renamed without changes.
File renamed without changes.
27 changes: 2 additions & 25 deletions cogs/bot.py → bot/cogs/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import git
from discord.ext import commands

from bot.utils import Helpers


class MainCommands():
def __init__(self, bot):
Expand Down Expand Up @@ -138,30 +140,5 @@ def _buildletterunicode():
return {letter:chr(ID) for letter, ID in zip(string.ascii_uppercase, range(127462, 127488))}


class Helpers:
@staticmethod
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

@staticmethod
def isDM(channel: discord.TextChannel) -> bool:
"""
Check to see if a channel is a DM
A DM is either an instance of DMChannel or GroupChannel
"""
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]


def setup(bot):
bot.add_cog(MainCommands(bot))
4 changes: 2 additions & 2 deletions cogs/mhw.py → bot/cogs/mhw.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
from discord.ext import commands
from yarl import URL

from .bot import Helpers
from .steam import SteamNewsPost
from bot.utils import Helpers
from bot.models.Steam import SteamNewsPost

class MHWNewsParser:
def __init__(self, bot):
Expand Down
4 changes: 2 additions & 2 deletions cogs/overwatch.py → bot/cogs/overwatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
from discord.ext import commands
from yarl import URL

from .bot import Helpers
from .reddit import RedditPost, RedditPRAW, RedditJSON
from bot.utils import Helpers
from bot.models.Reddit import RedditPost, RedditPRAW, RedditJSON


class PatchGifParser:
Expand Down
65 changes: 65 additions & 0 deletions bot/cogs/reddit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import re
import typing

import discord
from discord.ext import commands

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

@staticmethod
def buildSubredditEmbed(subredditlist: typing.List[str], embedlimit: int=3):
"""
Build a message embed from a list of subreddit strings (sans '/r/')
Limit to embedlimit number of subreddits per embed, for brevity. Default is 3
"""
snooURL = "https://images-eu.ssl-images-amazon.com/images/I/418PuxYS63L.png"

embed = discord.Embed(color=discord.Color(0x9c4af7))
embed.set_thumbnail(url=snooURL)
embed.set_author(name='Subreddit Embedder 9000')
embed.set_footer(text='Reddit', icon_url=snooURL)

if len(subredditlist) == 1:
embed.description = "Subreddit detected!"
subreddit = subredditlist[0]
embed.add_field(name=f"/r/{subreddit}", value=f"https://www.reddit.com/r/{subreddit}", inline=False)
else:
embed.description = "Subreddits detected!"
for subreddit in subredditlist[0:embedlimit]:
embed.add_field(name=f"/r/{subreddit}", value=f"https://www.reddit.com/r/{subreddit}", inline=False)

if len(subredditlist) > embedlimit:
embed.add_field(name="Note:", value=f"For brevity, only {embedlimit} subreddits have been embedded. You linked {len(subredditlist)}")

return embed

async def on_message(self, message: discord.Message):
# Avoid self-replies
if message.author.id == self.bot.user.id:
return

# Check to see if /r/_subreddit (e.g. /r/python) has been typed & add a Reddit embed
# Ignores regular reddit links (e.g. http://www.reddit.com/r/Python)
testSubreddit = re.findall(r'(?:^|\s)\/?[rR]\/(\w+)', message.content)
if testSubreddit:
logging.info(f"Subreddit(s) detected: '{testSubreddit}'")
logging.info(f"Original message: '{message.content}'")
SubredditEmbed = self.buildSubredditEmbed(testSubreddit)
await message.channel.send(embed=SubredditEmbed)

# Check to see if Reddit's stupid image/video hosting has added 'DashPlaylist.mpd'
# to the end of the URL, which links to a direct download (of nothing) rather
# than the web content
testVreddit = re.search(r'(https?:\/\/v.redd.it\/.*)(DASHPlaylist.*$)', message.content)
if testVreddit:
newURL = testVreddit.group(1)
logging.info(f"VReddit MPD detected: '{testVreddit.group(0)}'")
logging.info(f"Link converted to: {newURL}")
await message.channel.send(f"Here {message.author.mention}, let me fix that v.redd.it link for you: {newURL}")


def setup(bot):
bot.add_cog(Reddit(bot))
6 changes: 3 additions & 3 deletions cogs/rocketleague.py → bot/cogs/rocketleague.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
from discord.ext import commands
from yarl import URL

from .bot import Helpers
from .steam import SteamNewsPost
from bot.utils import Helpers
from bot.models.Steam import SteamNewsPost

class RLNewsParser:
def __init__(self, bot):
Expand All @@ -29,7 +29,7 @@ async def getofficialnews(self, appID: int=None) -> typing.List:
appID = appID if appID is not None else self.appID

news = await SteamNewsPost.asyncgetnewsforapp(appID=appID, count=15, maxlength=500)
logging.info(f"{len(news)} RLnews posts returned by Steam's API")
logging.info(f"{len(news)} RL news post(s) returned by Steam's API")
officialnews = [item for item in news if self.RLnewsfilter(item, self.psyonixstaff)]

logging.info(f"Found {len(officialnews)} official RL news posts")
Expand Down
File renamed without changes.
71 changes: 8 additions & 63 deletions cogs/reddit.py → bot/models/Reddit.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@
from pathlib import Path

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


Expand Down Expand Up @@ -53,6 +51,14 @@ def fromPRAW(inSub: praw.Submission) -> RedditPost:
}
return RedditPost(**submissiondict)

@staticmethod
def _stripURLs(instr: str) -> str:
"""
Strip out URLs from the returned content preview. They don't render in
Discord embeds so they just sit there and look bad.
"""
raise NotImplementedError


class RedditPRAW:
def __init__(self, credentialJSON: Path=Path('./credentials.JSON')):
Expand Down Expand Up @@ -259,64 +265,3 @@ def _isusernonsubmission(inURL: URL=None) -> bool:
return 'submitted' not in urlparts
else:
return False


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

@staticmethod
def buildSubredditEmbed(subredditlist: typing.List[str], embedlimit: int=3):
"""
Build a message embed from a list of subreddit strings (sans '/r/')
Limit to embedlimit number of subreddits per embed, for brevity. Default is 3
"""
snooURL = "https://images-eu.ssl-images-amazon.com/images/I/418PuxYS63L.png"

embed = discord.Embed(color=discord.Color(0x9c4af7))
embed.set_thumbnail(url=snooURL)
embed.set_author(name='Subreddit Embedder 9000')
embed.set_footer(text='Reddit', icon_url=snooURL)

if len(subredditlist) == 1:
embed.description = "Subreddit detected!"
subreddit = subredditlist[0]
embed.add_field(name=f"/r/{subreddit}", value=f"https://www.reddit.com/r/{subreddit}", inline=False)
else:
embed.description = "Subreddits detected!"
for subreddit in subredditlist[0:embedlimit]:
embed.add_field(name=f"/r/{subreddit}", value=f"https://www.reddit.com/r/{subreddit}", inline=False)

if len(subredditlist) > embedlimit:
embed.add_field(name="Note:", value=f"For brevity, only {embedlimit} subreddits have been embedded. You linked {len(subredditlist)}")

return embed

async def on_message(self, message: discord.Message):
# Avoid self-replies
if message.author.id == self.bot.user.id:
return

# Check to see if /r/_subreddit (e.g. /r/python) has been typed & add a Reddit embed
# Ignores regular reddit links (e.g. http://www.reddit.com/r/Python)
testSubreddit = re.findall(r'(?:^|\s)\/?[rR]\/(\w+)', message.content)
if testSubreddit:
logging.info(f"Subreddit(s) detected: '{testSubreddit}'")
logging.info(f"Original message: '{message.content}'")
SubredditEmbed = self.buildSubredditEmbed(testSubreddit)
await message.channel.send(embed=SubredditEmbed)

# Check to see if Reddit's stupid image/video hosting has added 'DashPlaylist.mpd'
# to the end of the URL, which links to a direct download (of nothing) rather
# than the web content
testVreddit = re.search(r'(https?:\/\/v.redd.it\/.*)(DASHPlaylist.*$)', message.content)
if testVreddit:
newURL = testVreddit.group(1)
logging.info(f"VReddit MPD detected: '{testVreddit.group(0)}'")
logging.info(f"Link converted to: {newURL}")
await message.channel.send(f"Here {message.author.mention}, let me fix that v.redd.it link for you: {newURL}")


def setup(bot):
bot.add_cog(Reddit(bot))
File renamed without changes.
Empty file added bot/models/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions bot/utils/Helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
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
A DM is either an instance of DMChannel or GroupChannel
"""
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]
Empty file added bot/utils/__init__.py
Empty file.
File renamed without changes.

0 comments on commit 85d243d

Please sign in to comment.