From 9ae7f44ad08c858b7d4e0a6cb8075db135dfa08e Mon Sep 17 00:00:00 2001 From: scragly <29337040+scragly@users.noreply.github.com> Date: Sat, 1 Dec 2018 20:41:53 +1000 Subject: Cleanup Baseclass --- bot/constants.py | 1 + 1 file changed, 1 insertion(+) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 1294912a..5382d5f3 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -74,6 +74,7 @@ class Colours: class Emojis: star = "\u2B50" christmas_tree = u"\U0001F384" + check = "\u2611" class Tokens(NamedTuple): -- cgit v1.2.3 From 9b575120e64fd1cb3e2b24793712d886296008bb Mon Sep 17 00:00:00 2001 From: scragly <29337040+scragly@users.noreply.github.com> Date: Sat, 1 Dec 2018 20:44:03 +1000 Subject: Allow Admin role env setting when debugging --- bot/constants.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 5382d5f3..6db8c68f 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -51,7 +51,7 @@ class Hacktoberfest(NamedTuple): class Roles(NamedTuple): - admin = 267628507062992896 + admin = int(environ.get('SEASONALBOT_DEBUG', 267628507062992896)) announcements = 463658397560995840 champion = 430492892331769857 contributor = 295488872404484098 -- cgit v1.2.3 From b036c9aa23099a6d3eb74bb1b548277cfbdb5edd Mon Sep 17 00:00:00 2001 From: scragly <29337040+scragly@users.noreply.github.com> Date: Sat, 1 Dec 2018 22:51:47 +1000 Subject: Add season element set methods, add server icon change support --- bot/constants.py | 2 +- bot/resources/avatars/christmas.png | Bin 44843 -> 0 bytes bot/resources/avatars/spooky.png | Bin 37202 -> 0 bytes bot/resources/avatars/standard.png | Bin 52156 -> 0 bytes bot/seasons/christmas/__init__.py | 4 +- bot/seasons/halloween/__init__.py | 2 +- bot/seasons/season.py | 141 +++++++++++++++++++++++++++++------- 7 files changed, 118 insertions(+), 31 deletions(-) delete mode 100644 bot/resources/avatars/christmas.png delete mode 100644 bot/resources/avatars/spooky.png delete mode 100644 bot/resources/avatars/standard.png (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 6db8c68f..52da161e 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -51,7 +51,7 @@ class Hacktoberfest(NamedTuple): class Roles(NamedTuple): - admin = int(environ.get('SEASONALBOT_DEBUG', 267628507062992896)) + admin = int(environ.get('SEASONALBOT_ADMIN', 267628507062992896)) announcements = 463658397560995840 champion = 430492892331769857 contributor = 295488872404484098 diff --git a/bot/resources/avatars/christmas.png b/bot/resources/avatars/christmas.png deleted file mode 100644 index 55b72fac..00000000 Binary files a/bot/resources/avatars/christmas.png and /dev/null differ diff --git a/bot/resources/avatars/spooky.png b/bot/resources/avatars/spooky.png deleted file mode 100644 index 4ab33188..00000000 Binary files a/bot/resources/avatars/spooky.png and /dev/null differ diff --git a/bot/resources/avatars/standard.png b/bot/resources/avatars/standard.png deleted file mode 100644 index c14ff42a..00000000 Binary files a/bot/resources/avatars/standard.png and /dev/null differ diff --git a/bot/seasons/christmas/__init__.py b/bot/seasons/christmas/__init__.py index 8eb78251..796dd895 100644 --- a/bot/seasons/christmas/__init__.py +++ b/bot/seasons/christmas/__init__.py @@ -5,5 +5,5 @@ class Christmas(SeasonBase): name = "christmas" start_date = "01/12" end_date = "31/12" - bot_name = "Santabot" - bot_avatar = "christmas.png" + bot_name = "Merrybot" + icon = "/logos/logo_seasonal/christmas/festive.png" diff --git a/bot/seasons/halloween/__init__.py b/bot/seasons/halloween/__init__.py index 4dd195fb..1f776c03 100644 --- a/bot/seasons/halloween/__init__.py +++ b/bot/seasons/halloween/__init__.py @@ -6,4 +6,4 @@ class Halloween(SeasonBase): start_date = "01/10" end_date = "31/10" bot_name = "Spookybot" - bot_avatar = "spooky.png" + icon = "/logos/logo_seasonal/halloween/spooky.png" diff --git a/bot/seasons/season.py b/bot/seasons/season.py index a86330e9..95367fd2 100644 --- a/bot/seasons/season.py +++ b/bot/seasons/season.py @@ -74,7 +74,7 @@ class SeasonBase: start_date = None end_date = None bot_name: str = "SeasonalBot" - bot_avatar: str = "standard.png" + icon: str = "/logos/logo_full/logo_full.png" @staticmethod def current_year(): @@ -96,39 +96,101 @@ class SeasonBase: def is_between_dates(cls, date): return cls.start() <= date <= cls.end() - def get_avatar(self): - avatar_path = Path("bot", "resources", "avatars", self.bot_avatar) - with open(avatar_path, "rb") as avatar_file: - return bytearray(avatar_file.read()) + async def get_icon(self): + base_url = "https://raw.githubusercontent.com/python-discord/branding/master" + async with bot.http_session.get(base_url + self.icon) as resp: + avatar = await resp.read() + return bytearray(avatar) - async def load(self): + async def apply_username(self, *, debug: bool = False): """ - Loads in the bot name, the bot avatar, and the extensions that are relevant to that season. + Applies the username for the current season. Returns if it was successful. """ guild = bot.get_guild(Client.guild) + result = None # Change only nickname if in debug mode due to ratelimits for user edits - if Client.debug: + if debug: if guild.me.display_name != self.bot_name: log.debug(f"Changing nickname to {self.bot_name}") await guild.me.edit(nick=self.bot_name) + else: if bot.user.name != self.bot_name: # attempt to change user details log.debug(f"Changing username to {self.bot_name}") - await bot.user.edit(username=self.bot_name, avatar=self.get_avatar()) + await bot.user.edit(username=self.bot_name) # fallback on nickname if failed due to ratelimit if bot.user.name != self.bot_name: - log.info(f"User details failed to change: Changing nickname to {self.bot_name}") + log.info(f"Username failed to change: Changing nickname to {self.bot_name}") await guild.me.edit(nick=self.bot_name) + result = False + else: + result = True # remove nickname if an old one exists if guild.me.nick and guild.me.nick != self.bot_name: log.debug(f"Clearing old nickname of {guild.me.nick}") await guild.me.edit(nick=None) + return result + + async def apply_avatar(self): + """ + Applies the avatar for the current season. Returns if it was successful. + """ + + # track old avatar hash for later comparison + old_avatar = bot.user.avatar + + # attempt the change + log.debug(f"Changing avatar to {self.icon}") + avatar = await self.get_icon() + await bot.user.edit(avatar=avatar) + + if bot.user.avatar != old_avatar: + log.debug(f"Avatar changed to {self.icon}") + return True + else: + log.debug(f"Changing avatar failed: {self.icon}") + return False + + async def apply_server_icon(self): + """ + Applies the server icon for the current season. Returns if it was successful. + """ + + guild = bot.get_guild(Client.guild) + + # track old icon hash for later comparison + old_icon = guild.icon + + # attempt the change + log.debug(f"Changing server icon to {self.icon}") + avatar = await self.get_icon() + await guild.edit(icon=avatar, reason=f"Seasonbot Season Change: {self.__name__}") + + new_icon = bot.get_guild(Client.guild).icon + if new_icon != old_icon: + log.debug(f"Server icon changed to {self.icon}") + return True + else: + log.debug(f"Changing server icon failed: {self.icon}") + return False + + async def load(self): + """ + Loads in the bot name, the bot avatar, and the extensions that are relevant to that season. + """ + + await self.apply_username(debug=Client.debug) + await self.apply_avatar() + + if not Client.debug: + await self.apply_server_icon() + # Prepare all the seasonal cogs, and then the evergreen ones. extensions = [] for ext_folder in {self.name, "evergreen"}: @@ -248,62 +310,87 @@ class SeasonManager: Re-applies the bot avatar for the currently loaded season. """ - # track old avatar hash for later comparison - old_avatar = bot.user.avatar - # attempt the change - await bot.user.edit(avatar=self.season.get_avatar()) + is_changed = await self.season.apply_avatar() - if bot.user.avatar != old_avatar: - log.debug(f"Avatar changed to {self.season.bot_avatar}") + if is_changed: colour = ctx.guild.me.colour title = "Avatar Refreshed" else: - log.debug(f"Changing avatar failed: {self.season.bot_avatar}") colour = discord.Colour.red() title = "Avatar Failed to Refresh" # report back details season_name = type(self.season).__name__ embed = discord.Embed( - description=f"**Season:** {season_name}\n**Avatar:** {self.season.bot_avatar}", + description=f"**Season:** {season_name}\n**Avatar:** {self.season.icon}", colour=colour ) embed.set_author(name=title) embed.set_thumbnail(url=bot.user.avatar_url_as(format="png")) await ctx.send(embed=embed) + @refresh.command(name="icon") + async def refresh_server_icon(self, ctx): + """ + Re-applies the server icon for the currently loaded season. + """ + + # attempt the change + is_changed = await self.season.apply_server_icon() + + if is_changed: + colour = ctx.guild.me.colour + title = "Server Icon Refreshed" + else: + colour = discord.Colour.red() + title = "Server Icon Failed to Refresh" + + # report back details + season_name = type(self.season).__name__ + embed = discord.Embed( + description=f"**Season:** {season_name}\n**Icon:** {self.season.icon}", + colour=colour + ) + embed.set_author(name=title) + embed.set_thumbnail(url=bot.get_guild(Client.guild).icon_url_as(format='png')) + await ctx.send(embed=embed) + @refresh.command(name="username", aliases=("name",)) async def refresh_username(self, ctx): """ Re-applies the bot username for the currently loaded season. """ - # track old username for later comparison old_username = str(bot.user) + old_display_name = ctx.guild.me.display_name # attempt the change - await bot.user.edit(username=self.season.bot_name) + is_changed = await self.season.apply_username() - if str(bot.user) != old_username: - log.debug(f"Username changed to {self.season.bot_name}") + if is_changed: colour = ctx.guild.me.colour title = "Username Refreshed" changed_element = "Username" + old_name = old_username new_name = str(bot.user) else: - log.debug(f"Changing username failed: Changing nickname to {self.season.bot_name}") - new_name = self.season.bot_name - await ctx.guild.me.edit(nick=new_name) colour = discord.Colour.red() - title = "Username Failed to Refresh" + + # if None, it's because it wasn't meant to change username + if is_changed is None: + title = "Nickname Refreshed" + else: + title = "Username Failed to Refresh" changed_element = "Nickname" + old_name = old_display_name + new_name = self.season.bot_name # report back details season_name = type(self.season).__name__ embed = discord.Embed( description=f"**Season:** {season_name}\n" - f"**Old Username:** {old_username}\n" + f"**Old {changed_element}:** {old_name}\n" f"**New {changed_element}:** {new_name}", colour=colour ) -- cgit v1.2.3 From 08e63544f25a77a6a024c436daa86f997b85f6f9 Mon Sep 17 00:00:00 2001 From: scragly <29337040+scragly@users.noreply.github.com> Date: Sun, 2 Dec 2018 03:21:27 +1000 Subject: Add season announcement support --- bot/constants.py | 4 +- bot/seasons/christmas/__init__.py | 9 ++++ bot/seasons/christmas/adventofcode.py | 5 +- bot/seasons/halloween/__init__.py | 1 + bot/seasons/season.py | 95 +++++++++++++++++++++++++++++------ 5 files changed, 97 insertions(+), 17 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 52da161e..02bc5a38 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -4,14 +4,14 @@ from typing import NamedTuple from bot.bot import SeasonalBot -__all__ = ('Client', 'Roles', 'bot') +__all__ = ("Channels", "Client", "Roles", "bot") log = logging.getLogger(__name__) class Channels(NamedTuple): admins = 365960823622991872 - announcements = 354619224620138496 + announcements = int(environ.get('CHANNEL_ANNOUNCEMENTS', 354619224620138496)) big_brother_logs = 468507907357409333 bot = 267659945086812160 checkpoint_test = 422077681434099723 diff --git a/bot/seasons/christmas/__init__.py b/bot/seasons/christmas/__init__.py index 796dd895..d0702100 100644 --- a/bot/seasons/christmas/__init__.py +++ b/bot/seasons/christmas/__init__.py @@ -2,7 +2,16 @@ from bot.seasons import SeasonBase class Christmas(SeasonBase): + """ + We are getting into the festive spirit with a new server icon, new + bot name and avatar, and some new commands for you to check out! + + No matter who you are, where you are or what beliefs you may follow, + we hope every one of you enjoy this festive season! + """ name = "christmas" + greeting = "Happy Holidays!" + colour = 0x1f8b4c start_date = "01/12" end_date = "31/12" bot_name = "Merrybot" diff --git a/bot/seasons/christmas/adventofcode.py b/bot/seasons/christmas/adventofcode.py index 4c766703..5a34d608 100644 --- a/bot/seasons/christmas/adventofcode.py +++ b/bot/seasons/christmas/adventofcode.py @@ -100,6 +100,9 @@ async def day_countdown(bot: commands.Bot): class AdventOfCode: + """ + Advent of Code festivities! Ho Ho Ho! + """ def __init__(self, bot: commands.Bot): self.bot = bot @@ -125,7 +128,7 @@ class AdventOfCode: @commands.group(name="adventofcode", aliases=("aoc",), invoke_without_command=True) async def adventofcode_group(self, ctx: commands.Context): """ - Advent of Code festivities! Ho Ho Ho! + All of the Advent of Code commands """ await ctx.invoke(self.bot.get_command("help"), "adventofcode") diff --git a/bot/seasons/halloween/__init__.py b/bot/seasons/halloween/__init__.py index 1f776c03..53920689 100644 --- a/bot/seasons/halloween/__init__.py +++ b/bot/seasons/halloween/__init__.py @@ -3,6 +3,7 @@ from bot.seasons import SeasonBase class Halloween(SeasonBase): name = "halloween" + greeting = "Happy Halloween!" start_date = "01/10" end_date = "31/10" bot_name = "Spookybot" diff --git a/bot/seasons/season.py b/bot/seasons/season.py index 95367fd2..c971284f 100644 --- a/bot/seasons/season.py +++ b/bot/seasons/season.py @@ -1,14 +1,16 @@ import asyncio import datetime import importlib +import inspect import logging import pkgutil +import typing from pathlib import Path import discord from discord.ext import commands -from bot.constants import Client, Roles, bot +from bot.constants import Channels, Client, Roles, bot from bot.decorators import with_role log = logging.getLogger(__name__) @@ -69,10 +71,11 @@ def get_season(season_name: str = None, date: datetime.datetime = None): class SeasonBase: - name = None + name: typing.Optional[str] = "evergreen" + start_date: typing.Optional[str] = None + end_date: typing.Optional[str] = None + colour: typing.Optional[int] = None date_format = "%d/%m/%Y" - start_date = None - end_date = None bot_name: str = "SeasonalBot" icon: str = "/logos/logo_full/logo_full.png" @@ -96,6 +99,11 @@ class SeasonBase: def is_between_dates(cls, date): return cls.start() <= date <= cls.end() + @property + def greeting(self): + season_name = " ".join(self.name.split("_")).title() + return f"New Season, {season_name}!" + async def get_icon(self): base_url = "https://raw.githubusercontent.com/python-discord/branding/master" async with bot.http_session.get(base_url + self.icon) as resp: @@ -180,17 +188,58 @@ class SeasonBase: log.debug(f"Changing server icon failed: {self.icon}") return False + async def announce_season(self): + # don't actually announce if reverting to normal season + if self.name == "evergreen": + log.debug(f"Season Changed: {self.icon}") + return + + guild = bot.get_guild(Client.guild) + + channel = guild.get_channel(Channels.announcements) + mention = f"<@&{Roles.announcements}>" + + # collect seasonal cogs + cogs = [] + for cog in bot.cogs.values(): + if "evergreen" in cog.__module__: + continue + cog_name = type(cog).__name__ + if cog_name != "SeasonManager": + cogs.append(cog_name) + + # no cogs, so no seasonal commands + if not cogs: + return + + # build cog info output + doc = inspect.getdoc(self) + announce_text = doc + "\n\n" if doc else "" + + def cog_name(cog): + return type(cog).__name__ + + cog_info = [] + for cog in sorted(cogs, key=cog_name): + doc = inspect.getdoc(bot.get_cog(cog)) + if doc: + cog_info.append(f"**{cog}**\n*{doc}*") + else: + cog_info.append(f"**{cog}**") + + embed = discord.Embed(description=announce_text, colour=self.colour or guild.me.colour) + embed.set_author(name=self.greeting) + cogs_text = "\n".join(cog_info) + embed.add_field(name="New Command Categories", value=cogs_text) + embed.set_footer(text="To see the new commands, use .help Category") + + await channel.send(mention, embed=embed) + async def load(self): """ - Loads in the bot name, the bot avatar, and the extensions that are relevant to that season. + Loads extensions, bot name and avatar, server icon and announces new season. """ - await self.apply_username(debug=Client.debug) - await self.apply_avatar() - - if not Client.debug: - await self.apply_server_icon() - # Prepare all the seasonal cogs, and then the evergreen ones. extensions = [] for ext_folder in {self.name, "evergreen"}: @@ -203,6 +252,15 @@ class SeasonBase: # Finally we can load all the cogs we've prepared. bot.load_extensions(extensions) + # Apply seasonal elements after extensions successfully load + await self.apply_username(debug=Client.debug) + + # Avoid heavy API ratelimited elements when debugging + if not Client.debug: + await self.apply_avatar() + await self.apply_server_icon() + await self.announce_season() + class SeasonManager: """ @@ -240,7 +298,7 @@ class SeasonManager: await self.season.load() @with_role(Roles.moderator, Roles.admin, Roles.owner) - @commands.command(name='season') + @commands.command(name="season") async def change_season(self, ctx, new_season: str): """ Changes the currently active season on the bot. @@ -263,6 +321,8 @@ class SeasonManager: current_season = self.season.name + forced_space = "\u200b " + entries = [] seasons = [get_season_class(s) for s in get_seasons()] for season in sorted(seasons, key=season_key): @@ -285,7 +345,6 @@ class SeasonManager: is_active = current_season == season.name sdec = "__" if is_active else "" - forced_space = "\u200b " entries.append( f"**{sdec}{season.__name__}:{sdec}**\n" f"{forced_space*3}{pdec}{period}{pdec}" @@ -353,7 +412,7 @@ class SeasonManager: colour=colour ) embed.set_author(name=title) - embed.set_thumbnail(url=bot.get_guild(Client.guild).icon_url_as(format='png')) + embed.set_thumbnail(url=bot.get_guild(Client.guild).icon_url_as(format="png")) await ctx.send(embed=embed) @refresh.command(name="username", aliases=("name",)) @@ -397,5 +456,13 @@ class SeasonManager: embed.set_author(name=title) await ctx.send(embed=embed) + @with_role(Roles.moderator, Roles.admin, Roles.owner) + @commands.command() + async def announce(self, ctx): + """ + Announces the currently loaded season. + """ + await self.season.announce_season() + def __unload(self): self.season_task.cancel() -- cgit v1.2.3 From ec9372f1f35c7daba01b350b3425cec74cd2a4a8 Mon Sep 17 00:00:00 2001 From: Scragly <29337040+scragly@users.noreply.github.com> Date: Mon, 3 Dec 2018 09:36:34 +1000 Subject: Handle edit errors, tidy model and docs --- bot/constants.py | 49 ++++++------ bot/seasons/christmas/__init__.py | 7 +- bot/seasons/halloween/__init__.py | 6 +- bot/seasons/season.py | 162 ++++++++++++++++++++++++++++---------- 4 files changed, 159 insertions(+), 65 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 02bc5a38..eff4897b 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -4,11 +4,24 @@ from typing import NamedTuple from bot.bot import SeasonalBot -__all__ = ("Channels", "Client", "Roles", "bot") +__all__ = ( + "AdventOfCode", "Channels", "Client", "Colours", "Emojis", "Hacktoberfest", "Roles", + "Tokens", "bot" +) log = logging.getLogger(__name__) +class AdventOfCode: + leaderboard_cache_age_threshold_seconds = 3600 + leaderboard_id = 363275 + leaderboard_join_code = "363275-442b6939" + leaderboard_max_displayed_members = 10 + year = 2018 + channel_id = int(environ.get("AOC_CHANNEL_ID", 517745814039166986)) + role_id = int(environ.get("AOC_ROLE_ID", 518565788744024082)) + + class Channels(NamedTuple): admins = 365960823622991872 announcements = int(environ.get('CHANNEL_ANNOUNCEMENTS', 354619224620138496)) @@ -45,6 +58,19 @@ class Client(NamedTuple): season_override = environ.get('SEASON_OVERRIDE') +class Colours: + soft_red = 0xcd6d6d + soft_green = 0x68c290 + dark_green = 0x1f8b4c + orange = 0xe67e22 + + +class Emojis: + star = "\u2B50" + christmas_tree = u"\U0001F384" + check = "\u2611" + + class Hacktoberfest(NamedTuple): channel_id = 498804484324196362 voice_id = 514420006474219521 @@ -66,30 +92,9 @@ class Roles(NamedTuple): rockstars = 458226413825294336 -class Colours: - soft_red = 0xcd6d6d - soft_green = 0x68c290 - - -class Emojis: - star = "\u2B50" - christmas_tree = u"\U0001F384" - check = "\u2611" - - class Tokens(NamedTuple): giphy = environ.get("GIPHY_TOKEN") aoc_session_cookie = environ.get("AOC_SESSION_COOKIE") -class AdventOfCode: - leaderboard_cache_age_threshold_seconds = 3600 - leaderboard_id = 363275 - leaderboard_join_code = "363275-442b6939" - leaderboard_max_displayed_members = 10 - year = 2018 - channel_id = int(environ.get("AOC_CHANNEL_ID", 517745814039166986)) - role_id = int(environ.get("AOC_ROLE_ID", 518565788744024082)) - - bot = SeasonalBot(command_prefix=Client.prefix) diff --git a/bot/seasons/christmas/__init__.py b/bot/seasons/christmas/__init__.py index d0702100..99d81b0c 100644 --- a/bot/seasons/christmas/__init__.py +++ b/bot/seasons/christmas/__init__.py @@ -1,3 +1,4 @@ +from bot.constants import Colours from bot.seasons import SeasonBase @@ -10,9 +11,11 @@ class Christmas(SeasonBase): we hope every one of you enjoy this festive season! """ name = "christmas" + bot_name = "Merrybot" greeting = "Happy Holidays!" - colour = 0x1f8b4c + start_date = "01/12" end_date = "31/12" - bot_name = "Merrybot" + + colour = Colours.dark_green icon = "/logos/logo_seasonal/christmas/festive.png" diff --git a/bot/seasons/halloween/__init__.py b/bot/seasons/halloween/__init__.py index 53920689..4b371f14 100644 --- a/bot/seasons/halloween/__init__.py +++ b/bot/seasons/halloween/__init__.py @@ -1,10 +1,14 @@ +from bot.constants import Colours from bot.seasons import SeasonBase class Halloween(SeasonBase): name = "halloween" + bot_name = "Spookybot" greeting = "Happy Halloween!" + start_date = "01/10" end_date = "31/10" - bot_name = "Spookybot" + + colour = Colours.orange icon = "/logos/logo_seasonal/halloween/spooky.png" diff --git a/bot/seasons/season.py b/bot/seasons/season.py index c971284f..66c90451 100644 --- a/bot/seasons/season.py +++ b/bot/seasons/season.py @@ -4,9 +4,10 @@ import importlib import inspect import logging import pkgutil -import typing from pathlib import Path +from typing import List, Optional, Type, Union +import async_timeout import discord from discord.ext import commands @@ -16,25 +17,29 @@ from bot.decorators import with_role log = logging.getLogger(__name__) -def get_seasons(): +def get_seasons() -> List[str]: """ Returns all the Season objects located in bot/seasons/ """ + seasons = [] for module in pkgutil.iter_modules([Path("bot", "seasons")]): if module.ispkg: seasons.append(module.name) - return seasons -def get_season_class(season_name): +def get_season_class(season_name: str) -> Type["SeasonBase"]: + """ + Get's the season class of the season module. + """ + season_lib = importlib.import_module(f"bot.seasons.{season_name}") return getattr(season_lib, season_name.capitalize()) -def get_season(season_name: str = None, date: datetime.datetime = None): +def get_season(season_name: str = None, date: datetime.datetime = None) -> "SeasonBase": """ Returns a Season object based on either a string or a date. """ @@ -71,48 +76,100 @@ def get_season(season_name: str = None, date: datetime.datetime = None): class SeasonBase: - name: typing.Optional[str] = "evergreen" - start_date: typing.Optional[str] = None - end_date: typing.Optional[str] = None - colour: typing.Optional[int] = None - date_format = "%d/%m/%Y" + """ + Base class for Seasonal classes. + """ + + name: Optional[str] = "evergreen" bot_name: str = "SeasonalBot" + + start_date: Optional[str] = None + end_date: Optional[str] = None + + colour: Optional[int] = None icon: str = "/logos/logo_full/logo_full.png" + date_format: str = "%d/%m/%Y" + @staticmethod - def current_year(): + def current_year() -> int: + """ + Returns the current year. + """ + return datetime.date.today().year @classmethod - def start(cls): + def start(cls) -> datetime.datetime: + """ + Returns the start date using current year and start_date attribute. + + If no start_date was defined, returns the minimum datetime to ensure + it's always below checked dates. + """ + if not cls.start_date: return datetime.datetime.min return datetime.datetime.strptime(f"{cls.start_date}/{cls.current_year()}", cls.date_format) @classmethod - def end(cls): + def end(cls) -> datetime.datetime: + """ + Returns the start date using current year and end_date attribute. + + If no end_date was defined, returns the minimum datetime to ensure + it's always above checked dates. + """ + if not cls.end_date: return datetime.datetime.max return datetime.datetime.strptime(f"{cls.end_date}/{cls.current_year()}", cls.date_format) @classmethod - def is_between_dates(cls, date): + def is_between_dates(cls, date: datetime.datetime) -> bool: + """ + Determines if the given date falls between the season's date range. + """ + return cls.start() <= date <= cls.end() @property - def greeting(self): + def greeting(self) -> str: + """ + Provides a default greeting based on the season name if one wasn't + defined in the season class. + + It's recommended to define one in most cases by overwriting this as a + normal attribute in the inhertiting class. + """ + season_name = " ".join(self.name.split("_")).title() return f"New Season, {season_name}!" - async def get_icon(self): + async def get_icon(self) -> bytes: + """ + Retrieves the icon image from the branding repository, using the + defined icon attribute for the season. + + The icon attribute must provide the url path, starting from the master + branch base url, including the starting slash: + `https://raw.githubusercontent.com/python-discord/branding/master` + """ + base_url = "https://raw.githubusercontent.com/python-discord/branding/master" - async with bot.http_session.get(base_url + self.icon) as resp: - avatar = await resp.read() - return bytearray(avatar) + full_url = base_url + self.icon + log.debug(f"Getting icon from: {full_url}") + async with bot.http_session.get(full_url) as resp: + return await resp.read() - async def apply_username(self, *, debug: bool = False): + async def apply_username(self, *, debug: bool = False) -> Union[bool, None]: """ - Applies the username for the current season. Returns if it was successful. + Applies the username for the current season. Only changes nickname if + `bool` is False, otherwise only changes the nickname. + + Returns True if it successfully changed the username. + Returns False if it failed to change the username, falling back to nick. + Returns None if `debug` was True and username change wasn't attempted. """ guild = bot.get_guild(Client.guild) @@ -128,11 +185,14 @@ class SeasonBase: if bot.user.name != self.bot_name: # attempt to change user details log.debug(f"Changing username to {self.bot_name}") - await bot.user.edit(username=self.bot_name) + try: + await bot.user.edit(username=self.bot_name) + except discord.HTTPException: + pass # fallback on nickname if failed due to ratelimit if bot.user.name != self.bot_name: - log.info(f"Username failed to change: Changing nickname to {self.bot_name}") + log.warning(f"Username failed to change: Changing nickname to {self.bot_name}") await guild.me.edit(nick=self.bot_name) result = False else: @@ -145,7 +205,7 @@ class SeasonBase: return result - async def apply_avatar(self): + async def apply_avatar(self) -> bool: """ Applies the avatar for the current season. Returns if it was successful. """ @@ -155,17 +215,21 @@ class SeasonBase: # attempt the change log.debug(f"Changing avatar to {self.icon}") - avatar = await self.get_icon() - await bot.user.edit(avatar=avatar) + icon = await self.get_icon() + try: + async with async_timeout.timeout(5): + await bot.user.edit(avatar=icon) + except (discord.HTTPException, asyncio.TimeoutError): + pass if bot.user.avatar != old_avatar: log.debug(f"Avatar changed to {self.icon}") return True - else: - log.debug(f"Changing avatar failed: {self.icon}") - return False - async def apply_server_icon(self): + log.warning(f"Changing avatar failed: {self.icon}") + return False + + async def apply_server_icon(self) -> bool: """ Applies the server icon for the current season. Returns if it was successful. """ @@ -177,25 +241,35 @@ class SeasonBase: # attempt the change log.debug(f"Changing server icon to {self.icon}") - avatar = await self.get_icon() - await guild.edit(icon=avatar, reason=f"Seasonbot Season Change: {self.__name__}") + icon = await self.get_icon() + try: + async with async_timeout.timeout(5): + await guild.edit(icon=icon, reason=f"Seasonbot Season Change: {self.name}") + except (discord.HTTPException, asyncio.TimeoutError): + pass new_icon = bot.get_guild(Client.guild).icon if new_icon != old_icon: log.debug(f"Server icon changed to {self.icon}") return True - else: - log.debug(f"Changing server icon failed: {self.icon}") - return False + + log.warning(f"Changing server icon failed: {self.icon}") + return False async def announce_season(self): + """ + Announces a change in season in the announcement channel. + + It will skip the announcement if the current active season is the + "evergreen" default season. + """ + # don't actually announce if reverting to normal season if self.name == "evergreen": - log.debug(f"Season Changed: {self.icon}") + log.debug(f"Season Changed: {self.name}") return guild = bot.get_guild(Client.guild) - channel = guild.get_channel(Channels.announcements) mention = f"<@&{Roles.announcements}>" @@ -238,6 +312,8 @@ class SeasonBase: async def load(self): """ Loads extensions, bot name and avatar, server icon and announces new season. + + If in debug mode, the avatar, server icon, and announcement will be skipped. """ # Prepare all the seasonal cogs, and then the evergreen ones. @@ -253,13 +329,19 @@ class SeasonBase: bot.load_extensions(extensions) # Apply seasonal elements after extensions successfully load - await self.apply_username(debug=Client.debug) + username_changed = await self.apply_username(debug=Client.debug) # Avoid heavy API ratelimited elements when debugging if not Client.debug: + log.info("Applying avatar.") await self.apply_avatar() + log.info("Applying server icon.") await self.apply_server_icon() - await self.announce_season() + if username_changed: + log.info(f"Announcing season {self.name}.") + await self.announce_season() + else: + log.info(f"Skipping season announcement due to username not being changed.") class SeasonManager: @@ -347,7 +429,7 @@ class SeasonManager: entries.append( f"**{sdec}{season.__name__}:{sdec}**\n" - f"{forced_space*3}{pdec}{period}{pdec}" + f"{forced_space*3}{pdec}{period}{pdec}\n" ) embed = discord.Embed(description="\n".join(entries), colour=ctx.guild.me.colour) -- cgit v1.2.3 From 8b439030c6123591924eaa7e61c48285f6549496 Mon Sep 17 00:00:00 2001 From: Scragly <29337040+scragly@users.noreply.github.com> Date: Tue, 4 Dec 2018 07:18:39 +1000 Subject: Use contextlib.suppress, remove unnecessary `u` prefix. --- bot/constants.py | 4 ++-- bot/seasons/season.py | 13 ++++--------- 2 files changed, 6 insertions(+), 11 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index eff4897b..71bdbf5f 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -67,7 +67,7 @@ class Colours: class Emojis: star = "\u2B50" - christmas_tree = u"\U0001F384" + christmas_tree = "\U0001F384" check = "\u2611" @@ -77,7 +77,7 @@ class Hacktoberfest(NamedTuple): class Roles(NamedTuple): - admin = int(environ.get('SEASONALBOT_ADMIN', 267628507062992896)) + admin = int(environ.get('SEASONALBOT_ADMIN_ROLE_ID', 267628507062992896)) announcements = 463658397560995840 champion = 430492892331769857 contributor = 295488872404484098 diff --git a/bot/seasons/season.py b/bot/seasons/season.py index 66c90451..f1d570e0 100644 --- a/bot/seasons/season.py +++ b/bot/seasons/season.py @@ -1,4 +1,5 @@ import asyncio +import contextlib import datetime import importlib import inspect @@ -185,10 +186,8 @@ class SeasonBase: if bot.user.name != self.bot_name: # attempt to change user details log.debug(f"Changing username to {self.bot_name}") - try: + with contextlib.suppress(discord.HTTPException): await bot.user.edit(username=self.bot_name) - except discord.HTTPException: - pass # fallback on nickname if failed due to ratelimit if bot.user.name != self.bot_name: @@ -216,11 +215,9 @@ class SeasonBase: # attempt the change log.debug(f"Changing avatar to {self.icon}") icon = await self.get_icon() - try: + with contextlib.suppress(discord.HTTPException, asyncio.TimeoutError): async with async_timeout.timeout(5): await bot.user.edit(avatar=icon) - except (discord.HTTPException, asyncio.TimeoutError): - pass if bot.user.avatar != old_avatar: log.debug(f"Avatar changed to {self.icon}") @@ -242,11 +239,9 @@ class SeasonBase: # attempt the change log.debug(f"Changing server icon to {self.icon}") icon = await self.get_icon() - try: + with contextlib.suppress(discord.HTTPException, asyncio.TimeoutError): async with async_timeout.timeout(5): await guild.edit(icon=icon, reason=f"Seasonbot Season Change: {self.name}") - except (discord.HTTPException, asyncio.TimeoutError): - pass new_icon = bot.get_guild(Client.guild).icon if new_icon != old_icon: -- cgit v1.2.3