Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
1ed857d
chore: switch commands.Bot typehints to bot.bot's Bot
vcokltfre Apr 19, 2021
713396a
chore(evergreen): format each cog load docstring the same way
vcokltfre Apr 19, 2021
227d0a7
chore(evergreen): make usage of . at sentence ends consistent
vcokltfre Apr 19, 2021
f919e0c
chore(evergreen): remove unneeded cog constructors
vcokltfre Apr 19, 2021
ae64ddd
Clean Up the Halloween Season
ToxicKidz Apr 19, 2021
8662541
chore: ctx.channel.send -> ctx.send
vcokltfre Apr 20, 2021
97048ce
Clean Up Christmas Season
ToxicKidz Apr 20, 2021
cda51f6
Merge branch 'spring-cleanup' of https://github.com/ToxicKidz/sir-lan…
ToxicKidz Apr 20, 2021
a1aa1a8
fix: Don't pass bot to __init__
ToxicKidz May 3, 2021
fa45ba7
fix: Resolve Merge Conflicts
ToxicKidz May 3, 2021
5838d29
chore: Clean Up the Valentines Season
ToxicKidz May 3, 2021
e9f3330
Clean Up the Easter Season
ToxicKidz May 3, 2021
5189259
chore: End the sentence with a period
ToxicKidz May 3, 2021
a7279c6
chore: Don't return a Message object when the return annotation is None
ToxicKidz May 3, 2021
8769624
chore: Don't make content an empty string
ToxicKidz May 4, 2021
a6cc40f
chore: Prefer double quotes over single quotes
ToxicKidz May 4, 2021
47a6625
Merge branch 'spring-cleanup' of https://github.com/ToxicKidz/sir-lan…
ToxicKidz May 4, 2021
c051abf
chore: Apply suggested changes
ToxicKidz May 4, 2021
dd20f59
Apply suggested changes to hanukkah_embed.py
ToxicKidz May 4, 2021
6d31315
fix: Pass bot only when __init__ is defined
ToxicKidz May 4, 2021
d73eaf3
chore: Change back to the original string
ToxicKidz May 4, 2021
f7c9fec
chore: Replace the remaining double quotes with double quotes
ToxicKidz May 4, 2021
6ae7606
chore: Don't have defaults for typing.Optional[...] in commands
ToxicKidz May 5, 2021
7a18b36
chore: Don't use "is not None"
ToxicKidz May 5, 2021
888f831
chore: Add all of the converters into bot/utils/converters.py
ToxicKidz May 5, 2021
0b0bd37
Merge branch 'spring-cleanup' of https://github.com/ToxicKidz/sir-lan…
ToxicKidz May 5, 2021
780aaeb
chore: Apply anand's suggested changes
ToxicKidz May 5, 2021
353264e
chore: Improve .space epic's docstring
ToxicKidz May 5, 2021
19e2efa
chore: Apply suggested changes
ToxicKidz May 5, 2021
e22c033
chore: Use pathlib more often and apply other changes
ToxicKidz May 5, 2021
b486ed4
chore: Remove useless call of `dict.keys()`
ToxicKidz May 5, 2021
49fb351
Merge branch 'spring-cleanup' of https://github.com/ToxicKidz/sir-lan…
ToxicKidz May 5, 2021
a1307cc
fix: Resolve Merge Conflicts
ToxicKidz May 7, 2021
d5f0115
chore: Reformat the code to follow the style guild
ToxicKidz May 7, 2021
0017b76
chore: Apply anand's suggested changes
ToxicKidz May 7, 2021
ae3ecb3
chore: Simplify the if statement
ToxicKidz May 7, 2021
4503a33
fix: Use str.isdecimal instead of str.isdigit
ToxicKidz May 9, 2021
4ba9c94
chore: Apply more suggested changes
ToxicKidz May 10, 2021
52aa6dc
chore: ctx.message.author -> ctx.author
ToxicKidz May 10, 2021
b17a60a
chore: Use ctx instead of ctx.channel
ToxicKidz May 10, 2021
e15d1ec
fix: Resolve Merge Conflicts
ToxicKidz May 10, 2021
2aa1916
chore: Use pathlib.Path.read_text & write_text over open
ToxicKidz May 13, 2021
a6848fd
fix: Again, Resolve Merge Conflicts
ToxicKidz May 13, 2021
42002ea
chore: Break up the HelpSession.build_pages method
ToxicKidz May 13, 2021
92c33d6
chore: Refactor more code to follow our style guide
ToxicKidz May 14, 2021
95e3bcb
chore: Remove redundant f-strings
ToxicKidz May 15, 2021
c09ab5c
chore: Reformat bot/utils/__init__.py
ToxicKidz May 15, 2021
8dd9e9c
fix: Resolve merge conflicts again
ToxicKidz May 15, 2021
e1361d0
chore: Update myvalenstate.py
ToxicKidz May 15, 2021
55d472a
chore: Make all aliases in commands tuples
ToxicKidz May 15, 2021
28eb6d8
fix: Remove the useless return
ToxicKidz May 15, 2021
f8a179d
chore: Make things that are only used once constants
ToxicKidz May 15, 2021
aad7b47
Merge branch 'spring-cleanup' of https://github.com/ToxicKidz/sir-lan…
ToxicKidz May 15, 2021
bf999d0
chore: Apply suggested changes to hanukkah_embed.py
ToxicKidz May 15, 2021
01e2272
chore: Make more things use constants
ToxicKidz May 15, 2021
369134e
chore: Apply suggestions from code review
ToxicKidz May 15, 2021
320a1be
chore: Resolve conflicts for the last time (hopefully)
ToxicKidz May 15, 2021
8ac335a
chore: Add Iceman's suggested changes
ToxicKidz May 15, 2021
0285da6
chore: Apply Iceman's suggestions
ToxicKidz May 15, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,12 @@ def monkeypatch_trace(self: logging.Logger, msg: str, *args, **kwargs) -> None:

