Skip to content

Commit

Permalink
[ThreadOpener] finishing touches
Browse files Browse the repository at this point in the history
  • Loading branch information
japandotorg committed Oct 14, 2023
1 parent e40b138 commit 992bcb4
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 7 deletions.
25 changes: 25 additions & 0 deletions threadopener/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,36 @@
SOFTWARE.
"""

import re
import json
from pathlib import Path
from typing import Pattern, Match, Optional

from redbot.core.bot import Red
from redbot.core.errors import CogLoadError

from .core import ThreadOpener
from .utils import validate_tagscriptengine

VERSION_RE: Pattern[str] = re.compile(r"TagScript==(\d\.\d\.\d)")

with open(Path(__file__).parent / "info.json") as f:
data = json.load(f)

tse_version = None
for requirement in data.get("requirements", []):
match: Optional[Match[str]] = VERSION_RE.search(requirement)
if match:
tse_version = match.group(1)
break

if not tse_version:
raise CogLoadError(
"Failed to find TagScriptEngine version number. Please report this to the cog author."
)


async def setup(bot: Red) -> None:
await validate_tagscriptengine(bot, tse_version)
cog = ThreadOpener(bot)
await bot.add_cog(cog)
2 changes: 2 additions & 0 deletions threadopener/_tagscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import discord
import TagScriptEngine as tse
from redbot.core.bot import Red
from redbot.core import commands
from redbot.core.utils.chat_formatting import humanize_number

Expand Down Expand Up @@ -50,6 +51,7 @@ def __init__(self, limit: int, length: int):
)


@final
class TagscriptConverter(commands.Converter[str]):
async def convert(self, ctx: commands.Context, argument: str) -> str:
try:
Expand Down
8 changes: 6 additions & 2 deletions threadopener/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

import discord
from redbot.core import commands
from redbot.core.utils.chat_formatting import humanize_list
from redbot.core.utils.chat_formatting import humanize_list, box

from ._tagscript import TagscriptConverter
from .abc import MixinMeta
Expand Down Expand Up @@ -176,9 +176,13 @@ async def _show_settings(self, ctx: commands.Context):
embed.add_field(
name="Auto Archive Duration",
value=data["auto_archive_duration"],
)
embed.add_field(
name=f"Message Toggle: {data['message_toggle']}",
value=box(str(data["message"]), lang="json"),
inline=False,
)
embed.add_field(name="Slowmode Delay", value=data["slowmode_delay"], inline=False)
embed.add_field(name="Slowmode Delay", value=data["slowmode_delay"])
if active_channels:
embed.add_field(
name="Active Channels",
Expand Down
12 changes: 7 additions & 5 deletions threadopener/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
import TagScriptEngine as tse
from redbot.core import Config, commands
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import humanize_list
from redbot.core.utils.chat_formatting import humanize_list, warning

from ._tagscript import (
TAGSCRIPT_LIMIT,
Expand Down Expand Up @@ -65,8 +65,8 @@ def __init__(self, bot: Red) -> None:
force_registration=True,
)
default_guilds: Dict[str, Optional[Union[List[int], Any]]] = {
"toggle": False,
"channels": [],
"toggle": False,
"slowmode_delay": None,
"message_toggle": False,
"message": thread_message,
Expand Down Expand Up @@ -149,18 +149,20 @@ async def on_message(self, message: discord.Message) -> None:
)
except discord.Forbidden:
await message.channel.send(
"I do not have permissions to create threads in this channel."
warning("I do not have permissions to create threads in this channel.")
)
except discord.HTTPException:
await message.channel.send(
"Something went wrong while creating threads in this channel."
warning("Something went wrong while creating threads in this channel.")
)
log.exception(
f"Something went wrong while creating threads in {message.channel.id}.",
exc_info=True,
)
except ValueError:
await message.channel.send("This guild does not have a guild info attached to it")
await message.channel.send(
warning("This server does not have a guild info attached to it")
)
log.exception(
f"Guild {message.guild.id} does not have a guild info attached to it.",
exc_info=True,
Expand Down
41 changes: 41 additions & 0 deletions threadopener/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from importlib import reload

from redbot.core.bot import Red
from redbot.core.errors import CogLoadError


async def validate_tagscriptengine(bot: Red, tse_version: str, *, reloaded: bool = False):
try:
import TagScriptEngine as tse
except ImportError as exc:
raise CogLoadError(
"The ThreadOpener cog failed to install TagScriptEngine. Reinstall the cog and restart your "
"bot. If it continues to fail to load, contact the cog author."
) from exc

commands = [
"`pip(3) uninstall -y TagScriptEngine`",
"`pip(3) uninstall -y TagScript`",
f"`pip(3) install TagScript=={tse_version}`",
]
commands = "\n".join(commands)

message = (
"The ThreadOpener cog attempted to install TagScriptEngine, but the version installed "
"is outdated. Shut down your bot, then in shell in your venv, run the following "
f"commands:\n{commands}\nAfter running these commands, restart your bot and reload "
"Tags. If it continues to fail to load, contact the cog author."
)

if not hasattr(tse, "VersionInfo"):
if not reloaded:
reload(tse)
await validate_tagscriptengine(bot, tse_version, reloaded=True)
return

await bot.send_to_owners(message)
raise CogLoadError(message)

if tse.version_info < tse.VersionInfo.from_str(tse_version):
await bot.send_to_owners(message)
raise CogLoadError(message)

0 comments on commit 992bcb4

Please sign in to comment.