Skip to content

Commit

Permalink
Simplify use of Settings module
Browse files Browse the repository at this point in the history
  • Loading branch information
lexicalunit committed May 8, 2024
1 parent e77a5f2 commit 9719f64
Show file tree
Hide file tree
Showing 37 changed files with 148 additions and 133 deletions.
4 changes: 3 additions & 1 deletion CHANGELOG.md
Expand Up @@ -15,6 +15,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

- Publish platform linux/amd64.
- Reduce complexity of Dockerfile.
- Reduce proliferation of Settings objects.
- Use __slots__ in some classes to reduce memory usage.

## [v11.0.2](https://github.com/lexicalunit/spellbot/releases/tag/v11.0.2) - 2024-05-02

Expand Down Expand Up @@ -776,7 +778,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

### Added

- Allow "award" level to **remove** a role, rather than give a role to a player.
- Allow "award" level to __remove__ a role, rather than give a role to a player.

## [v7.10.11](https://github.com/lexicalunit/spellbot/releases/tag/v7.10.11) - 2021-12-30

Expand Down
17 changes: 3 additions & 14 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 11 additions & 12 deletions src/spellbot/actions/admin_action.py
Expand Up @@ -16,7 +16,7 @@
safe_update_embed_origin,
)
from spellbot.services import GamesService
from spellbot.settings import Settings
from spellbot.settings import settings
from spellbot.utils import EMBED_DESCRIPTION_SIZE_LIMIT
from spellbot.views import SetupView

Expand Down Expand Up @@ -50,7 +50,6 @@ def award_line(award: GuildAwardDict) -> str:
class AdminAction(BaseAction):
def __init__(self, bot: SpellBot, interaction: discord.Interaction) -> None:
super().__init__(bot, interaction)
self.settings = Settings()