# Setup new logging configuration
logging.basicConfig(
format='%(asctime)s - %(name)s %(levelname)s: %(message)s',
format="%(asctime)s - %(name)s %(levelname)s: %(message)s",
datefmt="%D %H:%M:%S",
level=logging.TRACE if Client.debug else logging.DEBUG,
handlers=[console_handler, file_handler],
)
logging.getLogger().info('Logging initialization complete')
logging.getLogger().info("Logging initialization complete")


# On Windows, the selector event loop is required for aiodns.
Expand Down
2 changes: 1 addition & 1 deletion bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ async def check_channels(self) -> None:

all_channels_ids = [channel.id for channel in self.get_all_channels()]
for name, channel_id in vars(constants.Channels).items():
if name.startswith('_'):
if name.startswith("_"):
continue
if channel_id not in all_channels_ids:
log.error(f'Channel "{name}" with ID {channel_id} missing')
Expand Down
25 changes: 15 additions & 10 deletions bot/exts/christmas/advent_of_code/_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,15 @@ async def aoc_subscribe(self, ctx: commands.Context) -> None:

if role not in ctx.author.roles:
await ctx.author.add_roles(role)
await ctx.send("Okay! You have been __subscribed__ to notifications about new Advent of Code tasks. "
f"You can run `{unsubscribe_command}` to disable them again for you.")
await ctx.send(
"Okay! You have been __subscribed__ to notifications about new Advent of Code tasks. "
f"You can run `{unsubscribe_command}` to disable them again for you."
)
else:
await ctx.send("Hey, you already are receiving notifications about new Advent of Code tasks. "
f"If you don't want them any more, run `{unsubscribe_command}` instead.")
await ctx.send(
"Hey, you already are receiving notifications about new Advent of Code tasks. "
f"If you don't want them any more, run `{unsubscribe_command}` instead."
)

@in_month(Month.DECEMBER)
@adventofcode_group.command(name="unsubscribe", aliases=("unsub",), brief="Notifications for new days")
Expand Down Expand Up @@ -110,8 +114,10 @@ async def aoc_countdown(self, ctx: commands.Context) -> None:
else:
delta_str = f"{delta.days} days"

await ctx.send(f"The Advent of Code event is not currently running. "
f"The next event will start in {delta_str}.")
await ctx.send(
"The Advent of Code event is not currently running. "
f"The next event will start in {delta_str}."
)
return

tomorrow, time_left = _helpers.time_left_to_est_midnight()
Expand All @@ -124,7 +130,7 @@ async def aoc_countdown(self, ctx: commands.Context) -> None:
@whitelist_override(channels=AOC_WHITELIST)
async def about_aoc(self, ctx: commands.Context) -> None:
"""Respond with an explanation of all things Advent of Code."""
await ctx.send("", embed=self.cached_about_aoc)
await ctx.send(embed=self.cached_about_aoc)

