From 17b4703748d6e0b8f92e8679b7b6799c20097d11 Mon Sep 17 00:00:00 2001 From: Will Da Silva Date: Mon, 5 Oct 2020 14:14:01 -0400 Subject: Replace OMDB with TMDB Closes: #136 --- bot/constants.py | 1 - 1 file changed, 1 deletion(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index e113428e..d2e10ae1 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -184,7 +184,6 @@ class Roles(NamedTuple): class Tokens(NamedTuple): giphy = environ.get("GIPHY_TOKEN") aoc_session_cookie = environ.get("AOC_SESSION_COOKIE") - omdb = environ.get("OMDB_API_KEY") youtube = environ.get("YOUTUBE_API_KEY") tmdb = environ.get("TMDB_API_KEY") nasa = environ.get("NASA_API_KEY") -- cgit v1.2.3 From 3c02761087e98cede89f330470002248e03d0d0b Mon Sep 17 00:00:00 2001 From: Daniel Brown Date: Mon, 12 Oct 2020 13:42:22 -0500 Subject: Adding #voice_chat to the Seasonal Bot white list Since SeasonalBot is able to be used in the off-topic channels, it makes to have it work in the voice_chat channel as well. --- bot/constants.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index e113428e..1909cb86 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -75,6 +75,7 @@ class Channels(NamedTuple): show_your_projects = int(environ.get("CHANNEL_SHOW_YOUR_PROJECTS", 303934982764625920)) show_your_projects_discussion = 360148304664723466 hacktoberfest_2020 = 760857070781071431 + voice_chat = 412357430186344448 class Client(NamedTuple): @@ -209,6 +210,7 @@ WHITELISTED_CHANNELS = ( Channels.off_topic_0, Channels.off_topic_1, Channels.off_topic_2, + Channels.voice_chat, ) # Bot replies -- cgit v1.2.3 From 42316a7a57de91a04fdd1edf145cfb81294aafb7 Mon Sep 17 00:00:00 2001 From: Daniel Brown Date: Thu, 15 Oct 2020 09:47:18 -0500 Subject: Added Core Dev Sprint to whitelist For the sake of entertainment of the Core Devs, I have added the SeasonalBot functionality to the Core Dev Sprint channels. --- bot/constants.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 1909cb86..2466da02 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -76,6 +76,23 @@ class Channels(NamedTuple): show_your_projects_discussion = 360148304664723466 hacktoberfest_2020 = 760857070781071431 voice_chat = 412357430186344448 + + # Core Dev Sprint channels + announcements = 755958119963557958 + information = 753338352136224798 + organisers = 753340132639375420 + general = 753340631538991305 + social1_cheese_shop = 758779754789863514 + social2_pet_shop = 758780951978573824 + escape_room = 761031075942105109 + stdlib = 758553316732698634 + asyncio = 762904152438472714 + typing = 762904690341838888 + discussion_capi = 758553358587527218 + discussion_triage = 758553458365300746 + discussion_design = 758553492662255616 + discussion_mentor = 758553536623280159 + documentation = 761038271127093278 class Client(NamedTuple): @@ -211,6 +228,23 @@ WHITELISTED_CHANNELS = ( Channels.off_topic_1, Channels.off_topic_2, Channels.voice_chat, + + # Core Dev Sprint Channels + Channels.announcements, + Channels.information, + Channels.organisers, + Channels.general, + Channels.social1_cheese_shop, + Channels.social2_pet_shop, + Channels.escape_room, + Channels.stdlib, + Channels.asyncio, + Channels.typing, + Channels.discussion_capi, + Channels.discussion_triage, + Channels.discussion_design, + Channels.discussion_mentor, + Channels.documentation, ) # Bot replies -- cgit v1.2.3 From 273a5170a42c119d74c337532e3ff8fe91a6f34c Mon Sep 17 00:00:00 2001 From: Daniel Brown Date: Thu, 15 Oct 2020 10:32:09 -0500 Subject: Corrected Trailing Whitespace Removed a trailing white space that caused a build failure. --- bot/constants.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 2466da02..c5eed1f8 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -76,7 +76,7 @@ class Channels(NamedTuple): show_your_projects_discussion = 360148304664723466 hacktoberfest_2020 = 760857070781071431 voice_chat = 412357430186344448 - + # Core Dev Sprint channels announcements = 755958119963557958 information = 753338352136224798 @@ -228,7 +228,7 @@ WHITELISTED_CHANNELS = ( Channels.off_topic_1, Channels.off_topic_2, Channels.voice_chat, - + # Core Dev Sprint Channels Channels.announcements, Channels.information, -- cgit v1.2.3 From 725d3982128ae7da549b2a9aa1bfa5194393ba42 Mon Sep 17 00:00:00 2001 From: kwzrd Date: Thu, 15 Oct 2020 20:17:49 +0200 Subject: Constants: rename conflicting channel There were two attributes named 'announcements' on the Channels class. --- bot/constants.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index c5eed1f8..2056d542 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -78,7 +78,7 @@ class Channels(NamedTuple): voice_chat = 412357430186344448 # Core Dev Sprint channels - announcements = 755958119963557958 + sprint_announcements = 755958119963557958 information = 753338352136224798 organisers = 753340132639375420 general = 753340631538991305 @@ -230,7 +230,7 @@ WHITELISTED_CHANNELS = ( Channels.voice_chat, # Core Dev Sprint Channels - Channels.announcements, + Channels.sprint_announcements, Channels.information, Channels.organisers, Channels.general, -- cgit v1.2.3 From e67f4a063eb7c9926ed295a9c99394487d5ca633 Mon Sep 17 00:00:00 2001 From: kwzrd Date: Thu, 15 Oct 2020 20:28:38 +0200 Subject: Constants: prefix sprint channel names These are channels created for the CPython Core Dev Sprint event. --- bot/constants.py | 56 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 28 insertions(+), 28 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 2056d542..f1f34886 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -79,20 +79,20 @@ class Channels(NamedTuple): # Core Dev Sprint channels sprint_announcements = 755958119963557958 - information = 753338352136224798 - organisers = 753340132639375420 - general = 753340631538991305 - social1_cheese_shop = 758779754789863514 - social2_pet_shop = 758780951978573824 - escape_room = 761031075942105109 - stdlib = 758553316732698634 - asyncio = 762904152438472714 - typing = 762904690341838888 - discussion_capi = 758553358587527218 - discussion_triage = 758553458365300746 - discussion_design = 758553492662255616 - discussion_mentor = 758553536623280159 - documentation = 761038271127093278 + sprint_information = 753338352136224798 + sprint_organisers = 753340132639375420 + sprint_general = 753340631538991305 + sprint_social1_cheese_shop = 758779754789863514 + sprint_social2_pet_shop = 758780951978573824 + sprint_escape_room = 761031075942105109 + sprint_stdlib = 758553316732698634 + sprint_asyncio = 762904152438472714 + sprint_typing = 762904690341838888 + sprint_discussion_capi = 758553358587527218 + sprint_discussion_triage = 758553458365300746 + sprint_discussion_design = 758553492662255616 + sprint_discussion_mentor = 758553536623280159 + sprint_documentation = 761038271127093278 class Client(NamedTuple): @@ -231,20 +231,20 @@ WHITELISTED_CHANNELS = ( # Core Dev Sprint Channels Channels.sprint_announcements, - Channels.information, - Channels.organisers, - Channels.general, - Channels.social1_cheese_shop, - Channels.social2_pet_shop, - Channels.escape_room, - Channels.stdlib, - Channels.asyncio, - Channels.typing, - Channels.discussion_capi, - Channels.discussion_triage, - Channels.discussion_design, - Channels.discussion_mentor, - Channels.documentation, + Channels.sprint_information, + Channels.sprint_organisers, + Channels.sprint_general, + Channels.sprint_social1_cheese_shop, + Channels.sprint_social2_pet_shop, + Channels.sprint_escape_room, + Channels.sprint_stdlib, + Channels.sprint_asyncio, + Channels.sprint_typing, + Channels.sprint_discussion_capi, + Channels.sprint_discussion_triage, + Channels.sprint_discussion_design, + Channels.sprint_discussion_mentor, + Channels.sprint_documentation, ) # Bot replies -- cgit v1.2.3 From a1fc1ad5643f4ae5f5ebbb3cb8f8cdc0a34df95a Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Mon, 16 Nov 2020 16:18:21 +0200 Subject: Create Redis configuration class --- bot/constants.py | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index f1f34886..1dcc8846 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -216,6 +216,13 @@ class Wolfram(NamedTuple): key = environ.get("WOLFRAM_API_KEY") +class RedisCache(NamedTuple): + host = environ.get("REDIS_HOST", "redis.default.svc.cluster.local") + port = environ.get("REDIS_PORT", 6379) + password = environ.get("REDIS_PASSWORD") + use_fakeredis = environ.get("USE_FAKEREDIS", "false").lower() == "true" + + # Default role combinations MODERATION_ROLES = Roles.moderator, Roles.admin, Roles.owner STAFF_ROLES = Roles.helpers, Roles.moderator, Roles.admin, Roles.owner -- cgit v1.2.3 From 824084bf7c18edd96ea194b242fa47cb58bed15c Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Mon, 16 Nov 2020 16:23:20 +0200 Subject: Rename redis configuration class --- bot/constants.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 1dcc8846..b9648507 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -17,6 +17,7 @@ __all__ = ( "Roles", "Tokens", "Wolfram", + "RedisConfig", "MODERATION_ROLES", "STAFF_ROLES", "WHITELISTED_CHANNELS", @@ -216,7 +217,7 @@ class Wolfram(NamedTuple): key = environ.get("WOLFRAM_API_KEY") -class RedisCache(NamedTuple): +class RedisConfig(NamedTuple): host = environ.get("REDIS_HOST", "redis.default.svc.cluster.local") port = environ.get("REDIS_PORT", 6379) password = environ.get("REDIS_PASSWORD") -- cgit v1.2.3 From 6f524c3594a3ec7715569c66f8a3c0db369b5636 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sat, 21 Nov 2020 00:30:19 +0100 Subject: Make the bot name less hard-coded. --- bot/bot.py | 38 ++++++++++++++++++++------------------ bot/constants.py | 3 ++- 2 files changed, 22 insertions(+), 19 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/bot.py b/bot/bot.py index 3b4d43df..bf4a59c2 100644 --- a/bot/bot.py +++ b/bot/bot.py @@ -9,14 +9,14 @@ from async_rediscache import RedisSession from discord import DiscordException, Embed from discord.ext import commands -from bot.constants import Channels, Client, MODERATION_ROLES, RedisConfig +import bot.constants as constants log = logging.getLogger(__name__) -__all__ = ("SeasonalBot", "bot") +__all__ = ("Bot", "bot") -class SeasonalBot(commands.Bot): +class Bot(commands.Bot): """ Base bot instance. @@ -25,6 +25,8 @@ class SeasonalBot(commands.Bot): that the upload was successful. See the `mock_in_debug` decorator for further details. """ + name = constants.Client.name + def __init__(self, redis_session: RedisSession, **kwargs): super().__init__(**kwargs) self.http_session = ClientSession( @@ -33,12 +35,12 @@ class SeasonalBot(commands.Bot): self._guild_available = asyncio.Event() self.redis_session = redis_session - self.loop.create_task(self.send_log("SeasonalBot", "Connected!")) + self.loop.create_task(self.send_log(self.name, "Connected!")) @property def member(self) -> Optional[discord.Member]: """Retrieves the guild member object for the bot.""" - guild = self.get_guild(Client.guild) + guild = self.get_guild(constants.Client.guild) if not guild: return None return guild.me @@ -72,12 +74,12 @@ class SeasonalBot(commands.Bot): async def send_log(self, title: str, details: str = None, *, icon: str = None) -> None: """Send an embed message to the devlog channel.""" await self.wait_until_guild_available() - devlog = self.get_channel(Channels.devlog) + devlog = self.get_channel(constants.Channels.devlog) if not devlog: - log.info(f"Fetching devlog channel as it wasn't found in the cache (ID: {Channels.devlog})") + log.info(f"Fetching devlog channel as it wasn't found in the cache (ID: {constants.Channels.devlog})") try: - devlog = await self.fetch_channel(Channels.devlog) + devlog = await self.fetch_channel(constants.Channels.devlog) except discord.HTTPException as discord_exc: log.exception("Fetch failed", exc_info=discord_exc) return @@ -97,7 +99,7 @@ class SeasonalBot(commands.Bot): If the cache appears to still be empty (no members, no channels, or no roles), the event will not be set. """ - if guild.id != Client.guild: + if guild.id != constants.Client.guild: return if not guild.roles or not guild.members or not guild.channels: @@ -108,7 +110,7 @@ class SeasonalBot(commands.Bot): async def on_guild_unavailable(self, guild: discord.Guild) -> None: """Clear the internal `_guild_available` event when PyDis guild becomes unavailable.""" - if guild.id != Client.guild: + if guild.id != constants.Client.guild: return self._guild_available.clear() @@ -123,7 +125,7 @@ class SeasonalBot(commands.Bot): await self._guild_available.wait() -_allowed_roles = [discord.Object(id_) for id_ in MODERATION_ROLES] +_allowed_roles = [discord.Object(id_) for id_ in constants.MODERATION_ROLES] _intents = discord.Intents.default() # Default is all intents except for privileged ones (Members, Presences, ...) _intents.bans = False @@ -133,20 +135,20 @@ _intents.typing = False _intents.webhooks = False redis_session = RedisSession( - address=(RedisConfig.host, RedisConfig.port), - password=RedisConfig.password, + address=(constants.RedisConfig.host, constants.RedisConfig.port), + password=constants.RedisConfig.password, minsize=1, maxsize=20, - use_fakeredis=RedisConfig.use_fakeredis, - global_namespace="seasonalbot" + use_fakeredis=constants.RedisConfig.use_fakeredis, + global_namespace="sir-lancebot" ) loop = asyncio.get_event_loop() loop.run_until_complete(redis_session.connect()) -bot = SeasonalBot( +bot = Bot( redis_session=redis_session, - command_prefix=Client.prefix, - activity=discord.Game(name=f"Commands: {Client.prefix}help"), + command_prefix=constants.Client.prefix, + activity=discord.Game(name=f"Commands: {constants.Client.prefix}help"), allowed_mentions=discord.AllowedMentions(everyone=False, roles=_allowed_roles), intents=_intents, ) diff --git a/bot/constants.py b/bot/constants.py index b9648507..eda10121 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -97,7 +97,8 @@ class Channels(NamedTuple): class Client(NamedTuple): - guild = int(environ.get("SEASONALBOT_GUILD", 267624335836053506)) + name = "Sir Lancebot" + guild = int(environ.get("BOT_GUILD", 267624335836053506)) prefix = environ.get("PREFIX", ".") token = environ.get("SEASONALBOT_TOKEN") sentry_dsn = environ.get("SEASONALBOT_SENTRY_DSN") -- cgit v1.2.3 From 16417225e7c0bfbb4260d51722c2f68696e7ccd6 Mon Sep 17 00:00:00 2001 From: Leon Sandøy Date: Sat, 21 Nov 2020 00:30:58 +0100 Subject: Remove references to old name. I've tried to replace this with generic references where appropriate, but a lot of the time it just doesn't make a lot of sense to do so. --- .github/ISSUE_TEMPLATE/config.yml | 2 +- .github/workflows/build.yaml | 8 ++++---- CONTRIBUTING.md | 6 +++--- README.md | 12 +++++------ bot/constants.py | 33 +++++++++++++++--------------- bot/exts/easter/egg_facts.py | 8 ++++---- bot/exts/evergreen/game.py | 6 +++--- bot/exts/evergreen/help.py | 8 ++++---- bot/exts/evergreen/issues.py | 2 +- bot/exts/evergreen/source.py | 2 +- bot/exts/evergreen/space.py | 6 +++--- bot/exts/halloween/candy_collection.py | 6 +++--- bot/exts/halloween/hacktoberstats.py | 6 +++--- bot/exts/halloween/spookyreact.py | 6 +----- bot/exts/pride/pride_facts.py | 8 ++++---- bot/exts/utils/extensions.py | 2 +- bot/exts/valentines/be_my_valentine.py | 2 +- bot/resources/halloween/spooky_rating.json | 18 ++++++++-------- bot/utils/checks.py | 2 +- deployment.yaml | 12 +++++------ docker-compose.yml | 16 +++++++-------- 21 files changed, 82 insertions(+), 89 deletions(-) (limited to 'bot/constants.py') diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 519294a0..4580be2f 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -4,4 +4,4 @@ contact_links: url: https://discord.gg/python about: Contributors must be part of the community, so be sure to join! - name: Contributing Guide - url: https://pythondiscord.com/pages/contributing/seasonalbot/ + url: https://pythondiscord.com/pages/contributing/sir-lancebot/ diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index f133ba24..20449741 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -44,11 +44,11 @@ jobs: context: . file: ./Dockerfile push: true - cache-from: type=registry,ref=ghcr.io/python-discord/seasonalbot:latest + cache-from: type=registry,ref=ghcr.io/python-discord/sir-lancebot:latest cache-to: type=inline tags: | - ghcr.io/python-discord/seasonalbot:latest - ghcr.io/python-discord/seasonalbot:${{ steps.sha_tag.outputs.tag }} + ghcr.io/python-discord/sir-lancebot:latest + ghcr.io/python-discord/sir-lancebot:${{ steps.sha_tag.outputs.tag }} - name: Authenticate with Kubernetes uses: azure/k8s-set-context@v1 @@ -61,5 +61,5 @@ jobs: with: manifests: | deployment.yaml - images: 'ghcr.io/python-discord/seasonalbot:${{ steps.sha_tag.outputs.tag }}' + images: 'ghcr.io/python-discord/sir-lancebot:${{ steps.sha_tag.outputs.tag }}' kubectl-version: 'latest' diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e1fa39ec..7cf83db5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,6 +1,6 @@ -# Contributing to Seasonalbot +# Contributing to Sir Lancebot -Seasonalbot is a community project for the Python Discord community over at https://discord.gg/python. We will be providing support for those of you who are new to Git, and this project is to be considered educational. +Sir Lancebot is a community project for the Python Discord community over at https://discord.gg/python. We will be providing support for those of you who are new to Git, and this project is to be considered educational. Our projects are open-source and are automatically deployed whenever commits are pushed to the `master` branch on each repository, so we've created a set of guidelines in order to keep everything clean and in working order. @@ -39,7 +39,7 @@ All projects evolve over time, and this contribution guide is no different. This ## Supplemental Information ### Developer Environment -Seasonalbot utilizes [Pipenv](https://pipenv.readthedocs.io/en/latest/) for installation and dependency management. For users unfamiliar with the Pipenv workflow, Pipenv's documentation provides a [Basic Usage](https://pipenv.readthedocs.io/en/latest/basics/) tutorial, along with some of the more advanced workflows. A project-specific installation guide can be found in [Seasonalbot's README](https://github.com/python-discord/seasonalbot/blob/master/README.md). +Sir Lancebot utilizes [Pipenv](https://pipenv.readthedocs.io/en/latest/) for installation and dependency management. For users unfamiliar with the Pipenv workflow, Pipenv's documentation provides a [Basic Usage](https://pipenv.readthedocs.io/en/latest/basics/) tutorial, along with some of the more advanced workflows. A project-specific installation guide can be found in [Sir Lancebot's README](https://github.com/python-discord/sir-lancebot/blob/master/README.md). When pulling down changes from GitHub, remember to sync your environment using `pipenv sync --dev` to ensure you're using the most up-to-date versions the project's dependencies. diff --git a/README.md b/README.md index 0c9d1e7d..20e6c8c1 100755 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SeasonalBot +# Sir Lancebot [![Lint Badge][1]][2] [![Build Badge][3]][4] @@ -17,9 +17,9 @@ This later evolved into a bot that runs all year, providing season-appropriate f ## Getting started Before you start, please take some time to read through our [contributing guidelines](CONTRIBUTING.md). -See [Seasonalbot's Wiki](https://pythondiscord.com/pages/contributing/seasonalbot/) for in-depth guides on getting started with the project! +See [Sir Lancebot's Wiki](https://pythondiscord.com/pages/contributing/sir-lancebot/) for in-depth guides on getting started with the project! -[1]:https://github.com/python-discord/seasonalbot/workflows/Lint/badge.svg?branch=master -[2]:https://github.com/python-discord/seasonalbot/actions?query=workflow%3ALint+branch%3Amaster -[3]:https://github.com/python-discord/seasonalbot/workflows/Build/badge.svg?branch=master -[4]:https://github.com/python-discord/seasonalbot/actions?query=workflow%3ABuild+branch%3Amaster +[1]:https://github.com/python-discord/sir-lancebot/workflows/Lint/badge.svg?branch=master +[2]:https://github.com/python-discord/sir-lancebot/actions?query=workflow%3ALint+branch%3Amaster +[3]:https://github.com/python-discord/sir-lancebot/workflows/Build/badge.svg?branch=master +[4]:https://github.com/python-discord/sir-lancebot/actions?query=workflow%3ABuild+branch%3Amaster diff --git a/bot/constants.py b/bot/constants.py index eda10121..6999f321 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -68,13 +68,10 @@ class Channels(NamedTuple): off_topic_2 = 463035268514185226 python = 267624335836053506 reddit = 458224812528238616 - seasonalbot_commands = int(environ.get("CHANNEL_SEASONALBOT_COMMANDS", 607247579608121354)) - seasonalbot_voice = int(environ.get("CHANNEL_SEASONALBOT_VOICE", 606259004230074378)) + community_bot_commands = int(environ.get("CHANNEL_COMMUNITY_BOT_COMMANDS", 607247579608121354)) staff_lounge = 464905259261755392 verification = 352442727016693763 python_discussion = 267624335836053506 - show_your_projects = int(environ.get("CHANNEL_SHOW_YOUR_PROJECTS", 303934982764625920)) - show_your_projects_discussion = 360148304664723466 hacktoberfest_2020 = 760857070781071431 voice_chat = 412357430186344448 @@ -100,10 +97,10 @@ class Client(NamedTuple): name = "Sir Lancebot" guild = int(environ.get("BOT_GUILD", 267624335836053506)) prefix = environ.get("PREFIX", ".") - token = environ.get("SEASONALBOT_TOKEN") - sentry_dsn = environ.get("SEASONALBOT_SENTRY_DSN") - debug = environ.get("SEASONALBOT_DEBUG", "").lower() == "true" - github_bot_repo = "https://github.com/python-discord/seasonalbot" + token = environ.get("BOT_TOKEN") + sentry_dsn = environ.get("BOT_SENTRY_DSN") + debug = environ.get("BOT_DEBUG", "").lower() == "true" + github_bot_repo = "https://github.com/python-discord/sir-lancebot" # Override seasonal locks: 1 (January) to 12 (December) month_override = int(environ["MONTH_OVERRIDE"]) if "MONTH_OVERRIDE" in environ else None @@ -185,7 +182,7 @@ if Client.month_override is not None: class Roles(NamedTuple): - admin = int(environ.get("SEASONALBOT_ADMIN_ROLE_ID", 267628507062992896)) + admin = int(environ.get("BOT_ADMIN_ROLE_ID", 267628507062992896)) announcements = 463658397560995840 champion = 430492892331769857 contributor = 295488872404484098 @@ -225,6 +222,15 @@ class RedisConfig(NamedTuple): use_fakeredis = environ.get("USE_FAKEREDIS", "false").lower() == "true" +class Wikipedia: + total_chance = 3 + + +class Source: + github = "https://github.com/python-discord/sir-lancebot" + github_avatar_url = "https://avatars1.githubusercontent.com/u/9919" + + # Default role combinations MODERATION_ROLES = Roles.moderator, Roles.admin, Roles.owner STAFF_ROLES = Roles.helpers, Roles.moderator, Roles.admin, Roles.owner @@ -232,7 +238,7 @@ STAFF_ROLES = Roles.helpers, Roles.moderator, Roles.admin, Roles.owner # Whitelisted channels WHITELISTED_CHANNELS = ( Channels.bot, - Channels.seasonalbot_commands, + Channels.community_bot_commands, Channels.off_topic_0, Channels.off_topic_1, Channels.off_topic_2, @@ -309,10 +315,3 @@ POSITIVE_REPLIES = [ "Aye aye, cap'n!", "I'll allow it.", ] - -class Wikipedia: - total_chance = 3 - -class Source: - github = "https://github.com/python-discord/seasonalbot" - github_avatar_url = "https://avatars1.githubusercontent.com/u/9919" diff --git a/bot/exts/easter/egg_facts.py b/bot/exts/easter/egg_facts.py index 0051aa50..761e9059 100644 --- a/bot/exts/easter/egg_facts.py +++ b/bot/exts/easter/egg_facts.py @@ -6,7 +6,7 @@ from pathlib import Path import discord from discord.ext import commands -from bot.bot import SeasonalBot +from bot.bot import Bot from bot.constants import Channels, Colours, Month from bot.utils.decorators import seasonal_task @@ -20,7 +20,7 @@ class EasterFacts(commands.Cog): It also contains a background task which sends an easter egg fact in the event channel everyday. """ - def __init__(self, bot: SeasonalBot): + def __init__(self, bot: Bot): self.bot = bot self.facts = self.load_json() @@ -38,7 +38,7 @@ class EasterFacts(commands.Cog): """A background task that sends an easter egg fact in the event channel everyday.""" await self.bot.wait_until_guild_available() - channel = self.bot.get_channel(Channels.seasonalbot_commands) + channel = self.bot.get_channel(Channels.community_bot_commands) await channel.send(embed=self.make_embed()) @commands.command(name='eggfact', aliases=['fact']) @@ -56,6 +56,6 @@ class EasterFacts(commands.Cog): ) -def setup(bot: SeasonalBot) -> None: +def setup(bot: Bot) -> None: """Easter Egg facts cog load.""" bot.add_cog(EasterFacts(bot)) diff --git a/bot/exts/evergreen/game.py b/bot/exts/evergreen/game.py index 3c8b2725..d0fd7a40 100644 --- a/bot/exts/evergreen/game.py +++ b/bot/exts/evergreen/game.py @@ -11,7 +11,7 @@ from discord import Embed from discord.ext import tasks from discord.ext.commands import Cog, Context, group -from bot.bot import SeasonalBot +from bot.bot import Bot from bot.constants import STAFF_ROLES, Tokens from bot.utils.decorators import with_role from bot.utils.pagination import ImagePaginator, LinePaginator @@ -130,7 +130,7 @@ class AgeRatings(IntEnum): class Games(Cog): """Games Cog contains commands that collect data from IGDB.""" - def __init__(self, bot: SeasonalBot): + def __init__(self, bot: Bot): self.bot = bot self.http_session: ClientSession = bot.http_session @@ -415,7 +415,7 @@ class Games(Cog): return sorted((item for item in results if item[0] >= 0.60), reverse=True)[:4] -def setup(bot: SeasonalBot) -> None: +def setup(bot: Bot) -> None: """Add/Load Games cog.""" # Check does IGDB API key exist, if not, log warning and don't load cog if not Tokens.igdb: diff --git a/bot/exts/evergreen/help.py b/bot/exts/evergreen/help.py index ccd76d76..91147243 100644 --- a/bot/exts/evergreen/help.py +++ b/bot/exts/evergreen/help.py @@ -12,7 +12,7 @@ from discord.ext.commands import CheckFailure, Cog as DiscordCog, Command, Conte from fuzzywuzzy import fuzz, process from bot import constants -from bot.bot import SeasonalBot +from bot.bot import Bot from bot.constants import Emojis from bot.utils.pagination import ( FIRST_EMOJI, LAST_EMOJI, @@ -511,7 +511,7 @@ class Help(DiscordCog): await ctx.send(embed=embed) -def unload(bot: SeasonalBot) -> None: +def unload(bot: Bot) -> None: """ Reinstates the original help command. @@ -521,7 +521,7 @@ def unload(bot: SeasonalBot) -> None: bot.add_command(bot._old_help) -def setup(bot: SeasonalBot) -> None: +def setup(bot: Bot) -> None: """ The setup for the help extension. @@ -542,7 +542,7 @@ def setup(bot: SeasonalBot) -> None: raise -def teardown(bot: SeasonalBot) -> None: +def teardown(bot: Bot) -> None: """ The teardown for the help extension. diff --git a/bot/exts/evergreen/issues.py b/bot/exts/evergreen/issues.py index 97ee6a12..e419a6f5 100644 --- a/bot/exts/evergreen/issues.py +++ b/bot/exts/evergreen/issues.py @@ -33,7 +33,7 @@ class Issues(commands.Cog): self, ctx: commands.Context, numbers: commands.Greedy[int], - repository: str = "seasonalbot", + repository: str = "sir-lancebot", user: str = "python-discord" ) -> None: """Command to retrieve issue(s) from a GitHub repository.""" diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py index 0725714f..cdfe54ec 100644 --- a/bot/exts/evergreen/source.py +++ b/bot/exts/evergreen/source.py @@ -38,7 +38,7 @@ class BotSource(commands.Cog): async def source_command(self, ctx: commands.Context, *, source_item: SourceConverter = None) -> None: """Display information and a GitHub link to the source code of a command, tag, or cog.""" if not source_item: - embed = Embed(title="Seasonal Bot's GitHub Repository") + embed = Embed(title="Sir Lancebot's GitHub Repository") embed.add_field(name="Repository", value=f"[Go to GitHub]({Source.github})") embed.set_thumbnail(url=Source.github_avatar_url) await ctx.send(embed=embed) diff --git a/bot/exts/evergreen/space.py b/bot/exts/evergreen/space.py index 3587fc00..bc8e3118 100644 --- a/bot/exts/evergreen/space.py +++ b/bot/exts/evergreen/space.py @@ -8,7 +8,7 @@ from discord import Embed from discord.ext import tasks from discord.ext.commands import BadArgument, Cog, Context, Converter, group -from bot.bot import SeasonalBot +from bot.bot import Bot from bot.constants import Tokens logger = logging.getLogger(__name__) @@ -37,7 +37,7 @@ class DateConverter(Converter): class Space(Cog): """Space Cog contains commands, that show images, facts or other information about space.""" - def __init__(self, bot: SeasonalBot): + def __init__(self, bot: Bot): self.bot = bot self.http_session = bot.http_session @@ -240,7 +240,7 @@ class Space(Cog): ).set_image(url=image).set_footer(text="Powered by NASA API" + footer) -def setup(bot: SeasonalBot) -> None: +def setup(bot: Bot) -> None: """Load Space Cog.""" if not Tokens.nasa: logger.warning("Can't find NASA API key. Not loading Space Cog.") diff --git a/bot/exts/halloween/candy_collection.py b/bot/exts/halloween/candy_collection.py index 33e18b24..0cb37ecd 100644 --- a/bot/exts/halloween/candy_collection.py +++ b/bot/exts/halloween/candy_collection.py @@ -51,7 +51,7 @@ class CandyCollection(commands.Cog): if message.author.bot: return # ensure it's hacktober channel - if message.channel.id != Channels.seasonalbot_commands: + if message.channel.id != Channels.community_bot_commands: return # do random check for skull first as it has the lower chance @@ -73,7 +73,7 @@ class CandyCollection(commands.Cog): return # check to ensure it is in correct channel - if message.channel.id != Channels.seasonalbot_commands: + if message.channel.id != Channels.community_bot_commands: return # if its not a candy or skull, and it is one of 10 most recent messages, @@ -130,7 +130,7 @@ class CandyCollection(commands.Cog): @property def hacktober_channel(self) -> discord.TextChannel: """Get #hacktoberbot channel from its ID.""" - return self.bot.get_channel(id=Channels.seasonalbot_commands) + return self.bot.get_channel(id=Channels.community_bot_commands) @staticmethod async def send_spook_msg( diff --git a/bot/exts/halloween/hacktoberstats.py b/bot/exts/halloween/hacktoberstats.py index 26d75565..84b75022 100644 --- a/bot/exts/halloween/hacktoberstats.py +++ b/bot/exts/halloween/hacktoberstats.py @@ -193,7 +193,7 @@ class HacktoberStats(commands.Cog): For each PR: { "repo_url": str - "repo_shortname": str (e.g. "python-discord/seasonalbot") + "repo_shortname": str (e.g. "python-discord/sir-lancebot") "created_at": datetime.datetime "number": int } @@ -360,10 +360,10 @@ class HacktoberStats(commands.Cog): """ Extract shortname from https://api.github.com/repos/* URL. - e.g. "https://api.github.com/repos/python-discord/seasonalbot" + e.g. "https://api.github.com/repos/python-discord/sir-lancebot" | V - "python-discord/seasonalbot" + "python-discord/sir-lancebot" """ exp = r"https?:\/\/api.github.com\/repos\/([/\-\_\.\w]+)" return re.findall(exp, in_url)[0] diff --git a/bot/exts/halloween/spookyreact.py b/bot/exts/halloween/spookyreact.py index e5945aea..21b8ff7c 100644 --- a/bot/exts/halloween/spookyreact.py +++ b/bot/exts/halloween/spookyreact.py @@ -30,11 +30,7 @@ class SpookyReact(Cog): @Cog.listener() async def on_message(self, ctx: discord.Message) -> None: """ - A command to send the seasonalbot github project. - - Lines that begin with the bot's command prefix are ignored - - Seasonalbot's own messages are ignored + Triggered when the bot sees a message in October. """ for trigger in SPOOKY_TRIGGERS.keys(): trigger_test = re.search(SPOOKY_TRIGGERS[trigger][0], ctx.content.lower()) diff --git a/bot/exts/pride/pride_facts.py b/bot/exts/pride/pride_facts.py index 9ff4c9e0..5bd5d0ce 100644 --- a/bot/exts/pride/pride_facts.py +++ b/bot/exts/pride/pride_facts.py @@ -9,7 +9,7 @@ import dateutil.parser import discord from discord.ext import commands -from bot.bot import SeasonalBot +from bot.bot import Bot from bot.constants import Channels, Colours, Month from bot.utils.decorators import seasonal_task @@ -21,7 +21,7 @@ Sendable = Union[commands.Context, discord.TextChannel] class PrideFacts(commands.Cog): """Provides a new fact every day during the Pride season!""" - def __init__(self, bot: SeasonalBot): + def __init__(self, bot: Bot): self.bot = bot self.facts = self.load_facts() @@ -38,7 +38,7 @@ class PrideFacts(commands.Cog): """Background task to post the daily pride fact every day.""" await self.bot.wait_until_guild_available() - channel = self.bot.get_channel(Channels.seasonalbot_commands) + channel = self.bot.get_channel(Channels.community_bot_commands) await self.send_select_fact(channel, datetime.utcnow()) async def send_random_fact(self, ctx: commands.Context) -> None: @@ -102,6 +102,6 @@ class PrideFacts(commands.Cog): ) -def setup(bot: SeasonalBot) -> None: +def setup(bot: Bot) -> None: """Cog loader for pride facts.""" bot.add_cog(PrideFacts(bot)) diff --git a/bot/exts/utils/extensions.py b/bot/exts/utils/extensions.py index 102a0416..bb22c353 100644 --- a/bot/exts/utils/extensions.py +++ b/bot/exts/utils/extensions.py @@ -8,7 +8,7 @@ from discord.ext import commands from discord.ext.commands import Context, group from bot import exts -from bot.bot import SeasonalBot as Bot +from bot.bot import Bot from bot.constants import Client, Emojis, MODERATION_ROLES, Roles from bot.utils.checks import with_role_check from bot.utils.extensions import EXTENSIONS, unqualify diff --git a/bot/exts/valentines/be_my_valentine.py b/bot/exts/valentines/be_my_valentine.py index b1258307..4db4d191 100644 --- a/bot/exts/valentines/be_my_valentine.py +++ b/bot/exts/valentines/be_my_valentine.py @@ -99,7 +99,7 @@ class BeMyValentine(commands.Cog): emoji_1, emoji_2 = self.random_emoji() lovefest_role = discord.utils.get(ctx.guild.roles, id=Lovefest.role_id) - channel = self.bot.get_channel(Channels.seasonalbot_commands) + channel = self.bot.get_channel(Channels.community_bot_commands) valentine, title = self.valentine_check(valentine_type) if user is None: diff --git a/bot/resources/halloween/spooky_rating.json b/bot/resources/halloween/spooky_rating.json index d9c8dcb7..533e7107 100644 --- a/bot/resources/halloween/spooky_rating.json +++ b/bot/resources/halloween/spooky_rating.json @@ -2,46 +2,46 @@ "-1": { "title": "\uD83D\uDD6F You're not scarin' anyone \uD83D\uDD6F", "text": "No matter what you say or do, nobody even flinches when you try to scare them. Was your costume this year only a white sheet with holes for eyes? Or did you even bother with a costume at all? Either way, don't expect too many treats when going from door-to-door.", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/candle.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/candle.jpeg" }, "5": { "title": "\uD83D\uDC76 Like taking candy from a baby \uD83D\uDC76", "text": "Your scaring will probably make a baby cry... but that's the limit on your frightening powers. Be careful not to get to the point where everyone's running away from you because they don't like you, not because they're scared of you.", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/baby.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/baby.jpeg" }, "20": { "title": "\uD83C\uDFDA You're skills are forming... \uD83C\uDFDA", "text": "As you become the Devil's apprentice, you begin to make people jump every time you sneak up on them. A good start, but you have to learn not to wear the same costume every year until it doesn't fit you. People will notice you and your prowess will decrease.", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/tiger.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/tiger.jpeg" }, "30": { "title": "\uD83D\uDC80 Picture Perfect... \uD83D\uDC80", "text": "You've nailed the costume this year! You look suuuper scary! Now make sure to play the part and act out your costume and you'll be sure to give a few people a massive fright!", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/costume.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/costume.jpeg" }, "50": { "title": "\uD83D\uDC7B Uhm... are you human \uD83D\uDC7B", "text": "Uhm... you're too good to be human and now you're beginning to sound like a ghost. You're almost invisible when haunting and nobody truly knows where you are at any given time. But they will always scream at the sound of a ghost...", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/ghost.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/ghost.jpeg" }, "65": { "title": "\uD83C\uDF83 That potion can't be real \uD83C\uDF83", "text": "You're carrying... some... unknown liquids and no one knows who they are but yourself. Be careful on who you use these powerful spells on, because no Mage has the power to do any irreversible enchantments because even you won't know what will happen to these mortals.", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/necromancer.jepg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/necromancer.jepg" }, "80": { "title": "\uD83E\uDD21 The most sinister face \uD83E\uDD21", "text": "Who knew something intended to be playful could be so menacing... Especially other people seeing you in their nightmares, continuing to haunt them day by day, stuck in their head throughout the entire year. Make sure to pull a face they will never forget.", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/clown.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/clown.jpeg" }, "95": { "title": "\uD83D\uDE08 The Devil's Accomplice \uD83D\uDE08", "text": "Imagine being allies with the most evil character with an aim to scare people to death. Force people to suffer as they proceed straight to hell to meet your boss and best friend. Not even you know the power He has...", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/jackolantern.jpg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/jackolantern.jpg" }, "100": { "title":"\uD83D\uDC7F The Devil Himself \uD83D\uDC7F", "text": "You are the evillest creature in existence to scare anyone and everyone humanly possible. The reason your underlings are called mortals is that they die. With your help, they die a lot quicker. With all the evil power in the universe, you know what to do.", - "image": "https://raw.githubusercontent.com/python-discord/seasonalbot/master/bot/resources/halloween/spookyrating/devil.jpeg" + "image": "https://raw.githubusercontent.com/python-discord/sir-lancebot/master/bot/resources/halloween/spookyrating/devil.jpeg" } } diff --git a/bot/utils/checks.py b/bot/utils/checks.py index 3031a271..9dd4dde0 100644 --- a/bot/utils/checks.py +++ b/bot/utils/checks.py @@ -39,7 +39,7 @@ def in_whitelist_check( channels: Container[int] = (), categories: Container[int] = (), roles: Container[int] = (), - redirect: Optional[int] = constants.Channels.seasonalbot_commands, + redirect: Optional[int] = constants.Channels.community_bot_commands, fail_silently: bool = False, ) -> bool: """ diff --git a/deployment.yaml b/deployment.yaml index b04b528c..cad97c18 100644 --- a/deployment.yaml +++ b/deployment.yaml @@ -1,21 +1,21 @@ apiVersion: apps/v1 kind: Deployment metadata: - name: seasonalbot + name: sir-lancebot spec: replicas: 1 selector: matchLabels: - app: seasonalbot + app: sir-lancebot template: metadata: labels: - app: seasonalbot + app: sir-lancebot spec: containers: - - name: seasonalbot - image: ghcr.io/python-discord/seasonalbot:latest + - name: sir-lancebot + image: ghcr.io/python-discord/sir-lancebot:latest imagePullPolicy: Always envFrom: - secretRef: - name: seasonalbot-env + name: sir-lancebot-env diff --git a/docker-compose.yml b/docker-compose.yml index 24eeafe0..bb6ad6ac 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,10 +1,10 @@ version: "3.7" services: - seasonalbot: + sir-lancebot: build: context: . dockerfile: Dockerfile - container_name: seasonalbot + container_name: sir-lancebot init: true restart: always @@ -12,17 +12,15 @@ services: - redis environment: - - SEASONALBOT_TOKEN - - SEASONALBOT_DEBUG - - SEASONALBOT_GUILD - - SEASONALBOT_ADMIN_ROLE_ID + - BOT_TOKEN + - BOT_DEBUG + - BOT_GUILD + - BOT_ADMIN_ROLE_ID - CHANNEL_DEVLOG - - CHANNEL_SEASONALBOT_COMMANDS + - CHANNEL_COMMUNITY_BOT_COMMANDS - REDIS_HOST=redis volumes: - - /opt/pythondiscord/seasonalbot/log:/bot/bot/log - - /opt/pythondiscord/seasonalbot/data:/bot/data - .:/bot redis: -- cgit v1.2.3 From 415f550969555f6929cc2d0273818bf6db57cab0 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Tue, 24 Nov 2020 17:38:43 +0200 Subject: Update constants to match with new format of AoC that will run in 2020 --- bot/constants.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 6999f321..841f2303 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -31,8 +31,10 @@ log = logging.getLogger(__name__) class AdventOfCode: leaderboard_cache_age_threshold_seconds = 3600 - leaderboard_id = 631135 - leaderboard_join_code = str(environ.get("AOC_JOIN_CODE", None)) + leaderboard_public_ids = [645282] + leaderboard_staff_id = 957532 + leaderboard_public_join_codes = environ.get("AOC_PUBLIC_JOIN_CODES", "").split(",") + leaderboard_staff_join_code = environ.get("AOC_STAFF_JOIN_CODE", "") leaderboard_max_displayed_members = 10 year = int(environ.get("AOC_YEAR", datetime.utcnow().year)) role_id = int(environ.get("AOC_ROLE_ID", 518565788744024082)) @@ -44,7 +46,8 @@ class Branding: class Channels(NamedTuple): admins = 365960823622991872 - advent_of_code = int(environ.get("AOC_CHANNEL_ID", 517745814039166986)) + advent_of_code = int(environ.get("AOC_CHANNEL_ID", 780818162836439041)) + advent_of_code_staff = int(environ.get("AOC_STAFF_CHANNEL_ID", 778646502641500181)) announcements = int(environ.get("CHANNEL_ANNOUNCEMENTS", 354619224620138496)) big_brother_logs = 468507907357409333 bot = 267659945086812160 -- cgit v1.2.3 From 2f6236671f89eb1088e985284f87292695e376cf Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Tue, 24 Nov 2020 17:44:08 +0200 Subject: Add comments about AoC env config order and change cookies way --- bot/constants.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 841f2303..bbfe7c3f 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -33,6 +33,7 @@ class AdventOfCode: leaderboard_cache_age_threshold_seconds = 3600 leaderboard_public_ids = [645282] leaderboard_staff_id = 957532 + # Public join codes in environment must be in same order than in AdventOfCode.leaderboard_public_ids leaderboard_public_join_codes = environ.get("AOC_PUBLIC_JOIN_CODES", "").split(",") leaderboard_staff_join_code = environ.get("AOC_STAFF_JOIN_CODE", "") leaderboard_max_displayed_members = 10 @@ -203,7 +204,9 @@ class Roles(NamedTuple): class Tokens(NamedTuple): giphy = environ.get("GIPHY_TOKEN") - aoc_session_cookie = environ.get("AOC_SESSION_COOKIE") + # Public AoC cookies in environment must be in same order than in AdventOfCode.leaderboard_public_ids + aoc_public_session_cookies = environ.get("AOC_PUBLIC_SESSION_COOKIES", "").split(",") + aoc_staff_session_cookie = environ.get("AOC_STAFF_SESSION_COOKIE") omdb = environ.get("OMDB_API_KEY") youtube = environ.get("YOUTUBE_API_KEY") tmdb = environ.get("TMDB_API_KEY") -- cgit v1.2.3 From ffa3619a19515c147013669339f51d36f83a5f29 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Fri, 27 Nov 2020 19:14:27 +0200 Subject: Fix adventofcode extension (and constants) grammar Co-authored-by: Joe Banks --- bot/constants.py | 4 ++-- bot/exts/christmas/adventofcode.py | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index bbfe7c3f..d24551f6 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -33,7 +33,7 @@ class AdventOfCode: leaderboard_cache_age_threshold_seconds = 3600 leaderboard_public_ids = [645282] leaderboard_staff_id = 957532 - # Public join codes in environment must be in same order than in AdventOfCode.leaderboard_public_ids + # Public join codes in environment must be in the same order as AdventOfCode.leaderboard_public_ids leaderboard_public_join_codes = environ.get("AOC_PUBLIC_JOIN_CODES", "").split(",") leaderboard_staff_join_code = environ.get("AOC_STAFF_JOIN_CODE", "") leaderboard_max_displayed_members = 10 @@ -204,7 +204,7 @@ class Roles(NamedTuple): class Tokens(NamedTuple): giphy = environ.get("GIPHY_TOKEN") - # Public AoC cookies in environment must be in same order than in AdventOfCode.leaderboard_public_ids + # Public AoC cookies in environment must be in the same order as AdventOfCode.leaderboard_public_ids aoc_public_session_cookies = environ.get("AOC_PUBLIC_SESSION_COOKIES", "").split(",") aoc_staff_session_cookie = environ.get("AOC_STAFF_SESSION_COOKIE") omdb = environ.get("OMDB_API_KEY") diff --git a/bot/exts/christmas/adventofcode.py b/bot/exts/christmas/adventofcode.py index feff09aa..b188059e 100644 --- a/bot/exts/christmas/adventofcode.py +++ b/bot/exts/christmas/adventofcode.py @@ -185,11 +185,11 @@ class AdventOfCode(commands.Cog): @seasonal_task(Month.DECEMBER, sleep_time=60 * 30) async def leaderboard_members_updater(self) -> None: """Updates public leaderboards cached member amounts in every 30 minutes.""" - # Whole December isn't advent + # Check whether we are in the 25 days of advent if not is_in_advent(): return - # Update every leaderboard for what we have session cookie + # Update every leaderboard with our session cookies for aoc_id, cookie in self.leaderboard_cookies.items(): leaderboard = await AocPrivateLeaderboard.from_url(aoc_id, cookie) await self.public_leaderboard_members.set(aoc_id, len(leaderboard.members)) @@ -203,7 +203,7 @@ class AdventOfCode(commands.Cog): for aoc_id, cookie in self.leaderboard_cookies.items() ] - # Check does this have any failed requests + # Check if any requests failed if False in leaderboards: log.warning("Unable to get one or more of the public leaderboards. Not updating cache.") return @@ -243,7 +243,7 @@ class AdventOfCode(commands.Cog): "earned": datetime.fromtimestamp(user_data["days"][day]["star_two_earned"]), }) - # Sort these lists based on user star earning time + # Sort these lists based on the time a user earnt a star star_one_users = sorted(star_one_users, key=lambda k: k["earned"])[:100] star_two_users = sorted(star_two_users, key=lambda k: k["earned"])[:100] @@ -263,7 +263,7 @@ class AdventOfCode(commands.Cog): leaderboard_users[star_user_two["id"]]["score"] = points points -= 1 - # Put completions also in to make building easier later. + # Attach star completions for building the response later for user, user_data in leaderboard_users.items(): completions_star_one = sum([1 for day in user_data["days"].values() if day["star_one"]]) completions_star_two = sum([1 for day in user_data["days"].values() if day["star_two"]]) @@ -271,7 +271,7 @@ class AdventOfCode(commands.Cog): leaderboard_users[user]["star_one_completions"] = completions_star_one leaderboard_users[user]["star_two_completions"] = completions_star_two - # Finally clear old cache and persist everything to Redis + # Finally, clear old cache and persist everything to Redis await self.public_user_data.clear() [await self.public_user_data.set(user, json.dumps(user_data)) for user, user_data in leaderboard_users.items()] @@ -300,7 +300,7 @@ class AdventOfCode(commands.Cog): async def get_leaderboard(self, members_amount: int, context: commands.Context) -> typing.Union[str, bool]: """Generates leaderboard based on Redis data.""" - # When we don't have users in cache, log warning and return False. + # When we don't have users in cache, warn and return False. if await self.public_user_data.length() == 0: log.warning("Don't have cache for displaying AoC public leaderboard.") return False @@ -414,12 +414,12 @@ class AdventOfCode(commands.Cog): join_code = AocConfig.leaderboard_staff_join_code log.info(f"{author.name} ({author.id}) ran command in staff AoC channel. Returning staff code.") else: - # We want that user get only 1 code + # Ensure we use the same leaderboard code for the same user if await self.user_leaderboards.contains(ctx.author.id): join_code = self.leaderboard_join_codes[await self.user_leaderboards.get(ctx.author.id)] - log.info(f"{author.name} ({author.id}) have already cached AoC join code. Returning it.") + log.info(f"{author.name} ({author.id}) has a cached AoC join code, returning it.") else: - # Find leaderboard that have least members inside (based on cache) + # Find the leaderboard that has the least members inside from cache least_id, least = 0, 200 for aoc_id, amount in await self.public_leaderboard_members.items(): log.info(amount, least) -- cgit v1.2.3 From 73dff91f530d7125a7ff130e9a56b759b7fdbaab Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Mon, 30 Nov 2020 00:35:57 +0100 Subject: Add constants parsing for multiple leaderboards I've added a unified approach to setting data for multiple leaderboards using environmental variables. Instead of setting separate variables for the three pieces of data we have, hoping that the position of each board matches up in the three fields, I now set one environmental variable, AOC_LEADERBOARDS, that holds delimited data. The data is in the format: board_id1,session1,join_code1::board_id2,session2,join_code2[::...] The staff leaderboards should be included as usual in this environmental variable. Another environment variable, AOC_STAFF_LEADERBOARD_ID, can be used to designate which leaderboard should be used as the staff board. I've also made some other constants configurable in this commit and added the role ID of the Events Lead role to allow the Events Lead to force a reload of the leaderboard cache. --- bot/constants.py | 47 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 9 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index d24551f6..fc9929ec 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -2,7 +2,7 @@ import enum import logging from datetime import datetime from os import environ -from typing import NamedTuple +from typing import Dict, NamedTuple __all__ = ( "AdventOfCode", @@ -29,14 +29,42 @@ __all__ = ( log = logging.getLogger(__name__) +class AdventOfCodeLeaderboard(NamedTuple): + id: str + session: str + join_code: str + + +def _parse_aoc_leaderboard_env() -> Dict[str, AdventOfCodeLeaderboard]: + """ + Parse the environment variable containing leaderboard information. + + A leaderboard should be specified in the format `id,session,join_code`, + without the backticks. If more than leaderboard needs to be added to the + constants, separate the individual leaderboards with `::`. + + Example ENV: `id1,session1,join_code1::id2,session2,join_code2` + """ + raw_leaderboards = environ.get("AOC_LEADERBOARDS", "") + if not raw_leaderboards: + return {} + + leaderboards = {} + for leaderboard in raw_leaderboards.split("::"): + leaderboard_id, session, join_code = leaderboard.split(",") + leaderboards[leaderboard_id] = AdventOfCodeLeaderboard(leaderboard_id, session, join_code) + + return leaderboards + + class AdventOfCode: - leaderboard_cache_age_threshold_seconds = 3600 - leaderboard_public_ids = [645282] - leaderboard_staff_id = 957532 - # Public join codes in environment must be in the same order as AdventOfCode.leaderboard_public_ids - leaderboard_public_join_codes = environ.get("AOC_PUBLIC_JOIN_CODES", "").split(",") - leaderboard_staff_join_code = environ.get("AOC_STAFF_JOIN_CODE", "") - leaderboard_max_displayed_members = 10 + # Information for the several leaderboards we have + leaderboards = _parse_aoc_leaderboard_env() + staff_leaderboard_id = environ.get("AOC_STAFF_LEADERBOARD_ID", "") + + # Other Advent of Code constants + leaderboard_displayed_members = 10 + leaderboard_cache_expiry_seconds = 1800 year = int(environ.get("AOC_YEAR", datetime.utcnow().year)) role_id = int(environ.get("AOC_ROLE_ID", 518565788744024082)) @@ -197,9 +225,10 @@ class Roles(NamedTuple): muted = 277914926603829249 owner = 267627879762755584 verified = 352427296948486144 - helpers = 267630620367257601 + helpers = int(environ.get("ROLE_HELPERS", 267630620367257601)) rockstars = 458226413825294336 core_developers = 587606783669829632 + events_lead = 778361735739998228 class Tokens(NamedTuple): -- cgit v1.2.3 From b13667cfc261ec43daad6fd592d5b952f73997fe Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Mon, 30 Nov 2020 01:18:40 +0100 Subject: Remove now redundant advent_of_code_staff constant We're no longer going to use a two-channel setup for this event, as we don't want to split the event community into two, staff and non-staff. --- bot/constants.py | 1 - bot/exts/christmas/advent_of_code/_cog.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index fc9929ec..e459ed21 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -76,7 +76,6 @@ class Branding: class Channels(NamedTuple): admins = 365960823622991872 advent_of_code = int(environ.get("AOC_CHANNEL_ID", 780818162836439041)) - advent_of_code_staff = int(environ.get("AOC_STAFF_CHANNEL_ID", 778646502641500181)) announcements = int(environ.get("CHANNEL_ANNOUNCEMENTS", 354619224620138496)) big_brother_logs = 468507907357409333 bot = 267659945086812160 diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 1a6715bb..388d0592 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -24,7 +24,7 @@ AOC_REQUEST_HEADER = {"user-agent": "PythonDiscord AoC Event Bot"} EST = timezone("EST") COUNTDOWN_STEP = 60 * 5 -AOC_WHITELIST = WHITELISTED_CHANNELS + (Channels.advent_of_code, Channels.advent_of_code_staff) +AOC_WHITELIST = WHITELISTED_CHANNELS + (Channels.advent_of_code,) def is_in_advent() -> bool: -- cgit v1.2.3 From 5ce12af9d9f48042b0ebb7ef215e3253bcc418bd Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Mon, 30 Nov 2020 01:20:19 +0100 Subject: Set correct channel ID as default for AoC channel --- 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 e459ed21..00d75a3f 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -75,7 +75,7 @@ class Branding: class Channels(NamedTuple): admins = 365960823622991872 - advent_of_code = int(environ.get("AOC_CHANNEL_ID", 780818162836439041)) + advent_of_code = int(environ.get("AOC_CHANNEL_ID", 782715290437943306)) announcements = int(environ.get("CHANNEL_ANNOUNCEMENTS", 354619224620138496)) big_brother_logs = 468507907357409333 bot = 267659945086812160 -- cgit v1.2.3 From c352c80cf97620e715ee55184b54d1609312c76b Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Mon, 30 Nov 2020 01:38:11 +0100 Subject: Fix docstrings and add a few explanatory comments --- bot/constants.py | 4 ++-- bot/exts/christmas/advent_of_code/__init__.py | 2 +- bot/exts/christmas/advent_of_code/_cog.py | 4 ++-- bot/exts/christmas/advent_of_code/_helpers.py | 3 +++ 4 files changed, 8 insertions(+), 5 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 00d75a3f..cb5a91cc 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -40,8 +40,8 @@ def _parse_aoc_leaderboard_env() -> Dict[str, AdventOfCodeLeaderboard]: Parse the environment variable containing leaderboard information. A leaderboard should be specified in the format `id,session,join_code`, - without the backticks. If more than leaderboard needs to be added to the - constants, separate the individual leaderboards with `::`. + without the backticks. If more than one leaderboard needs to be added to + the constant, separate the individual leaderboards with `::`. Example ENV: `id1,session1,join_code1::id2,session2,join_code2` """ diff --git a/bot/exts/christmas/advent_of_code/__init__.py b/bot/exts/christmas/advent_of_code/__init__.py index 20ac5ab9..3c521168 100644 --- a/bot/exts/christmas/advent_of_code/__init__.py +++ b/bot/exts/christmas/advent_of_code/__init__.py @@ -2,7 +2,7 @@ from bot.bot import Bot def setup(bot: Bot) -> None: - """Advent of Code Cog load.""" + """Set up the Advent of Code extension.""" # Import the Cog at runtime to prevent side effects like defining # RedisCache instances too early. from ._cog import AdventOfCode diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 388d0592..19baca93 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -230,7 +230,7 @@ class AdventOfCode(commands.Cog): @adventofcode_group.command(name="join", aliases=("j",), brief="Learn how to join the leaderboard (via DM)") @override_in_channel(AOC_WHITELIST) async def join_leaderboard(self, ctx: commands.Context) -> None: - """DM the user the information for joining the PyDis AoC private leaderboard.""" + """DM the user the information for joining the Python Discord leaderboard.""" author = ctx.message.author log.info(f"{author.name} ({author.id}) has requested a PyDis AoC leaderboard code") @@ -284,7 +284,7 @@ class AdventOfCode(commands.Cog): @adventofcode_group.command( name="stats", aliases=("dailystats", "ds"), - brief="Get daily statistics for the PyDis private leaderboard" + brief="Get daily statistics for the Python Discord leaderboard" ) @override_in_channel(AOC_WHITELIST) async def private_leaderboard_daily_stats(self, ctx: commands.Context) -> None: diff --git a/bot/exts/christmas/advent_of_code/_helpers.py b/bot/exts/christmas/advent_of_code/_helpers.py index 8b85bf5d..57aad54d 100644 --- a/bot/exts/christmas/advent_of_code/_helpers.py +++ b/bot/exts/christmas/advent_of_code/_helpers.py @@ -102,10 +102,13 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict: sorted(leaderboard.items(), key=lambda t: t[1]["score"], reverse=True) ) + # Create summary stats for the stars completed for each day of the event. daily_stats = {} for day in range(1, 26): star_one = len(star_results.get((day, 1), [])) star_two = len(star_results.get((day, 1), [])) + # By using a dictionary instead of namedtuple here, we can serialize + # this data to JSON in order to cache it in Redis. daily_stats[day] = {"star_one": star_one, "star_two": star_two} return {"daily_stats": daily_stats, "leaderboard": sorted_leaderboard} -- cgit v1.2.3 From b0e30c21f0638a0b45096a01a00327acee51b46d Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Mon, 30 Nov 2020 13:50:34 +0100 Subject: Remove constants replaced by AOC_LEADERBOARDS There were still two constants left over that were no longer used after the rewrite. I've removed them. --- bot/constants.py | 3 --- 1 file changed, 3 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index cb5a91cc..292a242a 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -232,9 +232,6 @@ class Roles(NamedTuple): class Tokens(NamedTuple): giphy = environ.get("GIPHY_TOKEN") - # Public AoC cookies in environment must be in the same order as AdventOfCode.leaderboard_public_ids - aoc_public_session_cookies = environ.get("AOC_PUBLIC_SESSION_COOKIES", "").split(",") - aoc_staff_session_cookie = environ.get("AOC_STAFF_SESSION_COOKIE") omdb = environ.get("OMDB_API_KEY") youtube = environ.get("YOUTUBE_API_KEY") tmdb = environ.get("TMDB_API_KEY") -- cgit v1.2.3 From 210c564e1b6823617cb4f64ff5e33031dc61d487 Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Tue, 1 Dec 2020 18:30:12 +0100 Subject: Add support for ignoring scores from specific days I've added support for ignoring scores from specific days. A list of days to ignore can be provided using the environment variable `AOC_IGNORED_DAYS` as a comma-separated list. This example would ignore day 1 and day 23: AOC_IGNORED_DAYS=1,23 I've also added a helper function to sort the leaderboard not only on the achieved score, but also on the number of stars an individual has completed. --- bot/constants.py | 1 + bot/exts/christmas/advent_of_code/_helpers.py | 19 ++++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 292a242a..e313e086 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -63,6 +63,7 @@ class AdventOfCode: staff_leaderboard_id = environ.get("AOC_STAFF_LEADERBOARD_ID", "") # Other Advent of Code constants + ignored_days = [day for day in environ.get("AOC_IGNORED_DAYS", "").split(",")] leaderboard_displayed_members = 10 leaderboard_cache_expiry_seconds = 1800 year = int(environ.get("AOC_YEAR", datetime.utcnow().year)) diff --git a/bot/exts/christmas/advent_of_code/_helpers.py b/bot/exts/christmas/advent_of_code/_helpers.py index 72c1ce20..e84348cb 100644 --- a/bot/exts/christmas/advent_of_code/_helpers.py +++ b/bot/exts/christmas/advent_of_code/_helpers.py @@ -53,6 +53,17 @@ EST = pytz.timezone("EST") _StarResult = collections.namedtuple("StarResult", "name completion_time") +def leaderboard_sorting_function(entry: typing.Tuple[str, dict]) -> typing.Tuple[int, int]: + """ + Provide a sorting value for our leaderboard. + + The leaderboard is sorted primarily on the score someone has received and + secondary on the number of stars someone has completed. + """ + result = entry[1] + return result["score"], result["star_2_count"] + result["star_1_count"] + + def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict: """ Parse the leaderboard data received from the AoC website. @@ -98,13 +109,15 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict: # participants per star, we can compute the rank-based scores each participant # should get for that star. max_score = len(leaderboard) - for star in star_results.values(): - for rank, star_result in enumerate(sorted(star, key=operator.itemgetter(1))): + for(day, _star), results in star_results.items(): + if day in AdventOfCode.ignored_days: + continue + for rank, star_result in enumerate(sorted(results, key=operator.itemgetter(1))): leaderboard[star_result.name]["score"] += max_score - rank # Since dictionaries now retain insertion order, let's use that sorted_leaderboard = dict( - sorted(leaderboard.items(), key=lambda t: t[1]["score"], reverse=True) + sorted(leaderboard.items(), key=leaderboard_sorting_function, reverse=True) ) # Create summary stats for the stars completed for each day of the event. -- cgit v1.2.3 From d4c8c0f7184e5d494136cc2b7fc670e8ab7a8f93 Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Wed, 2 Dec 2020 00:22:55 +0100 Subject: Update docstrings and fix grammar in comments I've updated some docstrings to include more information about the inner workings of some of the functions. In addition, I've also slightly reformulated some block comments to improve their grammar. Kaizen change: There was a redundant list comprehension in the Advent of Code section of the constants. I've removed it. --- bot/constants.py | 2 +- bot/exts/christmas/advent_of_code/_cog.py | 4 ++-- bot/exts/christmas/advent_of_code/_helpers.py | 24 +++++++++++++++++------- 3 files changed, 20 insertions(+), 10 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index e313e086..c696b202 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -63,7 +63,7 @@ class AdventOfCode: staff_leaderboard_id = environ.get("AOC_STAFF_LEADERBOARD_ID", "") # Other Advent of Code constants - ignored_days = [day for day in environ.get("AOC_IGNORED_DAYS", "").split(",")] + ignored_days = environ.get("AOC_IGNORED_DAYS", "").split(",") leaderboard_displayed_members = 10 leaderboard_cache_expiry_seconds = 1800 year = int(environ.get("AOC_YEAR", datetime.utcnow().year)) diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 2f60e512..29dcc3cf 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -35,8 +35,8 @@ class AdventOfCode(commands.Cog): self.countdown_task = None self.status_task = None - countdown_coro = _helpers.day_countdown(self.bot) - self.countdown_task = self.bot.loop.create_task(countdown_coro) + announcement_coro = _helpers.new_puzzle_announcement(self.bot) + self.new_puzzle_announcement_task = self.bot.loop.create_task(announcement_coro) status_coro = _helpers.countdown_status(self.bot) self.status_task = self.bot.loop.create_task(status_coro) diff --git a/bot/exts/christmas/advent_of_code/_helpers.py b/bot/exts/christmas/advent_of_code/_helpers.py index c75f47fa..7a6d873e 100644 --- a/bot/exts/christmas/advent_of_code/_helpers.py +++ b/bot/exts/christmas/advent_of_code/_helpers.py @@ -374,9 +374,16 @@ async def wait_for_advent_of_code(*, hours_before: int = 1) -> None: """ Wait for the Advent of Code event to start. - This function returns `hours_before` (default: 1) before the Advent of Code + This function returns `hours_before` (default: 1) the Advent of Code actually starts. This allows functions to schedule and execute code that needs to run before the event starts. + + If the event has already started, this function returns immediately. + + Note: The "next Advent of Code" is determined based on the current value + of the `AOC_YEAR` environment variable. This allows callers to exit early + if we're already past the Advent of Code edition the bot is currently + configured for. """ start = datetime.datetime(AdventOfCode.year, 12, 1, 0, 0, 0, tzinfo=EST) target = start - datetime.timedelta(hours=hours_before) @@ -449,12 +456,13 @@ async def countdown_status(bot: Bot) -> None: await asyncio.sleep(delay) -async def day_countdown(bot: Bot) -> None: +async def new_puzzle_announcement(bot: Bot) -> None: """ - Calculate the number of seconds left until the next day of Advent. + Announce the release of a new Advent of Code puzzle. - Once we have calculated this we should then sleep that number and when the time is reached, ping - the Advent of Code role notifying them that the new challenge is ready. + This background task hibernates until just before the Advent of Code starts + and will then start announcing puzzles as they are published. After the + event has finished, this task will terminate. """ # We wake up one hour before the event starts to prepare the announcement # of the release of the first puzzle. @@ -483,8 +491,10 @@ async def day_countdown(bot: Bot) -> None: log.trace("Started puzzle notification loop.") tomorrow, time_left = time_left_to_est_midnight() - # Use fractional `total_seconds` to wake up very close to our target, with - # padding of 0.1 seconds to ensure that we actually pass midnight. + # Use `total_seconds` to get the time left in fractional seconds This + # should wake us up very close to the target. As a safe guard, the sleep + # duration is padded with 0.1 second to make sure we wake up after + # midnight. sleep_seconds = time_left.total_seconds() + 0.1 log.trace(f"The puzzle notification task will sleep for {sleep_seconds} seconds") await asyncio.sleep(sleep_seconds) -- cgit v1.2.3 From 1aad543a8d4b3c7317fe98937144591d85ad3330 Mon Sep 17 00:00:00 2001 From: Sebastiaan Zeeff Date: Sat, 5 Dec 2020 00:21:04 +0100 Subject: Support a fallback session cookie in constants To mitigate problems due to expiring session cookies, I'm currently in the process of adding support for a fallback cookie. Basically, my Advent of Code account is a member of *all* leaderboards, which means that my cookie can be used to fetch all leaderboards as well. As my session cookie should not expire until after the event, it should not give us any issues. However, to avoid issues with issuing too many requests from one session, we should still make sure to set individual session values regardless of the mitigation. --- bot/constants.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index e313e086..9e6db7a6 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -1,3 +1,4 @@ +import dataclasses import enum import logging from datetime import datetime @@ -29,11 +30,27 @@ __all__ = ( log = logging.getLogger(__name__) -class AdventOfCodeLeaderboard(NamedTuple): +@dataclasses.dataclass +class AdventOfCodeLeaderboard: id: str - session: str + _session: str join_code: str + # If we notice that the session for this board expired, we set + # this attribute to `True`. We will emit a Sentry error so we + # can handle it, but, in the meantime, we'll try using the + # fallback session to make sure the commands still work. + use_fallback_session: bool = False + + @property + def session(self) -> str: + """Return either the actual `session` cookie or the fallback cookie.""" + if self.use_fallback_session: + log.info(f"Returning fallback cookie for board `{self.id}`.") + return AdventOfCode.fallback_session + + return self._session + def _parse_aoc_leaderboard_env() -> Dict[str, AdventOfCodeLeaderboard]: """ @@ -61,6 +78,7 @@ class AdventOfCode: # Information for the several leaderboards we have leaderboards = _parse_aoc_leaderboard_env() staff_leaderboard_id = environ.get("AOC_STAFF_LEADERBOARD_ID", "") + fallback_session = environ.get("AOC_FALLBACK_SESSION", "") # Other Advent of Code constants ignored_days = [day for day in environ.get("AOC_IGNORED_DAYS", "").split(",")] -- cgit v1.2.3 From d884c21e8ae2bd82370b11621230d7172cb098a3 Mon Sep 17 00:00:00 2001 From: janine9vn Date: Wed, 2 Dec 2020 09:28:32 -0500 Subject: Disallow .aoc commands in primary aoc channel Commands like `.aoc leaderboard` and `.aoc stats` proved to be spammy in the main advent of code channel. An aoc_commands channel has been added for aoc commands and this update prohibits aoc commands from being used in the primary aoc channel and adds the comands channel to the whitelist. This also specifically allows the less spammier commands: join, subscribe, unsubscribe, and countdown in the primary channel to foster discussion though. --- bot/constants.py | 1 + bot/exts/christmas/advent_of_code/_cog.py | 10 +++++----- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 9e6db7a6..5dc42462 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -95,6 +95,7 @@ class Branding: class Channels(NamedTuple): admins = 365960823622991872 advent_of_code = int(environ.get("AOC_CHANNEL_ID", 782715290437943306)) + advent_of_code_commands = int(environ.get("AOC_COMMANDS_CHANNEL_ID", 783503267849437205)) announcements = int(environ.get("CHANNEL_ANNOUNCEMENTS", 354619224620138496)) big_brother_logs = 468507907357409333 bot = 267659945086812160 diff --git a/bot/exts/christmas/advent_of_code/_cog.py b/bot/exts/christmas/advent_of_code/_cog.py index 0bcd9f42..fad13f23 100644 --- a/bot/exts/christmas/advent_of_code/_cog.py +++ b/bot/exts/christmas/advent_of_code/_cog.py @@ -21,7 +21,7 @@ AOC_REQUEST_HEADER = {"user-agent": "PythonDiscord AoC Event Bot"} COUNTDOWN_STEP = 60 * 5 -AOC_WHITELIST = WHITELISTED_CHANNELS + (Channels.advent_of_code,) +AOC_WHITELIST = WHITELISTED_CHANNELS + (Channels.advent_of_code_commands,) async def countdown_status(bot: commands.Bot) -> None: @@ -139,7 +139,7 @@ class AdventOfCode(commands.Cog): aliases=("sub", "notifications", "notify", "notifs"), brief="Notifications for new days" ) - @override_in_channel(AOC_WHITELIST) + @override_in_channel(AOC_WHITELIST + (Channels.advent_of_code)) async def aoc_subscribe(self, ctx: commands.Context) -> None: """Assign the role for notifications about new days being ready.""" current_year = datetime.now().year @@ -160,7 +160,7 @@ class AdventOfCode(commands.Cog): @in_month(Month.DECEMBER) @adventofcode_group.command(name="unsubscribe", aliases=("unsub",), brief="Notifications for new days") - @override_in_channel(AOC_WHITELIST) + @override_in_channel(AOC_WHITELIST + Channels.advent_of_code) async def aoc_unsubscribe(self, ctx: commands.Context) -> None: """Remove the role for notifications about new days being ready.""" role = ctx.guild.get_role(AocConfig.role_id) @@ -172,7 +172,7 @@ class AdventOfCode(commands.Cog): await ctx.send("Hey, you don't even get any notifications about new Advent of Code tasks currently anyway.") @adventofcode_group.command(name="countdown", aliases=("count", "c"), brief="Return time left until next day") - @override_in_channel(AOC_WHITELIST) + @override_in_channel(AOC_WHITELIST + (Channels.advent_of_code)) async def aoc_countdown(self, ctx: commands.Context) -> None: """Return time left until next day.""" if not _helpers.is_in_advent(): @@ -207,7 +207,7 @@ class AdventOfCode(commands.Cog): await ctx.send("", embed=self.cached_about_aoc) @adventofcode_group.command(name="join", aliases=("j",), brief="Learn how to join the leaderboard (via DM)") - @override_in_channel(AOC_WHITELIST) + @override_in_channel(AOC_WHITELIST + (Channels.advent_of_code)) async def join_leaderboard(self, ctx: commands.Context) -> None: """DM the user the information for joining the Python Discord leaderboard.""" current_year = datetime.now().year -- cgit v1.2.3 From 0ca1c0b55ea5d07694dc53d4f4856cbcddb35a8f Mon Sep 17 00:00:00 2001 From: janine9vn Date: Fri, 11 Dec 2020 19:30:23 -0500 Subject: Change Default AoC Commands Channel Changes the default value of the advent_of_code_commands constant to be the same channel ID as sir-lancebot-commands. If no AoC commands channel is set in the .env file, it'll re-direct people to sir-lancebot-commands instead. --- 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 5dc42462..a58801f7 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -95,7 +95,7 @@ class Branding: class Channels(NamedTuple): admins = 365960823622991872 advent_of_code = int(environ.get("AOC_CHANNEL_ID", 782715290437943306)) - advent_of_code_commands = int(environ.get("AOC_COMMANDS_CHANNEL_ID", 783503267849437205)) + advent_of_code_commands = int(environ.get("AOC_COMMANDS_CHANNEL_ID", 607247579608121354)) announcements = int(environ.get("CHANNEL_ANNOUNCEMENTS", 354619224620138496)) big_brother_logs = 468507907357409333 bot = 267659945086812160 -- cgit v1.2.3 From 7d3180c91d65f959a8374167edd22486c1175ca7 Mon Sep 17 00:00:00 2001 From: ks129 <45097959+ks129@users.noreply.github.com> Date: Sat, 19 Dec 2020 19:18:45 +0200 Subject: Add Git SHA as constant --- bot/constants.py | 2 ++ 1 file changed, 2 insertions(+) (limited to 'bot/constants.py') diff --git a/bot/constants.py b/bot/constants.py index 5e97fa2d..0325066a 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -313,6 +313,8 @@ WHITELISTED_CHANNELS = ( Channels.sprint_documentation, ) +GIT_SHA = environ.get("GIT_SHA", "foobar") + # Bot replies ERROR_REPLIES = [ "Please don't do that.", -- cgit v1.2.3