async def _report_failure(self) -> None:
await safe_send_channel(
Expand All @@ -65,8 +64,8 @@ async def _build_channels_embeds(self) -> list[Embed]: # noqa: C901

def new_embed() -> Embed:
embed = Embed(title=f"Configuration for channels in {guild['name']}")
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.color = discord.Color(self.settings.INFO_EMBED_COLOR)
embed.set_thumbnail(url=settings.ICO_URL)
embed.color = discord.Color(settings.INFO_EMBED_COLOR)
return embed

def update_channel_settings(
Expand Down Expand Up @@ -136,8 +135,8 @@ async def _build_awards_embeds(self) -> list[Embed]:

def new_embed() -> Embed:
embed = Embed(title=f"SpellBot Player Awards for {guild['name']}")
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.color = discord.Color(self.settings.INFO_EMBED_COLOR)
embed.set_thumbnail(url=settings.ICO_URL)
embed.color = discord.Color(settings.INFO_EMBED_COLOR)
return embed

has_at_least_one_award = False
Expand Down Expand Up @@ -172,7 +171,7 @@ def new_embed() -> Embed:
async def _build_setup_embed(self) -> Embed:
guild = await self.services.guilds.to_dict()
embed = Embed(title=f"SpellBot Setup for {guild['name']}")
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.set_thumbnail(url=settings.ICO_URL)
description = (
"These are the current settings for SpellBot on this server."
" Please use the buttons below, as well as the `/set` commands,"
Expand All @@ -195,7 +194,7 @@ async def _build_setup_embed(self) -> Embed:
name="Create Voice Channels",
value=humanize_bool(guild["voice_create"]),
)
embed.color = discord.Color(self.settings.INFO_EMBED_COLOR)
embed.color = discord.Color(settings.INFO_EMBED_COLOR)
return embed

async def forget_channel(self, channel_str: str) -> None:
Expand Down Expand Up @@ -291,22 +290,22 @@ async def award_add(
)

embed = Embed()
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.set_thumbnail(url=settings.ICO_URL)
embed.set_author(name="Award added!")
line = award_line(award)
description = f"{line}\n\nYou can view all awards with the `/set awards` command."
embed.description = description
embed.color = self.settings.INFO_EMBED_COLOR
embed.color = settings.INFO_EMBED_COLOR
await safe_send_channel(self.interaction, embed=embed, ephemeral=True)

async def award_delete(self, guild_award_id: int) -> None:
await self.services.guilds.award_delete(guild_award_id)
embed = Embed()
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.set_thumbnail(url=settings.ICO_URL)
embed.set_author(name="Award deleted!")
description = "You can view all awards with the `/set awards` command."
embed.description = description
embed.color = self.settings.INFO_EMBED_COLOR
embed.color = settings.INFO_EMBED_COLOR
await safe_send_channel(self.interaction, embed=embed, ephemeral=True)

async def set_motd(self, message: str | None = None) -> None:
Expand Down
3 changes: 1 addition & 2 deletions src/spellbot/actions/block_action.py
Expand Up @@ -6,7 +6,7 @@
import discord

from spellbot.operations import safe_send_channel
from spellbot.settings import Settings
from spellbot.settings import settings
from spellbot.utils import EMBED_DESCRIPTION_SIZE_LIMIT

from .base_action import BaseAction
Expand Down Expand Up @@ -55,7 +55,6 @@ async def unblock(self, target: discord.User | discord.Member) -> None:
await self.execute(target, ActionType.UNBLOCK)

async def blocked(self, page: int) -> None:
settings = Settings()
blocklist = await self.services.users.blocklist(self.interaction.user.id)
embed = discord.Embed(title="Blocked Users")
embed.set_thumbnail(url=settings.ICO_URL)
Expand Down
15 changes: 7 additions & 8 deletions src/spellbot/actions/lfg_action.py
Expand Up @@ -23,7 +23,7 @@
safe_update_embed_origin,
save_create_channel_invite,
)
from spellbot.settings import Settings
from spellbot.settings import settings
from spellbot.views import BaseView, PendingGameView, StartedGameView, StartedGameViewWithConfirm

from .base_action import BaseAction
Expand All @@ -39,7 +39,6 @@
class LookingForGameAction(BaseAction):
def __init__(self, bot: SpellBot, interaction: discord.Interaction) -> None:
super().__init__(bot, interaction)
self.settings = Settings()

@tracer.wrap()
async def get_friends(self, friends: str | None = None) -> str:
Expand Down Expand Up @@ -196,7 +195,7 @@ async def execute( # noqa: C901
await safe_followup_channel(self.interaction, msg)
return None

if await self.services.users.pending_games() + 1 > self.settings.MAX_PENDING_GAMES:
if await self.services.users.pending_games() + 1 > settings.MAX_PENDING_GAMES:
msg = "You're in too many pending games to join another one at this time."
if origin:
return await safe_send_user(self.interaction.user, msg)
Expand Down Expand Up @@ -576,14 +575,14 @@ async def _handle_embed_creation( # noqa: C901,PLR0912
async def _reply_found_embed(self) -> None:
assert self.guild is not None
embed = discord.Embed()
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.set_thumbnail(url=settings.ICO_URL)
game_data = await self.services.games.to_dict()
links = game_data["jump_links"]
link = links[self.guild.id]
format = game_data["format"]
embed.set_author(name=f"I found a {GameFormat(format)} game for you!")
embed.description = f"You can [jump to the game post]({link}) to see it!"
embed.color = self.settings.INFO_EMBED_COLOR
embed.color = settings.INFO_EMBED_COLOR
await safe_followup_channel(self.interaction, embed=embed)

@tracer.wrap()
Expand Down Expand Up @@ -643,7 +642,7 @@ async def _handle_watched_players(self, player_xids: list[int]) -> None:
assert self.interaction.guild
mod_role: discord.Role | None = None
for role in self.interaction.guild.roles:
if role.name.startswith(self.settings.MOD_PREFIX):
if role.name.startswith(settings.MOD_PREFIX):
mod_role = role
break

Expand All @@ -657,9 +656,9 @@ async def _handle_watched_players(self, player_xids: list[int]) -> None:
data = await self.services.games.to_dict()

embed = discord.Embed()
embed.set_thumbnail(url=self.settings.ICO_URL)
embed.set_thumbnail(url=settings.ICO_URL)
embed.set_author(name="Watched user(s) joined a game")
embed.color = self.settings.INFO_EMBED_COLOR
embed.color = settings.INFO_EMBED_COLOR
description = ""
for jump_link in data["jump_links"].values():
description += f"[⇤ Jump to the game post]({jump_link})\n"
Expand Down
3 changes: 1 addition & 2 deletions src/spellbot/actions/record_action.py
Expand Up @@ -12,7 +12,7 @@
safe_send_channel,
safe_update_embed,
)
from spellbot.settings import Settings
from spellbot.settings import settings

from .base_action import BaseAction

Expand All @@ -23,7 +23,6 @@
from spellbot.models import GameDict, PlayDict

logger = logging.getLogger(__name__)
settings = Settings()


class RecordAction(BaseAction):
Expand Down
5 changes: 1 addition & 4 deletions src/spellbot/actions/score_action.py
Expand Up @@ -5,7 +5,7 @@
import discord

from spellbot.operations import safe_send_channel
from spellbot.settings import Settings
from spellbot.settings import settings

from .base_action import BaseAction

Expand All @@ -21,7 +21,6 @@ async def execute(self, target: discord.Member | discord.User) -> None:
target_xid = target.id
count = await self.services.plays.count(target_xid, self.interaction.guild_id)

settings = Settings()
embed = discord.Embed()
embed.set_thumbnail(url=settings.ICO_URL)
embed.set_author(name=f"Record of games played on {guild_name}")
Expand All @@ -40,7 +39,6 @@ async def history(self) -> None:
channel_name = self.interaction.channel.name # type: ignore
channel_xid = self.interaction.channel.id

settings = Settings()
embed = discord.Embed()
embed.set_thumbnail(url=settings.ICO_URL)
embed.set_author(name=f"Recent games played in {channel_name}")
Expand All @@ -62,7 +60,6 @@ async def top(self, monthly: bool, ago: int) -> None:
assert guild_xid is not None
data = await self.services.plays.top_records(guild_xid, channel_xid, monthly, ago)

settings = Settings()
embed = discord.Embed()
embed.set_thumbnail(url=settings.ICO_URL)
range_s = f"{ago} months ago" if ago else "this month" if monthly else "all time"
Expand Down
3 changes: 1 addition & 2 deletions src/spellbot/actions/tasks_action.py
Expand Up @@ -22,7 +22,7 @@
safe_update_embed,
)
from spellbot.services import GamesService, ServicesRegistry
from spellbot.settings import Settings
from spellbot.settings import settings

from .base_action import handle_exception

Expand All @@ -34,7 +34,6 @@
from spellbot import SpellBot
from spellbot.models import GameDict

settings = Settings()
logger = logging.getLogger(__name__)


Expand Down
4 changes: 1 addition & 3 deletions src/spellbot/actions/watch_action.py
Expand Up @@ -8,7 +8,7 @@

from spellbot.operations import safe_send_channel
from spellbot.services import WatchesService
from spellbot.settings import Settings
from spellbot.settings import settings
from spellbot.utils import EMBED_DESCRIPTION_SIZE_LIMIT

from .base_action import BaseAction
Expand Down Expand Up @@ -110,8 +110,6 @@ async def unwatch(
await self.execute(ActionType.UNWATCH, target=target, id=xid)

async def get_watched_embeds(self) -> list[Embed]:
settings = Settings()

def new_embed() -> Embed:
assert self.interaction.guild
embed = Embed(title="List of watched players on this server")
Expand Down
6 changes: 2 additions & 4 deletions src/spellbot/cli.py
Expand Up @@ -14,6 +14,7 @@
from .environment import running_in_pytest
from .logs import configure_logging
from .metrics import no_metrics
from .settings import settings

# load .env environment variables as early as possible
if not running_in_pytest(): # pragma: no cover
Expand Down Expand Up @@ -78,10 +79,7 @@ def main(
if dev:
hupper.start_reloader("spellbot.main")

from .settings import Settings

# Ensure that configure_logging() is called as early as possible
settings = Settings()
level = log_level if log_level is not None else (getenv("LOG_LEVEL") or "INFO")
configure_logging(level)

Expand Down Expand Up @@ -119,7 +117,7 @@ def main(

loop = asyncio.new_event_loop()
loop.set_debug(debug)
launch_web_server(settings, loop, port or settings.PORT)
launch_web_server(loop, port or settings.PORT)
loop.run_forever()
else:
from .client import build_bot
Expand Down
5 changes: 2 additions & 3 deletions src/spellbot/client.py
Expand Up @@ -14,7 +14,7 @@
from .metrics import setup_ignored_errors, setup_metrics
from .operations import safe_delete_message
from .services import ChannelsService, GamesService, GuildsService, VerifiesService
from .settings import Settings
from .settings import settings
from .spelltable import generate_link
from .utils import user_can_moderate

Expand All @@ -30,7 +30,6 @@ def __init__(
mock_games: bool = False,
create_connection: bool = True,
) -> None:
self.settings = Settings()
intents = discord.Intents().default()
intents.members = True
intents.message_content = True
Expand All @@ -40,7 +39,7 @@ def __init__(
command_prefix="!",
help_command=None,
intents=intents,
application_id=self.settings.BOT_APPLICATION_ID,
application_id=settings.BOT_APPLICATION_ID,
)
self.mock_games = mock_games
self.create_connection = create_connection
Expand Down

0 comments on commit 9719f64

Please sign in to comment.