@adventofcode_group.command(name="join", aliases=("j",), brief="Learn how to join the leaderboard (via DM)")
@whitelist_override(channels=AOC_WHITELIST)
Expand All @@ -135,7 +141,7 @@ async def join_leaderboard(self, ctx: commands.Context) -> None:
await ctx.send(f"The Python Discord leaderboard for {current_year} is not yet available!")
return

author = ctx.message.author
author = ctx.author
log.info(f"{author.name} ({author.id}) has requested a PyDis AoC leaderboard code")

if AocConfig.staff_leaderboard_id and any(r.id == Roles.helpers for r in author.roles):
Expand Down Expand Up @@ -273,8 +279,7 @@ def cog_unload(self) -> None:

def _build_about_embed(self) -> discord.Embed:
"""Build and return the informational "About AoC" embed from the resources file."""
with self.about_aoc_filepath.open("r", encoding="utf8") as f:
embed_fields = json.load(f)
embed_fields = json.loads(self.about_aoc_filepath.read_text("utf8"))

about_embed = discord.Embed(
title=self._base_url,
Expand Down
8 changes: 4 additions & 4 deletions bot/exts/christmas/advent_of_code/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict:
# star view. We need that per star view to compute rank scores per star.
for member in raw_leaderboard_data.values():
name = member["name"] if member["name"] else f"Anonymous #{member['id']}"
member_id = member['id']
member_id = member["id"]
leaderboard[member_id] = {"name": name, "score": 0, "star_1": 0, "star_2": 0}

# Iterate over all days for this participant
Expand All @@ -119,7 +119,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict:
leaderboard[member_id][f"star_{star}"] += 1

# Record completion datetime for this participant for this day/star
completion_time = datetime.datetime.fromtimestamp(int(data['get_star_ts']))
completion_time = datetime.datetime.fromtimestamp(int(data["get_star_ts"]))
star_results[(day, star)].append(
StarResult(member_id=member_id, completion_time=completion_time)
)
Expand All @@ -133,7 +133,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict:
if day in AdventOfCode.ignored_days:
continue

sorted_result = sorted(results, key=operator.attrgetter('completion_time'))
sorted_result = sorted(results, key=operator.attrgetter("completion_time"))
Comment thread
ToxicKidz marked this conversation as resolved.
for rank, star_result in enumerate(sorted_result):
leaderboard[star_result.member_id]["score"] += max_score - rank

Expand Down Expand Up @@ -307,7 +307,7 @@ async def fetch_leaderboard(invalidate_cache: bool = False) -> dict:

def get_summary_embed(leaderboard: dict) -> discord.Embed:
"""Get an embed with the current summary stats of the leaderboard."""
leaderboard_url = leaderboard['full_leaderboard_url']
leaderboard_url = leaderboard["full_leaderboard_url"]
refresh_minutes = AdventOfCode.leaderboard_cache_expiry_seconds // 60

aoc_embed = discord.Embed(
Expand Down
85 changes: 43 additions & 42 deletions bot/exts/christmas/hanukkah_embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,41 @@
from discord import Embed
from discord.ext import commands

from bot.bot import Bot
from bot.constants import Colours, Month
from bot.utils.decorators import in_month

log = logging.getLogger(__name__)

HEBCAL_URL = (
"https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&"
"year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on"
)


class HanukkahEmbed(commands.Cog):
"""A cog that returns information about Hanukkah festival."""

def __init__(self, bot: commands.Bot):
def __init__(self, bot: Bot):
self.bot = bot
self.url = ("https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&"
"year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3448439&m=50&s=on")
self.hanukkah_days = []
self.hanukkah_months = []
self.hanukkah_years = []

async def get_hanukkah_dates(self) -> List[str]:
"""Gets the dates for hanukkah festival."""
hanukkah_dates = []
async with self.bot.http_session.get(self.url) as response:
async with self.bot.http_session.get(HEBCAL_URL) as response:
json_data = await response.json()
festivals = json_data['items']
festivals = json_data["items"]
for festival in festivals:
if festival['title'].startswith('Chanukah'):
date = festival['date']
if festival["title"].startswith("Chanukah"):
date = festival["date"]
hanukkah_dates.append(date)
return hanukkah_dates

@in_month(Month.DECEMBER)
@commands.command(name='hanukkah', aliases=['chanukah'])
@commands.command(name="hanukkah", aliases=("chanukah",))
async def hanukkah_festival(self, ctx: commands.Context) -> None:
"""Tells you about the Hanukkah Festivaltime of festival, festival day, etc)."""
hanukkah_dates = await self.get_hanukkah_dates()
Expand All @@ -54,49 +58,46 @@ async def hanukkah_festival(self, ctx: commands.Context) -> None:
day = str(today.day)
month = str(today.month)
year = str(today.year)
embed = Embed()
embed.title = 'Hanukkah'
embed.colour = Colours.blue
embed = Embed(title="Hanukkah", colour=Colours.blue)
if day in self.hanukkah_days and month in self.hanukkah_months and year in self.hanukkah_years:
if int(day) == hanukkah_start_day:
now = datetime.datetime.utcnow()
now = str(now)
hours = int(now[11:13]) + 4 # using only hours
hours = now.hour + 4 # using only hours
hanukkah_start_hour = 18
if hours < hanukkah_start_hour:
embed.description = (f"Hanukkah hasnt started yet, "
f"it will start in about {hanukkah_start_hour-hours} hour/s.")
return await ctx.send(embed=embed)
embed.description = (
"Hanukkah hasnt started yet, "
f"it will start in about {hanukkah_start_hour - hours} hour/s."
)
await ctx.send(embed=embed)
return
elif hours > hanukkah_start_hour:
embed.description = (f'It is the starting day of Hanukkah ! '
f'Its been {hours-hanukkah_start_hour} hours hanukkah started !')
return await ctx.send(embed=embed)
embed.description = (
"It is the starting day of Hanukkah! "
f"Its been {hours - hanukkah_start_hour} hours hanukkah started!"
)
await ctx.send(embed=embed)
return
festival_day = self.hanukkah_days.index(day)
number_suffixes = ['st', 'nd', 'rd', 'th']
suffix = ''
if int(festival_day) == 1:
suffix = number_suffixes[0]
if int(festival_day) == 2:
suffix = number_suffixes[1]
if int(festival_day) == 3:
suffix = number_suffixes[2]
if int(festival_day) > 3:
suffix = number_suffixes[3]
message = ''
for _ in range(1, festival_day + 1):
message += ':menorah:'
embed.description = f'It is the {festival_day}{suffix} day of Hanukkah ! \n {message}'
number_suffixes = ["st", "nd", "rd", "th"]
suffix = number_suffixes[festival_day - 1 if festival_day <= 3 else 3]
message = ":menorah:" * festival_day
embed.description = f"It is the {festival_day}{suffix} day of Hanukkah!\n{message}"
await ctx.send(embed=embed)
else:
if today < hanukkah_start:
festival_starting_month = hanukkah_start.strftime('%B')
embed.description = (f"Hanukkah has not started yet. "
f"Hanukkah will start at sundown on {hanukkah_start_day}th "
f"of {festival_starting_month}.")
festival_starting_month = hanukkah_start.strftime("%B")
embed.description = (
f"Hanukkah has not started yet. "
f"Hanukkah will start at sundown on {hanukkah_start_day}th "
f"of {festival_starting_month}."
)
else:
festival_end_month = hanukkah_end.strftime('%B')
embed.description = (f"Looks like you missed Hanukkah !"
f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}.")
festival_end_month = hanukkah_end.strftime("%B")
embed.description = (
f"Looks like you missed Hanukkah!"
f"Hanukkah ended on {hanukkah_end_day}th of {festival_end_month}."
)

await ctx.send(embed=embed)

Expand All @@ -108,6 +109,6 @@ def hanukkah_dates_split(self, hanukkah_dates: List[str]) -> None:
self.hanukkah_years.append(date[0:4])


def setup(bot: commands.Bot) -> None:
"""Cog load."""
def setup(bot: Bot) -> None:
"""Load the Hanukkah Embed Cog."""
bot.add_cog(HanukkahEmbed(bot))
16 changes: 9 additions & 7 deletions bot/exts/easter/april_fools_vids.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
import logging
import random
from json import load
from json import loads
from pathlib import Path

from discord.ext import commands

from bot.bot import Bot

log = logging.getLogger(__name__)

with open("bot/resources/easter/april_fools_vids.json", encoding="utf-8") as f:
ALL_VIDS = load(f)
ALL_VIDS = loads(Path("bot/resources/easter/april_fools_vids.json").read_text("utf-8"))


class AprilFoolVideos(commands.Cog):
"""A cog for April Fools' that gets a random April Fools' video from Youtube."""

@commands.command(name='fool')
@commands.command(name="fool")
async def april_fools(self, ctx: commands.Context) -> None:
"""Get a random April Fools' video from Youtube."""
video = random.choice(ALL_VIDS)
Expand All @@ -23,6 +25,6 @@ async def april_fools(self, ctx: commands.Context) -> None:
await ctx.send(f"Check out this April Fools' video by {channel}.\n\n{url}")


def setup(bot: commands.Bot) -> None:
"""April Fools' Cog load."""
bot.add_cog(AprilFoolVideos(bot))
def setup(bot: Bot) -> None:
"""Load the April Fools' Cog."""
bot.add_cog(AprilFoolVideos())
42 changes: 22 additions & 20 deletions bot/exts/easter/bunny_name_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,26 @@

from discord.ext import commands

from bot.bot import Bot

log = logging.getLogger(__name__)

with Path("bot/resources/easter/bunny_names.json").open("r", encoding="utf8") as f:
BUNNY_NAMES = json.load(f)
BUNNY_NAMES = json.loads(Path("bot/resources/easter/bunny_names.json").read_text("utf8"))


class BunnyNameGenerator(commands.Cog):
"""Generate a random bunny name, or bunnify your Discord username!"""

def __init__(self, bot: commands.Bot):
self.bot = bot

def find_separators(self, displayname: str) -> Union[List[str], None]:
@staticmethod
def find_separators(displayname: str) -> Union[List[str], None]:
"""Check if Discord name contains spaces so we can bunnify an individual word in the name."""
new_name = re.split(r'[_.\s]', displayname)
new_name = re.split(r"[_.\s]", displayname)
if displayname not in new_name:
return new_name
return None

Comment thread
ToxicKidz marked this conversation as resolved.
def find_vowels(self, displayname: str) -> str:
@staticmethod
def find_vowels(displayname: str) -> str:
"""
Finds vowels in the user's display name.

Expand All @@ -34,21 +35,22 @@ def find_vowels(self, displayname: str) -> str:
Only the most recently matched pattern will apply the changes.
"""
expressions = [
(r'a.+y', 'patchy'),
(r'e.+y', 'ears'),
(r'i.+y', 'ditsy'),
(r'o.+y', 'oofy'),
(r'u.+y', 'uffy'),
("a.+y", "patchy"),
("e.+y", "ears"),
("i.+y", "ditsy"),
("o.+y", "oofy"),
("u.+y", "uffy"),
]

for exp, vowel_sub in expressions:
new_name = re.sub(exp, vowel_sub, displayname)
if new_name != displayname:
return new_name

def append_name(self, displayname: str) -> str:
@staticmethod
def append_name(displayname: str) -> str:
"""Adds a suffix to the end of the Discord name."""
extensions = ['foot', 'ear', 'nose', 'tail']
extensions = ["foot", "ear", "nose", "tail"]
suffix = random.choice(extensions)
appended_name = displayname + suffix

Expand All @@ -62,7 +64,7 @@ async def bunnyname(self, ctx: commands.Context) -> None:
@commands.command()
async def bunnifyme(self, ctx: commands.Context) -> None:
"""Gets your Discord username and bunnifies it."""
username = ctx.message.author.display_name
username = ctx.author.display_name

# If name contains spaces or other separators, get the individual words to randomly bunnify
spaces_in_name = self.find_separators(username)
Expand All @@ -75,7 +77,7 @@ async def bunnifyme(self, ctx: commands.Context) -> None:
unmatched_name = self.append_name(username)

if spaces_in_name is not None:
replacements = ['Cotton', 'Fluff', 'Floof' 'Bounce', 'Snuffle', 'Nibble', 'Cuddle', 'Velvetpaw', 'Carrot']
replacements = ["Cotton", "Fluff", "Floof" "Bounce", "Snuffle", "Nibble", "Cuddle", "Velvetpaw", "Carrot"]
word_to_replace = random.choice(spaces_in_name)
substitute = random.choice(replacements)
bunnified_name = username.replace(word_to_replace, substitute)
Expand All @@ -87,6 +89,6 @@ async def bunnifyme(self, ctx: commands.Context) -> None:
await ctx.send(bunnified_name)


def setup(bot: commands.Bot) -> None:
"""Bunny Name Generator Cog load."""
bot.add_cog(BunnyNameGenerator(bot))
def setup(bot: Bot) -> None:
"""Load the Bunny Name Generator Cog."""
bot.add_cog(BunnyNameGenerator())
Loading