Skip to content

Commit

Permalink
Use enums in config, resolve #2821
Browse files Browse the repository at this point in the history
  • Loading branch information
fourjr committed Nov 10, 2020
1 parent 038fc61 commit 1b5d993
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 39 deletions.
6 changes: 3 additions & 3 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from core.clients import ApiClient, PluginDatabaseClient, MongoDBClient
from core.config import ConfigManager
from core.utils import human_join, match_title, normalize_alias
from core.models import PermissionLevel, SafeFormatter, getLogger, configure_logging
from core.models import DMDisabled, PermissionLevel, SafeFormatter, getLogger, configure_logging
from core.thread import ThreadManager
from core.time import human_timedelta

Expand Down Expand Up @@ -770,7 +770,7 @@ async def process_dm_modmail(self, message: discord.Message) -> None:
)
return

if self.config["dm_disabled"] >= 1:
if self.config["dm_disabled"] in (DMDisabled.NEW_THREADS, DMDisabled.ALL_THREADS):
embed = discord.Embed(
title=self.config["disabled_new_thread_title"],
color=self.error_color,
Expand All @@ -787,7 +787,7 @@ async def process_dm_modmail(self, message: discord.Message) -> None:

thread = await self.threads.create(message.author, message=message)
else:
if self.config["dm_disabled"] == 2:
if self.config["dm_disabled"] == DMDisabled.ALL_THREADS:
embed = discord.Embed(
title=self.config["disabled_current_thread_title"],
color=self.error_color,
Expand Down
20 changes: 10 additions & 10 deletions cogs/modmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from natural.date import duration

from core import checks
from core.models import PermissionLevel, SimilarCategoryConverter, getLogger
from core.models import DMDisabled, PermissionLevel, SimilarCategoryConverter, getLogger
from core.paginator import EmbedPaginatorSession
from core.thread import Thread
from core.time import UserFriendlyTime, human_timedelta
Expand Down Expand Up @@ -964,7 +964,7 @@ async def contact(

else:
thread = await self.bot.threads.create(user, creator=ctx.author, category=category)
if self.bot.config["dm_disabled"] >= 1:
if self.bot.config["dm_disabled"] in (DMDisabled.NEW_THREADS, DMDisabled.ALL_THREADS):
logger.info("Contacting user %s when Modmail DM is disabled.", user)

if not silent:
Expand Down Expand Up @@ -1450,8 +1450,8 @@ async def enable(self, ctx):
color=self.bot.main_color,
)

if self.bot.config["dm_disabled"] != 0:
self.bot.config["dm_disabled"] = 0
if self.bot.config["dm_disabled"] != DMDisabled.NONE:
self.bot.config["dm_disabled"] = DMDisabled.NONE
await self.bot.config.update()

return await ctx.send(embed=embed)
Expand Down Expand Up @@ -1481,8 +1481,8 @@ async def disable_new(self, ctx):
description="Modmail will not create any new threads.",
color=self.bot.main_color,
)
if self.bot.config["dm_disabled"] < 1:
self.bot.config["dm_disabled"] = 1
if self.bot.config["dm_disabled"] < DMDisabled.NEW_THREADS:
self.bot.config["dm_disabled"] = DMDisabled.NEW_THREADS
await self.bot.config.update()

return await ctx.send(embed=embed)
Expand All @@ -1501,8 +1501,8 @@ async def disable_all(self, ctx):
color=self.bot.main_color,
)

if self.bot.config["dm_disabled"] != 2:
self.bot.config["dm_disabled"] = 2
if self.bot.config["dm_disabled"] != DMDisabled.ALL_THREADS:
self.bot.config["dm_disabled"] = DMDisabled.ALL_THREADS
await self.bot.config.update()

return await ctx.send(embed=embed)
Expand All @@ -1514,13 +1514,13 @@ async def isenable(self, ctx):
Check if the DM functionalities of Modmail is enabled.
"""

if self.bot.config["dm_disabled"] == 1:
if self.bot.config["dm_disabled"] == DMDisabled.NEW_THREADS:
embed = discord.Embed(
title="New Threads Disabled",
description="Modmail is not creating new threads.",
color=self.bot.error_color,
)
elif self.bot.config["dm_disabled"] == 2:
elif self.bot.config["dm_disabled"] == DMDisabled.ALL_THREADS:
embed = discord.Embed(
title="All DM Disabled",
description="Modmail is not accepting any DM messages for new and existing threads.",
Expand Down
43 changes: 18 additions & 25 deletions core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from discord.ext.commands import BadArgument

from core._color_data import ALL_COLORS
from core.models import InvalidConfigError, Default, getLogger
from core.models import DMDisabled, InvalidConfigError, Default, getLogger
from core.time import UserFriendlyTimeSync
from core.utils import strtobool

Expand Down Expand Up @@ -98,9 +98,7 @@ class ConfigManager:
"activity_message": "",
"activity_type": None,
"status": None,
# dm_disabled 0 = none, 1 = new threads, 2 = all threads
# TODO: use enum
"dm_disabled": 0,
"dm_disabled": DMDisabled.NONE,
"oauth_whitelist": [],
# moderation
"blocked": {},
Expand Down Expand Up @@ -165,7 +163,11 @@ class ConfigManager:
"enable_eval",
}

special_types = {"status", "activity_type"}
enums = {
"dm_disabled": DMDisabled,
"status": discord.Status,
"activity_type": discord.ActivityType
}

defaults = {**public_keys, **private_keys, **protected_keys}
all_keys = set(defaults.keys())
Expand Down Expand Up @@ -277,26 +279,15 @@ def get(self, key: str, convert=True) -> typing.Any:
value = strtobool(value)
except ValueError:
value = self.remove(key)

elif key in self.special_types:
elif key in self.enums:
if value is None:
return None

if key == "status":
try:
# noinspection PyArgumentList
value = discord.Status(value)
except ValueError:
logger.warning("Invalid status %s.", value)
value = self.remove(key)

elif key == "activity_type":
try:
# noinspection PyArgumentList
value = discord.ActivityType(value)
except ValueError:
logger.warning("Invalid activity %s.", value)
value = self.remove(key)
try:
value = self.enums[key](value)
except ValueError:
logger.warning("Invalid %s %s.", key, value)
value = self.remove(key)

return value

Expand Down Expand Up @@ -355,8 +346,10 @@ def set(self, key: str, item: typing.Any, convert=True) -> None:
except ValueError:
raise InvalidConfigError("Must be a yes/no value.")

# elif key in self.special_types:
# if key == "status":
elif key in self.enums:
if isinstance(item, self.enums[key]):
# value is an enum type
item = item.value

return self.__setitem__(key, item)

Expand Down
6 changes: 6 additions & 0 deletions core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,3 +257,9 @@ async def publish(self):

async def ack(self):
return


class DMDisabled(IntEnum):
NONE = 0
NEW_THREADS = 1
ALL_THREADS = 2
2 changes: 1 addition & 1 deletion core/thread.py
Original file line number Diff line number Diff line change
Expand Up @@ -896,7 +896,7 @@ async def send(
except Exception as e:
logger.warning("Cannot delete message: %s.", e)

if from_mod and self.bot.config["dm_disabled"] == 2 and destination != self.channel:
if from_mod and self.bot.config["dm_disabled"] == DMDisabled.ALL_THREADS and destination != self.channel:
logger.info("Sending a message to %s when DM disabled is set.", self.recipient)

try:
Expand Down

0 comments on commit 1b5d993

Please sign in to comment.