diff --git a/README.md b/README.md
index bbed778..6353ac8 100644
--- a/README.md
+++ b/README.md
@@ -37,6 +37,7 @@ that contains a better embed (that allows to play videos directly in Discord, fo
TBIB, and any custom websites of your choice
- Posts translation
- Disable by website, channel, member, role or keyword
+- Fixed links removable along with the original message, or with a ❌ reaction
- Highly customizable behavior and appearance
- Multiple languages supported
- Modern interface for settings
@@ -87,7 +88,7 @@ It is also listed on the websites (please leave an upvote/review if you like the
| Message content | Fixed links in hypertext with original and author links in hypertext | Fixed links | Author + full message content with fixed links in hypertext | - Fixed link
- Fixed link in hypertext
- Medias as attachment
- Custom (premium) | Empty | Fixed link in hypertext | Medias as attachment | Author's mention + message content with fixed links | Message content with fixed links | Author's mention + message content with fixed links in hypertext | Video as attachment and post content if video, else fixed link in hypertext + original and message links in hypertext (one per message) | Full message content with fixed links | Fixed links in invisible hypertext | - Full message content with fixed links
- Full message content + medias as attachment | Author's mention + message content with first link fixed + original | - Empty (bot - one per link)
- Full message content (fake user - one per link) | Author's mention + message content with first link fixed + original | Empty (one per link) | Fixed links | Empty | Fixed links | Full message content with fixed links | Full message content with fixed links | Author mention + Full message content with fixed links on one line | First fixed link | First link fixed in authors' name hypertext + message content, without the first link | Empty |
| Message embed | - Normal view
- Direct view (following provider)
- Gallery view (following provider)
- Text view (following provider) | Normal view | Normal view | - Normal view
- Direct view | One per post, one per video, one per quote | Normal view | One per post, one per quote | Normal view | - Normal view- Direct view (Twitter) | Normal view | Normal view (if non-video) | Normal view | Normal view | Normal view | Normal view | Normal view | Normal view | Normal view | Normal view | Normal view (only first link) | Direct view | Normal view | Normal view | Normal view | Normal view | Normal view | Video direct view (only the last link) |
| Respect markdown | ✓ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ |
-| Possibility for op to delete the bot's post | ✕ | ✕ | ✓ | ✓ | ✓ | ✕ | ✓ | ✕ | ✕ | ✓ | ✕ | ✕ | ✕ | ✓ | ✓ | ✓ | ✓ | ✕ | ✕ | ✕ | ✓ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ |
+| Possibility for op to delete the bot's post | ✓ | ✕ | ✓ | ✓ | ✓ | ✕ | ✓ | ✕ | ✕ | ✓ | ✕ | ✕ | ✕ | ✓ | ✓ | ✓ | ✓ | ✕ | ✕ | ✕ | ✓ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ |
| Other features and notes | - Custom websites
- Posts translation
- Embed customization
- Advanced filters rules management
- Troubleshoot system
- Respond to bots/webhooks (premium)
- Open links in app on click
- Silent messages | ✕ | ✕ | - Website interface
- Download system
- Repond to bots/webhooks (premium) | ✕ | - Transcription
- Translation | - Posts translation
- Download videos
- Tweet save
- Customization
- React to other bots | ✕ | - Custom websites
- Posts translation (Twitter)- Can respond to bots | ✕ | ✕ | ✕ | - Customise provider/fixer for each website | - Posts translation
- Respond to bots/webhooks
- Open links in app on click
- Automatic NSFW spoilering
- Channel transfer
- Buttons customization | - Reply to itself in an infinite loop | - Channel-specific settings
- Posts translation
- Troubleshoot system
- Respond to bots/webhooks (premium)
- Custom avatar
- NSFW detection & spoiler
- URLs modificators (macros)
- Embed customization | ✕ | ✕ | - Download videos | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | ✕ | - Download
- Save on cloud |
| Languages | en, fr, pl, ru, es-ES, vi, zh-CN, zh-TW, pt-BR, ja ([contribute to add more!](https://crowdin.com/project/fixtweetbot)) | en, ja | en | en | en | en | ja, en | en | en | ja, en | en | - | en | en, es-ES, vi, zh-CN, zh-TW, nl | - | en | - | en | - | en | en | en | - | - | - | - | en |
| Open-sourced | ~ Source-available | ✓ | ✕ | ✕ | ✕ | ✕ | ✓ | ✕ | ✓ | ✕ | ✕ | ~ Source-available | ~ Source-available | ✓ | ✕ | ✕ | ✕ | ✕ | ✓ | ~ Source-available | ✕ | ✓ | ~ Source-available | ✓ | ~ Source-available | ~ Source-available | ✕ |
diff --git a/cogs/commands.py b/cogs/commands.py
index b4e3c50..536497a 100644
--- a/cogs/commands.py
+++ b/cogs/commands.py
@@ -41,62 +41,64 @@ async def settings(self, i: discore.Interaction):
async def about(self, i: discore.Interaction):
entrypoint_context.set(f"command about {{interaction={i!r}}}")
await Event.buff_cr({'name': 'command_about'})
- embed = discore.Embed(
- title=t('about.name'),
- description=t('about.description'))
- discore.set_embed_footer(self.bot, embed)
- embed.add_field(
- name=t('about.help.name'),
- value=t('about.help.value',
- settings_command='/' + t('settings.command.name'),
- support_link=discore.config.support_link,
- troubleshooting_section=t('settings.troubleshooting.name')),
- inline=False
- )
- embed.add_field(
- name=t('about.premium.name'),
- value=t(f'about.premium.{str(bool(is_premium(i))).lower()}'),
- inline=False)
- embed.add_field(
- name=t('about.links.name'),
- value=t('about.links.value',
- invite_link=discore.config.invite_link.format(id=self.bot.application_id),
- topgg_link=discore.config.topgg_link.format(id=self.bot.user.id),
- repo_link=discore.config.repo_link,
- translation_link=discore.config.translation_link,
- credits_link=discore.config.repo_link + "/blob/v" + discore.config.version + "/README.md#credits",
- support_link=discore.config.support_link),
- inline=False)
- view = discore.ui.View()
+ links = discore.ui.ActionRow()
if not is_premium(i) and is_sku():
- view.add_item(discore.ui.Button(
+ links.add_item(discore.ui.Button(
style=discore.ButtonStyle.premium,
sku_id=discore.config.sku
))
- view.add_item(discore.ui.Button(
+ links.add_item(discore.ui.Button(
style=discore.ButtonStyle.link,
label=t('about.source'),
url=discore.config.repo_link,
emoji=discore.PartialEmoji.from_str(discore.config.emoji.github)
))
- view.add_item(discore.ui.Button(
+ links.add_item(discore.ui.Button(
style=discore.ButtonStyle.link,
label=t('about.invite'),
url=discore.config.invite_link.format(id=self.bot.application_id),
emoji=discore.PartialEmoji.from_str(discore.config.emoji.add)
))
- view.add_item(discore.ui.Button(
+ links.add_item(discore.ui.Button(
style=discore.ButtonStyle.link,
label=t('about.support'),
url=discore.config.support_link,
emoji=discore.PartialEmoji.from_str(discore.config.emoji.discord)
))
+ view = discore.ui.LayoutView()
+ view.add_item(discore.ui.Container(
+ discore.ui.Section(
+ f"## {t('about.name')}\n{t('about.description')}",
+ accessory=discore.ui.Thumbnail(self.bot.user.display_avatar.url)),
+ discore.ui.Separator(),
+ discore.ui.TextDisplay(
+ f"### {t('about.help.name')}\n" + t(
+ 'about.help.value',
+ settings_command='/' + t('settings.command.name'),
+ support_link=discore.config.support_link,
+ troubleshooting_section=t('settings.troubleshooting.name'))),
+ discore.ui.TextDisplay(
+ f"### {t('about.premium.name')}\n" + t(f'about.premium.{str(bool(is_premium(i))).lower()}')),
+ discore.ui.TextDisplay(
+ f"### {t('about.links.name')}\n" + t(
+ 'about.links.value',
+ invite_link=discore.config.invite_link.format(id=self.bot.application_id),
+ topgg_link=discore.config.topgg_link.format(id=self.bot.user.id),
+ repo_link=discore.config.repo_link,
+ translation_link=discore.config.translation_link,
+ credits_link=discore.config.repo_link + "/blob/v" + discore.config.version + "/README.md#credits",
+ support_link=discore.config.support_link)),
+ discore.ui.Separator(),
+ links,
+ discore.ui.TextDisplay(footer(self.bot)),
+ accent_color=discore.config.color or None
+ ))
# Discord API sometimes returns incorrect error code, in this case 404 Unknown interaction when interaction
# is actually found and the message has been sent.
# Even if the interaction is really not found, there's not much we can do (as the interaction is lost),
# so in both cases we just ignore the error.
try:
- await i.response.send_message(embed=embed, view=view)
+ await i.response.send_message(view=view, allowed_mentions=discore.AllowedMentions.none())
except discore.NotFound:
pass
diff --git a/cogs/developer.py b/cogs/developer.py
index 20cbe3f..cdedb22 100644
--- a/cogs/developer.py
+++ b/cogs/developer.py
@@ -56,7 +56,7 @@ class Developer(discore.Cog,
@discore.app_commands.guilds(*dev_guilds)
async def update(self, i: discore.Interaction) -> None:
await i.response.defer(thinking=True)
- await i.followup.send(execute_command("git pull"))
+ await i.edit_original_response(view=utils.notice(execute_command("git pull")))
@discore.app_commands.command(
name="requirements",
@@ -65,7 +65,8 @@ async def update(self, i: discore.Interaction) -> None:
@discore.app_commands.guilds(*dev_guilds)
async def requirements(self, i: discore.Interaction) -> None:
await i.response.defer(thinking=True)
- await i.followup.send(execute_command("pip install --force-reinstall -r requirements.txt", timeout=120))
+ await i.edit_original_response(
+ view=utils.notice(execute_command("pip install --force-reinstall -r requirements.txt", timeout=120)))
@discore.app_commands.command(
name="shell",
@@ -74,7 +75,7 @@ async def requirements(self, i: discore.Interaction) -> None:
@discore.app_commands.guilds(*dev_guilds)
async def shell(self, i: discore.Interaction, command: str, timeout: int | None = 30) -> None:
await i.response.defer(thinking=True)
- await i.followup.send(execute_command(command, timeout=timeout))
+ await i.edit_original_response(view=utils.notice(execute_command(command, timeout=timeout)))
@discore.app_commands.command(
name="exec",
@@ -98,10 +99,10 @@ async def _exec(self, i: discore.Interaction, code: str) -> None:
exec(function, env)
res = repr(await env["_ex"](self, i))
except Exception as e:
- await i.followup.send(f"```{type(e).__name__}: {e}```")
+ await i.edit_original_response(view=utils.notice(f"```{type(e).__name__}: {e}```"))
return
- await i.followup.send(
- f"```py\n{discore.sanitize(res, limit=1990)}\n```")
+ await i.edit_original_response(
+ view=utils.notice(f"```py\n{discore.sanitize(res, limit=1990)}\n```"))
@discore.app_commands.command(
name="log",
@@ -112,7 +113,7 @@ async def log(self, i: discore.Interaction) -> None:
with open(discore.config.log.file, encoding='utf-8') as f:
logs = f.read()
await i.response.send_message(
- f"```\n{discore.sanitize(logs, 1992, replace_newline=False, crop_at_end=False)}\n```")
+ view=utils.notice(f"```\n{discore.sanitize(logs, 1992, replace_newline=False, crop_at_end=False)}\n```"))
@discore.app_commands.command(
name="runtime",
@@ -137,64 +138,38 @@ async def runtime(self, i: discore.Interaction) -> None:
except asyncio.TimeoutError:
pass
- e = discore.Embed(
- title="Runtime",
- color=discore.config.color or None)
- e.add_field(
- name="Bot Version",
- value=discore.config.version)
- e.add_field(
- name="Bot commit",
- value='`' + subprocess.check_output('git log -1 --pretty=format:"%h"', shell=True, encoding='utf-8') + '`')
- e.add_field(
- name="Bot commit date",
- value="")
- e.add_field(
- name="Discore Version",
- value=metadata.version('discore'))
- e.add_field(
- name="Discore commit",
- value=f"`{discore_commit[:7]}`")
- e.add_field(
- name="Discore commit date",
- value=f"" if commit_date else "Unknown")
- e.add_field(
- name="Discord.py Version",
- value=metadata.version('discord.py'))
- e.add_field(
- name="Python Version",
- value='.'.join(map(str, sys.version_info[:3])))
- e.add_field(
- name="Platform",
- value=sys.platform)
- e.add_field(
- name="Start time",
- value=f""
- if self.bot.start_time
- else f" (init)")
- e.add_field(
- name="Uptime",
- value=f""
- if self.bot.start_time
- else f" (init)")
- e.add_field(
- name="Current time",
- value=f"")
- e.add_field(
- name="Memory usage",
- value=f"{p.memory_info().rss / 1024 / 1024:.2f} MB")
- e.add_field(
- name="CPU usage",
- value=f"{p.cpu_percent():.2f} %")
- e.set_footer(
- text=self.bot.user.name + (
- f" | ver. {discore.config.version}" if discore.config.version else ""),
- icon_url=self.bot.user.display_avatar.url
- )
- discore.set_embed_footer(self.bot, e)
-
- await i.response.send_message(embed=e)
+ fields = {
+ "Bot Version": discore.config.version,
+ "Bot commit":
+ '`' + subprocess.check_output('git log -1 --pretty=format:"%h"', shell=True, encoding='utf-8') + '`',
+ "Bot commit date":
+ "",
+ "Discore Version": metadata.version('discore'),
+ "Discore commit": f"`{discore_commit[:7]}`",
+ "Discore commit date": f"" if commit_date else "Unknown",
+ "Discord.py Version": metadata.version('discord.py'),
+ "Python Version": '.'.join(map(str, sys.version_info[:3])),
+ "Platform": sys.platform,
+ "Start time":
+ f""
+ if self.bot.start_time
+ else f" (init)",
+ "Uptime":
+ f""
+ if self.bot.start_time
+ else f" (init)",
+ "Current time": f"",
+ "Memory usage": f"{p.memory_info().rss / 1024 / 1024:.2f} MB",
+ "CPU usage": f"{p.cpu_percent():.2f} %",
+ }
+ view = discore.ui.LayoutView()
+ view.add_item(discore.ui.Container(
+ discore.ui.TextDisplay("## Runtime\n" + "\n".join(f"**{name}:** {value}" for name, value in fields.items())),
+ discore.ui.TextDisplay(utils.footer(self.bot)),
+ accent_color=discore.config.color or None
+ ))
+
+ await i.response.send_message(view=view)
@discore.app_commands.command(
@@ -204,11 +179,11 @@ async def runtime(self, i: discore.Interaction) -> None:
@discore.app_commands.guilds(*dev_guilds)
async def add_premium(self, i: discore.Interaction) -> None:
if not discore.config.sku:
- await i.response.send_message("SKU not set")
+ await i.response.send_message(view=utils.notice("SKU not set"))
return
await self.bot.create_entitlement(
sku=discore.Object(id=discore.config.sku), owner=i.guild, owner_type=discore.EntitlementOwnerType.guild)
- await i.response.send_message("Premium enabled")
+ await i.response.send_message(view=utils.notice("Premium enabled"))
@discore.app_commands.command(
name="remove_premium",
@@ -217,12 +192,13 @@ async def add_premium(self, i: discore.Interaction) -> None:
@discore.app_commands.guilds(*dev_guilds)
async def remove_premium(self, i: discore.Interaction) -> None:
if not discore.config.sku:
- await i.response.send_message("SKU not set")
+ await i.response.send_message(view=utils.notice("SKU not set"))
return
for entitlement in i.entitlements:
if entitlement.sku_id == discore.config.sku:
try:
await entitlement.delete()
except:
- await i.response.send_message("Failed to disable premium")
- await i.response.send_message("Premium disabled")
+ await i.response.send_message(view=utils.notice("Failed to disable premium"))
+ return
+ await i.response.send_message(view=utils.notice("Premium disabled"))
diff --git a/cogs/link_fix.py b/cogs/link_fix.py
index d5bf6de..d14d707 100644
--- a/cogs/link_fix.py
+++ b/cogs/link_fix.py
@@ -3,6 +3,7 @@
"""
import re
+from dataclasses import dataclass, field
from typing import List
import discord_markdown_ast_parser as dmap
from discord_markdown_ast_parser.parser import NodeType
@@ -23,6 +24,77 @@
_logger = logging.getLogger(__name__)
+@dataclass
+class Fix:
+ """The fixed messages sent for a message, kept to be able to delete them afterwards."""
+
+ original_id: int
+ guild_id: int
+ author_id: int
+ messages: list[discore.Message] = field(default_factory=list)
+ original_deleted: bool = False
+
+
+# The fixes, by the id of their original message and of each of their fixed messages.
+# They are kept in memory and capped: the links fixed before a restart (or about 10 000 fixes ago) can't be removed
+# automatically anymore. They would have to be stored in the database if it ever matters.
+MAX_TRACKED_MESSAGES = 20_000
+tracked_fixes: dict[int, Fix] = {}
+
+# The reaction that deletes a fixed message
+DELETE_EMOJI = '❌'
+
+
+def track_original(original_message: discore.Message) -> Fix:
+ """
+ Remember a message that is about to be fixed, to know if it gets deleted from then on.
+
+ :param original_message: the message that is about to be fixed
+ :return: the fix of the message
+ """
+
+ fix = tracked_fixes.setdefault(
+ original_message.id, Fix(original_message.id, original_message.guild.id, original_message.author.id))
+ while len(tracked_fixes) > MAX_TRACKED_MESSAGES:
+ del tracked_fixes[next(iter(tracked_fixes))]
+ return fix
+
+
+def track_fix(fix: Fix, message: discore.Message) -> None:
+ """
+ Remember a fixed message, to be able to delete it afterwards.
+
+ :param fix: the fix the message belongs to
+ :param message: the message containing the fixed links
+ """
+
+ fix.messages.append(message)
+ tracked_fixes[message.id] = fix
+
+
+async def on_message_deleted(message_id: int) -> None:
+ """
+ Delete the fixed messages of a deleted message, if the guild asks for it.
+
+ :param message_id: the id of the deleted message
+ """
+
+ fix = tracked_fixes.pop(message_id, None)
+ if fix is None:
+ return
+ if message_id != fix.original_id:
+ # A fixed message has been deleted, not the original one
+ fix.messages[:] = [message for message in fix.messages if message.id != message_id]
+ return
+ fix.original_deleted = True
+ if Guild.find(fix.guild_id).delete_with_original:
+ messages = list(fix.messages)
+ fix.messages.clear()
+ for message in messages:
+ tracked_fixes.pop(message.id, None)
+ await asyncio.gather(*(safe_send_coro(m.delete(), not_found=True, forbidden=True) for m in messages))
+
+
def get_website(guild: Guild, url: str, spoiler: bool = False) -> WebsiteLink | None:
"""
Get the website of the URL.
@@ -136,11 +208,14 @@ async def fix_embeds(
or (isinstance(channel, discore.Thread) and (channel.locked or channel.archived))):
return
+ # Registered before anything is sent, as the original message can be deleted while its links are being fixed
+ fix = track_original(original_message) if guild.delete_with_original or guild.delete_on_reaction else None
+
async def render_and_send() -> tuple[list[tuple[str, list[WebsiteLink]]], dict[discore.Message, list[WebsiteLink]]]:
rendered_links = [link for link in links if await link.render()]
if not rendered_links:
return [], {}
- return await send_fixed_links(rendered_links, guild, original_message)
+ return await send_fixed_links(rendered_links, guild, original_message, fix)
if guild.reply_as_original_author_replica:
not_sent, messages = await render_and_send()
@@ -148,10 +223,17 @@ async def render_and_send() -> tuple[list[tuple[str, list[WebsiteLink]]], dict[d
async with Typing(channel):
not_sent, messages = await render_and_send()
+ if fix is not None and not fix.messages:
+ tracked_fixes.pop(original_message.id, None)
+
to_delete = []
+ to_react = []
if messages:
results = await asyncio.gather(*(wait_for_embed(msg) for msg in messages))
- to_delete = [msg for msg, has_embed in zip(messages, results) if not has_embed]
+ # A fixed message deleted in the meantime (along with its original message, or on a reaction) didn't fail
+ to_delete = [
+ msg for msg, has_embed in zip(messages, results)
+ if not has_embed and not (fix is not None and msg not in fix.messages)]
if to_delete:
err_data = [
@@ -166,20 +248,28 @@ async def render_and_send() -> tuple[list[tuple[str, list[WebsiteLink]]], dict[d
{'name': 'fixed_link', 'data': await _format_link_data(link, original_message)}
for link in msg_links])
+ if (guild.delete_on_reaction and guild.add_delete_reaction
+ and permissions.add_reactions and permissions.read_message_history):
+ # Added once the fixed messages are known to stay, so that the reaction only has to be clicked
+ to_react = [msg for msg in fix.messages if msg not in to_delete]
+
if not_sent:
err_data = [
{'name': 'fixed_link_not_sent', 'data': await _format_link_data(link, original_message, msg_content, include_sensitive=True)}
for msg_content, links in not_sent for link in links]
_logger.warning("Message(s) failed to send: %s", repr(err_data))
await Event.buff_cr(*err_data)
+ tasks = [safe_send_coro(msg.add_reaction(DELETE_EMOJI), not_found=True, forbidden=True) for msg in to_react]
if messages and not to_delete and not not_sent:
- await edit_original_message(guild, original_message, permissions)
+ tasks.append(edit_original_message(guild, original_message, permissions))
+ await asyncio.gather(*tasks)
async def send_fixed_links(
rendered_links: list[WebsiteLink],
guild: Guild,
- original_message: discore.Message
+ original_message: discore.Message,
+ fix: Fix | None = None
) -> tuple[list[tuple[str, list[WebsiteLink]]], dict[discore.Message, list[WebsiteLink]]]:
"""
Send the fixed links to the channel, according to the guild settings and its context
@@ -199,9 +289,14 @@ async def send_fixed_links(
:param rendered_links: the rendered WebsiteLink objects to send
:param guild: the guild associated with the context
:param original_message: the original message associated with the context to reply to
+ :param fix: the fix of the original message, if its fixed messages have to be remembered
:return: a tuple containing the list of links that failed to be sent, and a dict of the messages sent with their corresponding links
"""
+ def abandoned() -> bool:
+ """Whether the original message was deleted meanwhile, and its fixed links have to go with it"""
+ return fix is not None and fix.original_deleted and guild.delete_with_original
+
messages_sent: dict[discore.Message, list[WebsiteLink]] = {}
links_failed: list[tuple[str, list[WebsiteLink]]] = []
@@ -210,6 +305,8 @@ async def send_fixed_links(
webhook = await get_or_create_webhook(original_message.channel) if use_original_author_replica else None
for i, (message_content, links_in_group) in enumerate(grouped):
+ if abandoned():
+ break
if webhook is not None:
coro = webhook_send(webhook, original_message, message_content, guild.reply_silently)
elif i == 0 and guild.reply_to_message:
@@ -219,7 +316,12 @@ async def send_fixed_links(
sent, msg = await safe_send_coro(coro, invalid_form_body='Embed size exceeds maximum size', forbidden=True)
if sent and msg:
+ if abandoned():
+ await safe_send_coro(msg.delete(), not_found=True, forbidden=True)
+ break
messages_sent[msg] = links_in_group
+ if fix is not None:
+ track_fix(fix, msg)
else:
links_failed.append((message_content, links_in_group))
@@ -316,6 +418,8 @@ async def edit_original_message(guild: Guild, message: discore.Message, permissi
return
if guild.original_message == OriginalMessage.DELETE:
+ # Deleting the original message ourselves must not delete its fixed links
+ tracked_fixes.pop(message.id, None)
await safe_send_coro(message.delete(), not_found=True, forbidden=True)
else:
await wait_for_embed(message)
@@ -373,3 +477,41 @@ async def on_message(self, message: discore.Message) -> None:
return
await fix_embeds(message, guild, links)
+
+ @discore.Cog.listener()
+ async def on_raw_message_delete(self, payload: discore.RawMessageDeleteEvent) -> None:
+ if payload.message_id in tracked_fixes:
+ entrypoint_context.set(f"event on_raw_message_delete {{payload={payload!r}}}")
+ await on_message_deleted(payload.message_id)
+
+ @discore.Cog.listener()
+ async def on_raw_bulk_message_delete(self, payload: discore.RawBulkMessageDeleteEvent) -> None:
+ for message_id in payload.message_ids & tracked_fixes.keys():
+ entrypoint_context.set(f"event on_raw_bulk_message_delete {{payload={payload!r}}}")
+ await on_message_deleted(message_id)
+
+ @discore.Cog.listener()
+ async def on_raw_reaction_add(self, payload: discore.RawReactionActionEvent) -> None:
+ """
+ Delete a fixed message when its original author, or a member who can manage messages, reacts to it with ❌,
+ if the guild asks for it
+
+ :param payload: The reaction that was added
+ """
+
+ fix = tracked_fixes.get(payload.message_id)
+ if fix is None or payload.emoji.name != DELETE_EMOJI or payload.message_id == fix.original_id:
+ return
+ if payload.member is None or payload.member.bot:
+ return
+ entrypoint_context.set(f"event on_raw_reaction_add {{payload={payload!r}}}")
+ message = next((m for m in fix.messages if m.id == payload.message_id), None)
+ if message is None:
+ return
+ channel = self.bot.get_channel(payload.channel_id)
+ if payload.user_id != fix.author_id and not (
+ channel and channel.permissions_for(payload.member).manage_messages):
+ return
+ if not Guild.find(fix.guild_id).delete_on_reaction:
+ return
+ await safe_send_coro(message.delete(), not_found=True, forbidden=True)
diff --git a/database/migrations/2026_11_11_232918_add_fixed_links_removal.py b/database/migrations/2026_11_11_232918_add_fixed_links_removal.py
new file mode 100644
index 0000000..cc78005
--- /dev/null
+++ b/database/migrations/2026_11_11_232918_add_fixed_links_removal.py
@@ -0,0 +1,23 @@
+"""AddFixedLinksRemoval Migration."""
+
+from masoniteorm.migrations import Migration
+
+
+class AddFixedLinksRemoval(Migration):
+ def up(self):
+ """
+ Run the migrations.
+ """
+ with self.schema.table("guilds") as table:
+ table.boolean("delete_with_original").default(False).after("reply_as_original_author_replica")
+ table.boolean("delete_on_reaction").default(False).after("delete_with_original")
+ table.boolean("add_delete_reaction").default(False).after("delete_on_reaction")
+
+ def down(self):
+ """
+ Revert the migrations.
+ """
+ with self.schema.table("guilds") as table:
+ table.drop_column("delete_with_original")
+ table.drop_column("delete_on_reaction")
+ table.drop_column("add_delete_reaction")
diff --git a/database/models/Guild.py b/database/models/Guild.py
index a4641f7..175e11b 100644
--- a/database/models/Guild.py
+++ b/database/models/Guild.py
@@ -62,6 +62,9 @@ class Guild(DiscordRepresentation):
'reply_to_message': bool,
'reply_silently': bool,
'reply_as_original_author_replica': bool,
+ 'delete_with_original': bool,
+ 'delete_on_reaction': bool,
+ 'add_delete_reaction': bool,
'webhooks': bool,
'original_message': OriginalMessage,
'twitter_view': FxEmbedView,
diff --git a/locales/en-US.yml b/locales/en-US.yml
index 3b04d49..72fce36 100644
--- a/locales/en-US.yml
+++ b/locales/en-US.yml
@@ -58,6 +58,9 @@ settings:
manage_webhooks:
"true": "🟢 `Manage webhooks` permission"
"false": "🔴 Missing `manage webhooks` permission"
+ add_reactions:
+ "true": "🟢 `Add reactions` permission"
+ "false": "🔴 Missing `add reactions` permission"
filters:
button:
toggle:
@@ -85,7 +88,6 @@ settings:
name: "Channels"
description: "Enable/Disable in specific channels"
select: "Select the channel to edit"
- content: "**Enable/Disable %{bot} in %{element}**\n- %{state}\n- %{default_state}%{perms}"
state:
"true": "🟢 Enabled in %{element}%{details}"
"false": "🔴 Disabled in %{element}%{details}"
@@ -93,7 +95,6 @@ settings:
name: "Members"
description: "Enable/Disable for specific members"
select: "Select the member to edit"
- content: "**Enable/Disable %{bot} for %{element}**\n- %{state}\n- %{default_state}"
state:
"true": "🟢 Enabled for %{element}%{details}"
"false": "🔴 Disabled for %{element}%{details}"
@@ -106,7 +107,6 @@ settings:
name: "Roles"
description: "Enable/Disable for specific roles"
select: "Select the role to edit"
- content: "**Enable/Disable %{bot} for %{element}**\n- %{state}\n- %{default_state}\n- %{rule}"
state:
"true": "🟢 Enabled for %{element}%{details}"
"false": "🔴 Disabled for %{element}%{details}"
@@ -150,7 +150,6 @@ settings:
reply_method:
name: "Reply method"
description: "Change the behavior on the reply"
- content: "**Change what to do on the reply**\n- %{state}\n- %{silent}\n- %{replica}%{perms}"
reply:
button:
"true": "Replying"
@@ -182,6 +181,19 @@ settings:
state:
"true": "🟢 Replying to webhooks"
"false": "🔴 Ignoring webhooks"
+ removal:
+ name: "Fixed links removal"
+ description: "Choose when the fixed links are deleted"
+ delete_with_original:
+ "true": "🔗 Deleting the fixed link when the original message is deleted"
+ "false": "🔗 Keeping the fixed link when the original message is deleted"
+ unavailable: "🔗 Not available while the original message is deleted once fixed (the ❌ reaction can be used instead)"
+ delete_on_reaction:
+ "true": "❌ The author, and members with the `Manage messages` permission, can delete a fixed link by reacting to it with ❌"
+ "false": "❌ Reacting to a fixed link with ❌ doesn't delete it"
+ add_delete_reaction:
+ "true": "👆 %{bot} adds the ❌ reaction to the fixed links itself, so that it only has to be clicked"
+ "false": "👆 %{bot} doesn't add the ❌ reaction to the fixed links itself"
original_message:
name: "Original message"
description: "Change the behavior on the original message"
@@ -216,7 +228,9 @@ settings:
description: "Change the different websites settings"
placeholder: "Select a website to edit"
content: "**Change the different websites settings**\n\nSelect a website to edit its settings"
- page_button: "Displaying %{options_count} of %{total_options} websites (page n°%{current_page}/%{total_pages})"
+ page: "Page %{page}/%{pages}"
+ previous_page: "Previous page"
+ next_page: "Next page"
base_website:
description: "Change the %{name} links settings"
content: "**Enable/Disable the %{name} link fix and manage its options**\n%{state}%{view}\n-# Credits: %{credits}"
@@ -262,7 +276,6 @@ settings:
website: "- %{name}: `%{domain}` → `%{fix_domain}`"
selected_website: "- **%{name}: `%{domain}` → `%{fix_domain}`**"
placeholder: "Select the website to edit"
- empty: "No websites registered"
button:
add: "Add website"
edit: "Edit website"
diff --git a/locales/ko.yml b/locales/ko.yml
index 77491de..ab60ce6 100644
--- a/locales/ko.yml
+++ b/locales/ko.yml
@@ -56,6 +56,9 @@ settings:
manage_webhooks:
"true": "🟢 `웹후크 관리하기` 권한"
"false": "🔴 `웹후크 관리하기` 권한 없음"
+ add_reactions:
+ "true": "🟢 `반응 추가하기` 권한"
+ "false": "🔴 `반응 추가하기` 권한 없음"
filters:
button:
toggle:
@@ -83,7 +86,6 @@ settings:
name: "채널"
description: "특정 채널에 대해 활성화/비활성화하기"
select: "수정할 채널을 선택하세요"
- content: "**%{element}에서 %{bot} 활성화/비활성화하기**\n- %{state}\n- %{default_state}%{perms}"
state:
"true": "🟢 %{element}%{details}에서 활성화됨"
"false": "🔴 %{element}%{details}에서 비활성화됨"
@@ -91,7 +93,6 @@ settings:
name: "멤버"
description: "특정 멤버에 대해 활성화/비활성화하기"
select: "수정할 멤버를 선택하세요"
- content: "**%{element}에게 %{bot} 활성화/비활성화하기 **\n- %{state}\n- %{default_state}"
state:
"true": "🟢 %{element}%{details}에 대해 활성화됨"
"false": "🔴 %{element}%{details}에 대해 비활성화됨"
@@ -104,7 +105,6 @@ settings:
name: "역할"
description: "특정 역할에 대해 활성화/비활성화하기"
select: "수정할 역할을 선택하세요."
- content: "**%{element}에 대해 %{bot} 활성화/비활성화하기**\n- %{state}\n- %{default_state}%{rule}"
state:
"true": "🟢 %{element}%{details}에 대해 활성화됨"
"false": "🔴 %{element}%{details}에 대해 비활성화됨"
@@ -148,7 +148,6 @@ settings:
reply_method:
name: "답장 방법"
description: "답장할 때의 동작 변경하기"
- content: "**답장할 때 수행할 작업 변경하기**\n- %{state}\n- %{silent}\n- %{replica}%{perms}"
reply:
button:
"true": "답장"
@@ -180,6 +179,19 @@ settings:
state:
"true": "🟢 웹후크에 답장하기"
"false": "🔴 웹후크 무시하기"
+ removal:
+ name: "수정된 링크 삭제"
+ description: "수정된 링크가 삭제되는 조건 바꾸기"
+ delete_with_original:
+ "true": "🔗 원본 메시지가 삭제되면 수정된 링크도 함께 삭제해요"
+ "false": "🔗 원본 메시지가 삭제되어도 수정된 링크는 그대로 둬요"
+ unavailable: "🔗 수정 후 원본 메시지를 삭제하도록 설정된 동안에는 사용할 수 없어요 (대신 ❌ 반응을 사용할 수 있어요)"
+ delete_on_reaction:
+ "true": "❌ 작성자와 `메시지 관리하기` 권한이 있는 멤버가 수정된 링크에 ❌ 반응을 달면 삭제해요"
+ "false": "❌ 수정된 링크에 ❌ 반응을 달아도 삭제하지 않아요"
+ add_delete_reaction:
+ "true": "👆 %{bot}이(가) 수정된 링크에 ❌ 반응을 미리 달아둬서, 누르기만 하면 돼요"
+ "false": "👆 %{bot}이(가) 수정된 링크에 ❌ 반응을 미리 달아두지 않아요"
original_message:
name: "원본 메시지"
description: "원본 메시지에서의 동작 바꾸기"
@@ -214,6 +226,9 @@ settings:
description: "다른 웹사이트 설정 바꾸기"
placeholder: "수정할 웹사이트를 선택하세요"
content: "**다른 웹사이트 설정 바꾸기**\n\n설정을 수정할 웹사이트를 선택하세요"
+ page: "%{page}/%{pages} 페이지"
+ previous_page: "이전 페이지"
+ next_page: "다음 페이지"
base_website:
description: "%{name} 링크 설정 바꾸기"
content: "**%{name} 링크 수정 활성화/비활성화 및 옵션 바꾸기**\n%{state}%{view}\n-# 기여자: %{credits}"
@@ -259,7 +274,6 @@ settings:
website: "- %{name}: `%{domain}` → `%{fix_domain}`"
selected_website: "- **%{name}: `%{domain}` → `%{fix_domain}`**"
placeholder: "수정할 웹사이트를 선택하세요"
- empty: "등록된 웹사이트가 없어요"
button:
add: "웹사이트 추가하기"
edit: "웹사이트 수정하기"
diff --git a/main.py b/main.py
index c5dab18..0c69324 100644
--- a/main.py
+++ b/main.py
@@ -6,7 +6,7 @@
os.environ['DB_CONFIG_PATH'] = 'database/config.py'
-intents = discore.Intents(guild_messages=True, message_content=True, guilds=True)
+intents = discore.Intents(guild_messages=True, message_content=True, guilds=True, guild_reactions=True)
bot = discore.Bot(help_command=None, intents=intents)
asyncio.run(bot.tree.set_translator(I18nTranslator()))
diff --git a/src/settings.py b/src/settings.py
index bbab89d..12d3061 100644
--- a/src/settings.py
+++ b/src/settings.py
@@ -4,7 +4,6 @@
from __future__ import annotations
import asyncio
-import math
from typing import Type, List, overload, Iterable, Any
import discore.ui.select
@@ -58,17 +57,12 @@ def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: Da
self.ctx: DataElements = ctx
@property
- async def embed(self) -> discore.Embed:
+ def title(self) -> str:
"""
- Build the setting embed
- :return: The embed
+ Build the setting title
+ :return: The title
"""
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}" if self.emoji else t(self.name),
- description=t(self.description)
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
+ return f"{self.emoji} {t(self.name)}" if self.emoji else t(self.name)
@property
async def option(self) -> discore.SelectOption:
@@ -84,12 +78,12 @@ async def option(self) -> discore.SelectOption:
)
@property
- async def items(self) -> List[discore.ui.Item]:
+ async def layout(self) -> List[discore.ui.Item]:
"""
- Build the setting items
- :return: The items
+ Build the setting components (its texts and controls), displayed below its title
+ :return: The components
"""
- return []
+ return [discore.ui.TextDisplay(t(self.description))]
# noinspection PyShadowingBuiltins
@classmethod
@@ -156,11 +150,20 @@ def __init__(
self.lang = self.ctx.guild.lang
@property
- async def embed(self) -> discore.Embed:
+ def title(self) -> str:
+ return f"{self.emoji} {self.name}"
+
+ @property
+ async def layout(self) -> List[discore.ui.Item]:
self.lang = self.ctx.guild.lang if self.is_translation else None
- embed = discore.Embed(
- title=f"{self.emoji} {self.name}",
- description=t(
+ state_switch = discore.ui.Button(
+ style=discore.ButtonStyle.primary if self.state else discore.ButtonStyle.secondary,
+ label=t(f'settings.base_website.button.state.{l(self.state)}'),
+ custom_id=self.id
+ )
+ edit_callback(state_switch, self.view, self.action)
+ items = [discore.ui.Section(
+ t(
f'settings.base_website.content',
name=self.name,
state=t(
@@ -176,22 +179,9 @@ async def embed(self) -> discore.Embed:
+ ' ' + t(f'settings.base_website.view.{self.view_state.name.lower()}.label'))
if self.view_state else '',
credits=t('settings.base_website.credits_separator').join(f"[{p_name}](<{p_url}>)" for p_name, p_url in self.proxies.items())
- )
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
-
- @property
- async def items(self) -> List[discore.ui.Item]:
- items = []
- self.lang = self.ctx.guild.lang if self.is_translation else None
- state_switch = discore.ui.Button(
- style=discore.ButtonStyle.primary if self.state else discore.ButtonStyle.secondary,
- label=t(f'settings.base_website.button.state.{l(self.state)}'),
- custom_id=self.id
- )
- edit_callback(state_switch, self.view, self.action)
- items.append(state_switch)
+ ),
+ accessory=state_switch
+ )]
if self.is_translation:
translation_button = discore.ui.Button(
style=discore.ButtonStyle.primary if self.translation and self.state else discore.ButtonStyle.secondary,
@@ -203,14 +193,13 @@ async def items(self) -> List[discore.ui.Item]:
disabled=not self.state
)
edit_callback(translation_button, self.view, self.translation_action)
- items.append(translation_button)
translation_lang_button = discore.ui.Button(
label=t('settings.base_website.button.translation_lang'),
custom_id=f'{self.id}_translation_lang',
disabled=not (self.translation and self.state)
)
edit_callback(translation_lang_button, self.view, self.translation_lang_action)
- items.append(translation_lang_button)
+ items.append(discore.ui.ActionRow(translation_button, translation_lang_button))
if self.is_view:
view_selector = discore.ui.Select(
options=[
@@ -224,7 +213,7 @@ async def items(self) -> List[discore.ui.Item]:
]
)
edit_callback(view_selector, self.view, self.view_action)
- items.append(view_selector)
+ items.append(discore.ui.ActionRow(view_selector))
return items
@@ -264,37 +253,44 @@ async def option(self) -> discore.SelectOption:
)
-class TranslationModal(discore.ui.Modal):
+class Modal(discore.ui.Modal):
+ """A modal displayed in the language of the user submitting it"""
+
+ async def interaction_check(self, interaction: discore.Interaction) -> bool:
+ # The texts are built from the global locale, which is otherwise only set when a command is invoked
+ discore.set_locale(interaction)
+ return True
+
+
+class TranslationModal(Modal):
def __init__(self, setting: BaseSetting, **kwargs):
"""
Modal for changing the language setting of the guild
:param setting: The setting to change the language for
:param kwargs: Additional keyword arguments for the modal
"""
-
+
super().__init__(
title=t('settings.lang_modal.title'),
timeout=180,
**kwargs
)
self.setting = setting
- # noinspection PyUnresolvedReferences
- self.lang = setting.ctx.guild.lang
self.interaction_lang = setting.interaction.locale.value.split('-')[0]
# noinspection PyUnresolvedReferences
- self.add_item(discore.ui.TextInput(
- label=t('settings.lang_modal.label'),
+ self.lang = discore.ui.TextInput(
placeholder=t('settings.lang_modal.placeholder', lang_iso=self.interaction_lang),
custom_id='lang',
- default=self.lang
- ))
+ default=setting.ctx.guild.lang
+ )
+ self.add_item(discore.ui.Label(text=t('settings.lang_modal.label'), component=self.lang))
async def on_submit(self, interaction: discore.Interaction):
- lang = str(self.children[0])
- if len(lang) != 2:
+ lang = self.lang.value.strip().lower()
+ if len(lang) != 2 or not (lang.isascii() and lang.isalpha()):
# noinspection PyUnresolvedReferences
await interaction.response.send_message(
- t('settings.lang_modal.error', invalid_lang=lang, lang_iso=self.interaction_lang), ephemeral=True, delete_after=10)
+ view=notice(t('settings.lang_modal.error', invalid_lang=lang, lang_iso=self.interaction_lang)), ephemeral=True, delete_after=10)
return
self.setting.ctx.guild.update({'lang': lang})
await self.setting.view.refresh(interaction)
@@ -309,71 +305,6 @@ class EmbedEZBaseSetting(WebsiteBaseSetting):
view_enum = EmbedEzView
-class ClickerSetting(BaseSetting):
- """Represents a clicker setting (for testing purposes)"""
-
- name = 'Clicker'
- id = 'clicker'
- description = 'A simple clicker game'
- emoji = '👆'
-
- def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: DataElements):
- super().__init__(interaction, view, ctx)
- self.counter = 0
-
- @property
- async def embed(self) -> discore.Embed:
- embed = discore.Embed(
- title=f"{self.emoji} {self.name}",
- description=self.description + (
- f'\n**You clicked {self.counter} times**' if self.counter > 0 else ''
- )
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
-
- @property
- async def items(self) -> List[discore.ui.Item]:
- item = discore.ui.Button(
- style=discore.ButtonStyle.primary,
- label=f'{self.name} ({self.counter})',
- custom_id=self.id
- )
- edit_callback(item, self.view, self.action)
- return [item]
-
- async def action(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
- self.counter += 1
- await view.refresh(interaction)
-
-
-class ToggleSetting(BaseSetting):
- """Represents a toggle setting (for testing purposes)"""
-
- name = 'Toggle'
- id = 'toggle'
- description = 'Toggle the setting'
- emoji = '🔄'
-
- def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: DataElements):
- super().__init__(interaction, view, ctx)
- self.state = False
-
- @property
- async def items(self) -> List[discore.ui.Item]:
- item = discore.ui.Button(
- style=discore.ButtonStyle.green if self.state else discore.ButtonStyle.red,
- label=f'{self.name} {"ON" if self.state else "OFF"}',
- custom_id=self.id
- )
- edit_callback(item, self.view, self.action)
- return [item]
-
- async def action(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
- self.state = not self.state
- await view.refresh(interaction)
-
-
class TroubleshootingSetting(BaseSetting):
"""Represents the troubleshooting setting"""
@@ -383,16 +314,7 @@ class TroubleshootingSetting(BaseSetting):
emoji = '🛠️'
@property
- async def embed(self) -> discore.Embed:
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=t('settings.troubleshooting.description')
- )
- embed.add_field(
- name=t('settings.troubleshooting.ping.name'),
- value=t('settings.troubleshooting.ping.value', latency=format(self.bot.latency * 1000, '.0f')),
- inline=False
- )
+ async def layout(self) -> List[discore.ui.Item]:
perms = [
'view_channel',
'send_messages',
@@ -406,11 +328,10 @@ async def embed(self) -> discore.Embed:
perms.append('read_message_history')
if self.ctx.guild.reply_as_original_author_replica:
perms.append('manage_webhooks')
- embed.add_field(
- name=t('settings.troubleshooting.permissions', channel=self.ctx.channel.mention),
- value=format_perms(perms, self.ctx.channel.discord_object, include_label=False, include_valid=True),
- inline=False
- )
+ if self.ctx.guild.delete_on_reaction and self.ctx.guild.add_delete_reaction:
+ perms.append('add_reactions')
+ if 'read_message_history' not in perms:
+ perms.append('read_message_history')
# (id, display_value, state, indented)
options = [
('channels', self.ctx.channel.mention, self.ctx.channel.enabled(self.ctx.guild), False),
@@ -426,94 +347,46 @@ async def embed(self) -> discore.Embed:
('keywords', keyword, self.ctx.guild.keywords_use_allow_list, False)
for keyword in self.ctx.guild.keywords
)
-
- str_options_fields = group_join(
- (
+ # (name, value)
+ fields = [
+ (t('settings.troubleshooting.ping.name'),
+ t('settings.troubleshooting.ping.value', latency=format(self.bot.latency * 1000, '.0f'))),
+ (t('settings.troubleshooting.permissions', channel=self.ctx.channel.mention),
+ format_perms(perms, self.ctx.channel.discord_object, include_label=False, include_valid=True)),
+ (t('settings.troubleshooting.filters'), "\n".join(
(' - ' if indented else '- ') + t(f'settings.{id}.state.{l(state)}',
- **{'element': display_value, 'details': ''})
- for id, display_value, state, indented in options),
- 1024
- )
-
- for i, str_options in enumerate(str_options_fields):
- embed.add_field(
- name=t('settings.troubleshooting.filters') + (f' ({i+1})' if i+1 > 1 else ''),
- value=str_options,
- inline=False
- )
-
- websites = {
- 'twitter': 'Twitter',
- 'instagram': 'Instagram',
- 'tiktok': 'TikTok',
- 'reddit': 'Reddit',
- 'threads': 'Threads',
- 'bluesky': 'Bluesky',
- 'snapchat': 'Snapchat',
- 'facebook': 'Facebook',
- 'pinterest': 'Pinterest',
- 'pixiv': 'Pixiv',
- 'twitch': 'Twitch',
- 'spotify': 'Spotify',
- 'deviantart': 'DeviantArt',
- 'newgrounds': 'Newgrounds',
- 'mastodon': 'Mastodon',
- 'tumblr': 'Tumblr',
- 'bilibili': 'BiliBili',
- 'weibo': 'Weibo',
- 'xiaohongshu': 'Xiaohongshu',
- 'imgur': 'Imgur',
- 'ifunny': 'iFunny',
- 'youtube': 'YouTube',
- 'linkedin': 'LinkedIn',
- 'furaffinity': 'Fur Affinity',
- 'imageboards': 'Imageboards',
- }
- str_websites = "\n".join([
- '- ' + t(
- f'settings.base_website.state.{l(bool(self.ctx.guild[key]))}',
- name=value, translation=''
- )
- for key, value in websites.items()
- ])
- embed.add_field(
- name=t('settings.troubleshooting.websites'),
- value=str_websites,
- inline=False
- )
- if self.ctx.guild.custom_websites:
- str_custom_websites = "\n".join([
- f"- `{website.domain}`"
- for website in self.ctx.guild.custom_websites
- ])
- embed.add_field(
- name=t('settings.troubleshooting.custom_websites'),
- value=str_custom_websites,
- inline=False
- )
- embed.add_field(
- name=t('settings.troubleshooting.premium.name'),
- value=t(f'settings.troubleshooting.premium.{l(bool(is_premium(self.interaction)))}'),
- inline=False)
- discore.set_embed_footer(self.bot, embed)
- return embed
+ **{'element': display_value, 'details': ''})
+ for id, display_value, state, indented in options)),
+ (t('settings.troubleshooting.websites'), "\n".join(
+ '- ' + t(
+ f'settings.base_website.state.{l(bool(self.ctx.guild[website.id]))}',
+ name=website.name, translation='')
+ for website in self.view.settings['websites'].settings.values()
+ if isinstance(website, WebsiteBaseSetting))),
+ ]
+ if custom_websites := self.ctx.guild.custom_websites:
+ fields.append((t('settings.troubleshooting.custom_websites'), "\n".join(
+ f"- `{website.domain}`" for website in custom_websites)))
+ fields.append((
+ t('settings.troubleshooting.premium.name'),
+ t(f'settings.troubleshooting.premium.{l(bool(is_premium(self.interaction)))}')))
- @property
- async def items(self) -> List[discore.ui.Item]:
refresh_button = discore.ui.Button(
label=t('settings.troubleshooting.refresh')
)
edit_callback(refresh_button, self.view, self.refresh_action)
- premium_button = discore.ui.Button(
- style=discore.ButtonStyle.premium,
- sku_id=discore.config.sku
- )
- support = discore.ui.Button(
+ buttons = discore.ui.ActionRow(refresh_button)
+ if not is_premium(self.interaction) and is_sku():
+ buttons.add_item(discore.ui.Button(
+ style=discore.ButtonStyle.premium,
+ sku_id=discore.config.sku
+ ))
+ buttons.add_item(discore.ui.Button(
style=discore.ButtonStyle.link,
label=t('about.support'),
url=discore.config.support_link,
emoji=discore.PartialEmoji.from_str(discore.config.emoji.discord)
- )
+ ))
# noinspection PyTypeChecker
select_channel = discore.ui.ChannelSelect(
custom_id=f'channel_select',
@@ -536,11 +409,13 @@ async def items(self) -> List[discore.ui.Item]:
placeholder=t(f'settings.members.select')
)
edit_callback(select_member, self.view, self.select_member_action)
- return (
- [refresh_button, support, select_channel, select_member]
- if is_premium(self.interaction) or not is_sku()
- else [refresh_button, premium_button, support, select_channel, select_member]
- )
+ return [
+ discore.ui.TextDisplay(t(self.description)),
+ *(discore.ui.TextDisplay(f"### {name}\n{value}") for name, value in fields),
+ buttons,
+ discore.ui.ActionRow(select_channel),
+ discore.ui.ActionRow(select_member),
+ ]
async def refresh_action(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
self.interaction = interaction
@@ -585,34 +460,20 @@ def __init__(
self.reset_clicked_level = 0
self.perms: list[str] = []
- @property
- async def embed(self) -> discore.Embed:
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=
- t(f'settings.{self.id}.content',
- bot=self.bot.user.display_name,
- element=self.element.mention,
- state=t(f'settings.{self.id}.state.{l(self.enabled)}',
- element=self.element.mention,
- details=t(f'settings.filters.labels.details.on_list.{l(self.element.on_list(self.ctx.guild))}',
- list= t(f'settings.filters.labels.details.list.{l(self.use_deny_list)}')),
- ),
- default_state= t(f'settings.filters.labels.default.{l(self.use_deny_list)}'),
- perms=format_perms(self.perms, self.ctx.channel.discord_object))
- )
- self.reset_clicked_level -= 1
- discore.set_embed_footer(self.bot, embed)
- return embed
-
- @property
- async def items(self) -> List[discore.ui.Item]:
- toggle_button = discore.ui.Button(
+ def toggle_button(self) -> discore.ui.Button:
+ """
+ Build the button enabling or disabling the selected element
+ :return: The button
+ """
+ return discore.ui.Button(
style=discore.ButtonStyle.primary if self.enabled else discore.ButtonStyle.secondary,
label=t(f'settings.filters.button.toggle.{l(self.enabled)}'),
custom_id=f'{self.id}_toggle'
)
- edit_callback(toggle_button, self.view, self.toggle)
+
+ @property
+ async def layout(self) -> List[discore.ui.Item]:
+ toggle_button = edit_callback(self.toggle_button(), self.view, self.toggle)
if is_premium(self.interaction):
toggle_default_button = discore.ui.Button(
style=discore.ButtonStyle.primary if self.use_deny_list else discore.ButtonStyle.secondary,
@@ -631,6 +492,7 @@ async def items(self) -> List[discore.ui.Item]:
custom_id=f'{self.id}_reset'
)
edit_callback(reset_button, self.view, self.reset)
+ self.reset_clicked_level -= 1
selector = self.Select(
custom_id=f'{self.id}_select',
default_values=[self.element.discord_object],
@@ -638,7 +500,29 @@ async def items(self) -> List[discore.ui.Item]:
**self.select_kwargs
)
edit_callback(selector, self.view, self.select_element)
- return [toggle_button, toggle_default_button, reset_button, selector]
+ items = [
+ discore.ui.TextDisplay(f"**{t(self.description)}**"),
+ discore.ui.Section(
+ t(f'settings.{self.id}.state.{l(self.enabled)}',
+ element=self.element.mention,
+ details=t(f'settings.filters.labels.details.on_list.{l(self.element.on_list(self.ctx.guild))}',
+ list=t(f'settings.filters.labels.details.list.{l(self.use_deny_list)}'))),
+ accessory=toggle_button),
+ discore.ui.Section(
+ t(f'settings.filters.labels.default.{l(self.use_deny_list)}'),
+ accessory=toggle_default_button),
+ *self.extra_sections(),
+ ]
+ if missing_perms := format_perms(self.perms, self.ctx.channel.discord_object).strip():
+ items.append(discore.ui.TextDisplay(missing_perms))
+ return items + [discore.ui.ActionRow(selector), discore.ui.ActionRow(reset_button)]
+
+ def extra_sections(self) -> List[discore.ui.Item]:
+ """
+ Build the sections specific to the setting, displayed below the common ones
+ :return: The sections
+ """
+ return []
async def toggle(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
self.enabled = not self.enabled
@@ -703,47 +587,13 @@ async def select_element(self, view: SettingsView, interaction: discore.Interact
)
await view.refresh(interaction)
- @property
- async def items(self) -> List[discore.ui.Item]:
+ def toggle_button(self) -> discore.ui.Button:
if is_premium(self.interaction) or not self.ctx.member.bot:
- toggle_button = discore.ui.Button(
- style=discore.ButtonStyle.primary if self.enabled else discore.ButtonStyle.secondary,
- label=t(f'settings.filters.button.toggle.{l(self.enabled)}'),
- custom_id=f'{self.id}_toggle'
- )
- else:
- toggle_button = discore.ui.Button(
- label=t('settings.members.toggle_bot_premium'),
- disabled=True
- )
- edit_callback(toggle_button, self.view, self.toggle)
- if is_premium(self.interaction):
- toggle_default_button = discore.ui.Button(
- style=discore.ButtonStyle.primary if self.use_deny_list else discore.ButtonStyle.secondary,
- label=t(f'settings.filters.button.toggle_default.{l(self.use_deny_list)}'),
- custom_id=f'{self.id}_default'
- )
- else:
- toggle_default_button = discore.ui.Button(
- label=t('settings.filters.button.toggle_default.premium'),
- disabled=True
- )
- edit_callback(toggle_default_button, self.view, self.toggle_default)
- reset_button = discore.ui.Button(
- style=discore.ButtonStyle.danger,
- label=t(f'settings.filters.button.reset.{l(self.reset_clicked_level > 1)}'),
- custom_id=f'{self.id}_reset'
+ return super().toggle_button()
+ return discore.ui.Button(
+ label=t('settings.members.toggle_bot_premium'),
+ disabled=True
)
- edit_callback(reset_button, self.view, self.reset)
- selector = self.Select(
- custom_id=f'{self.id}_select',
- default_values=[self.element.discord_object],
- placeholder=t(f'settings.{self.id}.select'),
- **self.select_kwargs
- )
- edit_callback(selector, self.view, self.select_element)
- return [toggle_button, toggle_default_button, reset_button, selector]
-
class ChannelSetting(GenericFilterSetting):
@@ -802,29 +652,7 @@ def __init__(
super().__init__(interaction, view, ctx)
self.use_any_rule = ctx.guild.roles_use_any_rule
- @property
- async def embed(self) -> discore.Embed:
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=
- t(f'settings.{self.id}.content',
- bot=self.bot.user.display_name,
- element=self.element.mention,
- state=t(f'settings.{self.id}.state.{l(self.enabled)}',
- element=self.element.mention,
- details=t(f'settings.filters.labels.details.on_list.{l(self.element.on_list(self.ctx.guild))}',
- list= t(f'settings.filters.labels.details.list.{l(self.use_deny_list)}')),
- ),
- default_state= t(f'settings.filters.labels.default.{l(self.use_deny_list)}'),
- rule=t(f'settings.{self.id}.rule.{l(self.use_any_rule)}'),
- perms=format_perms(self.perms, self.ctx.channel.discord_object))
- )
- self.reset_clicked_level -= 1
- discore.set_embed_footer(self.bot, embed)
- return embed
-
- @property
- async def items(self) -> List[discore.ui.Item]:
+ def extra_sections(self) -> List[discore.ui.Item]:
if is_premium(self.interaction):
toggle_rule_button = discore.ui.Button(
style=discore.ButtonStyle.primary if self.use_any_rule else discore.ButtonStyle.secondary,
@@ -837,8 +665,9 @@ async def items(self) -> List[discore.ui.Item]:
disabled=True
)
edit_callback(toggle_rule_button, self.view, self.toggle_rule)
- items = await super().items
- return [items[0], items[1], toggle_rule_button, items[2], items[3]]
+ return [discore.ui.Section(
+ t(f'settings.{self.id}.rule.{l(self.use_any_rule)}'),
+ accessory=toggle_rule_button)]
async def toggle(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
self.enabled = not self.enabled
@@ -859,7 +688,7 @@ async def toggle_rule(self, view: SettingsView, interaction: discore.Interaction
await view.refresh(interaction)
-class KeywordModal(discore.ui.Modal):
+class KeywordModal(Modal):
def __init__(self, keyword_index: int | None, keyword_setting: KeywordsSetting, **kwargs):
super().__init__(
@@ -869,28 +698,32 @@ def __init__(self, keyword_index: int | None, keyword_setting: KeywordsSetting,
)
self.keyword_index = keyword_index
self.setting = keyword_setting
- self.add_item(discore.ui.TextInput(
- label=t('settings.keywords.modal.value.label'),
+ self.keyword = discore.ui.TextInput(
placeholder=t('settings.keywords.modal.value.placeholder'),
custom_id='value',
default=keyword_setting.keywords[keyword_index] if keyword_index is not None else None
- ))
+ )
+ self.add_item(discore.ui.Label(text=t('settings.keywords.modal.value.label'), component=self.keyword))
async def on_submit(self, interaction: discore.Interaction):
- children = self.children
- value_field = str(children[0])
+ value_field = self.keyword.value.strip()
+
+ if not value_field:
+ # A keyword made of spaces can't be listed, and would match nearly every message
+ await self.setting.view.refresh(interaction)
+ return
if len(value_field) > 50:
await interaction.response.send_message(
- t('settings.keywords.modal.error.length', max=50), ephemeral=True, delete_after=10)
+ view=notice(t('settings.keywords.modal.error.length', max=50)), ephemeral=True, delete_after=10)
return
if value_field in self.setting.keywords and (
self.keyword_index is None or
- value_field.index(value_field) != self.keyword_index
+ self.setting.keywords.index(value_field) != self.keyword_index
):
await interaction.response.send_message(
- t('settings.keywords.modal.error.exists'), ephemeral=True, delete_after=10)
+ view=notice(t('settings.keywords.modal.error.exists')), ephemeral=True, delete_after=10)
return
if self.keyword_index is not None:
@@ -920,46 +753,46 @@ def __init__(
self.use_allow_list = self.ctx.guild.keywords_use_allow_list
@property
- async def embed(self) -> discore.Embed:
+ async def layout(self) -> List[discore.ui.Item]:
keywords_str = "\n".join(
[
f'- **{keyword}**' if index == self.selected_index else f'- {keyword}'
for index, keyword in enumerate(self.keywords)
] if self.keywords else ['*' + t('settings.keywords.empty') + '*']
)
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=t(
- f'settings.keywords.content.{l(self.use_allow_list)}',
- keywords=keywords_str
+ if is_premium(self.interaction):
+ toggle_mode_button = discore.ui.Button(
+ style=discore.ButtonStyle.primary if self.use_allow_list else discore.ButtonStyle.secondary,
+ label=t(f'settings.keywords.button.toggle_mode.{l(self.use_allow_list)}'),
+ custom_id=f'{self.id}_default'
)
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
+ edit_callback(toggle_mode_button, self.view, self.toggle_mode)
+ else:
+ toggle_mode_button = discore.ui.Button(
+ label=t('settings.keywords.button.toggle_mode.premium'),
+ disabled=True
+ )
+ items = [discore.ui.Section(
+ t(f'settings.keywords.content.{l(self.use_allow_list)}', keywords=keywords_str),
+ accessory=toggle_mode_button
+ )]
- @property
- async def items(self) -> List[discore.ui.Item]:
- # use the same structure as CustomWebsitesSetting
if self.keywords:
- options = [
- discore.SelectOption(
- label=keyword,
- value=str(index),
- default=index == self.selected_index
- )
- for index, keyword in enumerate(self.keywords)
- ]
- else:
- options = [discore.SelectOption(
- label=t('settings.keywords.empty'), value='0', default=True)]
-
- select = discore.ui.Select(
- placeholder=t('settings.keywords.button.placeholder'),
- options=options,
- custom_id='select_keyword',
- disabled=not self.keywords
- )
- edit_callback(select, self.view, self.select_keyword)
+ select = discore.ui.Select(
+ placeholder=t('settings.keywords.button.placeholder'),
+ options=[
+ discore.SelectOption(
+ label=keyword,
+ value=str(index),
+ default=index == self.selected_index
+ )
+ for index, keyword in enumerate(self.keywords)
+ ],
+ custom_id='select_keyword'
+ )
+ edit_callback(select, self.view, self.select_keyword)
+ items.append(discore.ui.ActionRow(select))
+
if len(self.keywords) >= 3 and not is_premium(self.interaction):
add_button = discore.ui.Button(
style=discore.ButtonStyle.primary,
@@ -994,20 +827,8 @@ async def items(self) -> List[discore.ui.Item]:
disabled=self.selected_index is None
)
edit_callback(delete_button, self.view, self.delete_keyword)
- if is_premium(self.interaction):
- toggle_mode_button = discore.ui.Button(
- style=discore.ButtonStyle.primary if self.use_allow_list else discore.ButtonStyle.secondary,
- label=t(f'settings.keywords.button.toggle_mode.{l(self.use_allow_list)}'),
- custom_id=f'{self.id}_default'
- )
- edit_callback(toggle_mode_button, self.view, self.toggle_mode)
- else:
- toggle_mode_button = discore.ui.Button(
- label=t('settings.keywords.button.toggle_mode.premium'),
- disabled=True
- )
-
- return [select, add_button, edit_button, delete_button, toggle_mode_button]
+ items.append(discore.ui.ActionRow(add_button, edit_button, delete_button))
+ return items
async def select_keyword(self, view: SettingsView, interaction: discore.Interaction, select: discore.ui.Select) -> None:
"""
@@ -1069,24 +890,6 @@ def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: Da
super().__init__(interaction, view, ctx)
self.state = ctx.guild.original_message
- @property
- async def embed(self) -> discore.Embed:
- option_tr_path = f'settings.original_message.option.{self.state.name.lower()}'
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=t(
- 'settings.original_message.content',
- state=t(option_tr_path + '.emoji') + ' ' + t(option_tr_path + '.label'),
- channel=self.ctx.channel.mention,
- perms=format_perms(
- ['manage_messages']
- if self.state != OriginalMessage.NOTHING
- else [],
- self.ctx.channel.discord_object))
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
-
@property
async def option(self) -> discore.SelectOption:
return discore.SelectOption(
@@ -1099,7 +902,8 @@ async def option(self) -> discore.SelectOption:
)
@property
- async def items(self) -> List[discore.ui.Item]:
+ async def layout(self) -> List[discore.ui.Item]:
+ option_tr_path = f'settings.original_message.option.{self.state.name.lower()}'
item = discore.ui.Select(
options=[
discore.SelectOption(
@@ -1112,11 +916,27 @@ async def items(self) -> List[discore.ui.Item]:
]
)
edit_callback(item, self.view, self.action)
- return [item]
+ return [
+ discore.ui.TextDisplay(t(
+ 'settings.original_message.content',
+ state=t(option_tr_path + '.emoji') + ' ' + t(option_tr_path + '.label'),
+ channel=self.ctx.channel.mention,
+ perms=format_perms(
+ ['manage_messages']
+ if self.state != OriginalMessage.NOTHING
+ else [],
+ self.ctx.channel.discord_object))),
+ discore.ui.ActionRow(item)
+ ]
async def action(self, view: SettingsView, interaction: discore.Interaction, select: discore.ui.Select) -> None:
self.state = OriginalMessage[select.values[0]]
- self.ctx.guild.update({'original_message': self.state.value}, cast=False)
+ changes = {'original_message': self.state.value}
+ if self.state == OriginalMessage.DELETE:
+ # Nothing is left to delete the fixed links along with
+ changes['delete_with_original'] = False
+ # Forced, as the option can have been enabled from another settings message meanwhile
+ self.ctx.guild.update(changes, cast=False, force=True)
await view.refresh(interaction)
@@ -1134,33 +954,6 @@ def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: Da
self.reply_to_message = bool(ctx.guild.reply_to_message and not self.reply_as_original_author_replica)
self.reply_silently = bool(ctx.guild.reply_silently)
- @property
- async def embed(self) -> discore.Embed:
- perms = [
- 'view_channel',
- 'send_messages',
- 'embed_links'
- ]
- if isinstance(self.ctx.channel.discord_object, discore.Thread):
- perms.append('send_messages_in_threads')
- if self.reply_to_message:
- perms.append('read_message_history')
- if self.reply_as_original_author_replica:
- perms.append('manage_webhooks')
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=t(
- 'settings.reply_method.content',
- state=t(f'settings.reply_method.reply.state.{l(self.reply_to_message)}', emoji=self.emoji),
- silent=t(f'settings.reply_method.silent.state.{l(self.reply_silently)}'),
- replica=t(
- f'settings.reply_method.original_author_replica.state.{l(self.reply_as_original_author_replica)}',
- bot=self.bot.user.display_name),
- perms=format_perms(perms, self.ctx.channel.discord_object))
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
-
@property
async def option(self) -> discore.SelectOption:
has_missing_perms = (
@@ -1177,7 +970,18 @@ async def option(self) -> discore.SelectOption:
)
@property
- async def items(self) -> List[discore.ui.Item]:
+ async def layout(self) -> List[discore.ui.Item]:
+ perms = [
+ 'view_channel',
+ 'send_messages',
+ 'embed_links'
+ ]
+ if isinstance(self.ctx.channel.discord_object, discore.Thread):
+ perms.append('send_messages_in_threads')
+ if self.reply_to_message:
+ perms.append('read_message_history')
+ if self.reply_as_original_author_replica:
+ perms.append('manage_webhooks')
reply_to_message_button = discore.ui.Button(
style=discore.ButtonStyle.primary if self.reply_to_message else discore.ButtonStyle.secondary,
label=t(f'settings.reply_method.reply.button.{l(self.reply_to_message)}'),
@@ -1199,7 +1003,22 @@ async def items(self) -> List[discore.ui.Item]:
custom_id='reply_as_original_author_replica'
)
edit_callback(original_author_replica_button, self.view, self.toggle_reply_as_original_author_replica)
- return [reply_to_message_button, reply_silently_button, original_author_replica_button]
+ items = [
+ discore.ui.TextDisplay(f"**{t(self.description)}**"),
+ discore.ui.Section(
+ t(f'settings.reply_method.reply.state.{l(self.reply_to_message)}', emoji=self.emoji),
+ accessory=reply_to_message_button),
+ discore.ui.Section(
+ t(f'settings.reply_method.silent.state.{l(self.reply_silently)}'),
+ accessory=reply_silently_button),
+ discore.ui.Section(
+ t(f'settings.reply_method.original_author_replica.state.{l(self.reply_as_original_author_replica)}',
+ bot=self.bot.user.display_name),
+ accessory=original_author_replica_button),
+ ]
+ if missing_perms := format_perms(perms, self.ctx.channel.discord_object).strip():
+ items.append(discore.ui.TextDisplay(missing_perms))
+ return items
async def toggle_reply_to_message(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
if self.reply_as_original_author_replica:
@@ -1236,17 +1055,6 @@ def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: Da
super().__init__(interaction, view, ctx)
self.state = bool(ctx.guild.db_object.webhooks)
- @property
- async def embed(self) -> discore.Embed:
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=t(
- 'settings.webhooks.content',
- state=t(f'settings.webhooks.state.{l(self.state)}'))
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
-
@property
async def option(self) -> discore.SelectOption:
return discore.SelectOption(
@@ -1257,14 +1065,17 @@ async def option(self) -> discore.SelectOption:
)
@property
- async def items(self) -> List[discore.ui.Item]:
+ async def layout(self) -> List[discore.ui.Item]:
item = discore.ui.Button(
style=discore.ButtonStyle.primary if self.state else discore.ButtonStyle.secondary,
label=t(f'settings.webhooks.button.{l(self.state)}'),
custom_id=self.id
)
edit_callback(item, self.view, self.action)
- return [item]
+ return [discore.ui.Section(
+ t('settings.webhooks.content', state=t(f'settings.webhooks.state.{l(self.state)}')),
+ accessory=item
+ )]
async def action(self, view: SettingsView, interaction: discore.Interaction, _) -> None:
self.state = not self.state
@@ -1272,6 +1083,75 @@ async def action(self, view: SettingsView, interaction: discore.Interaction, _)
await view.refresh(interaction)
+class RemovalSetting(BaseSetting):
+ """Represents the fixed links removal setting (along with the original message, or on a ❌ reaction)"""
+
+ name = 'settings.removal.name'
+ id = 'removal'
+ description = 'settings.removal.description'
+ emoji = '🗑️'
+
+ @property
+ def perms(self) -> list[str]:
+ """The permissions needed to add the ❌ reaction to the fixed links, if the guild asks for it"""
+ if self.ctx.guild.delete_on_reaction and self.ctx.guild.add_delete_reaction:
+ return ['add_reactions', 'read_message_history']
+ return []
+
+ @property
+ async def option(self) -> discore.SelectOption:
+ return discore.SelectOption(
+ label=('⚠️ ' if is_missing_perm(self.perms, self.ctx.channel.discord_object) else '') + t(self.name),
+ value=self.id,
+ description=t(self.description),
+ emoji=self.emoji
+ )
+
+ @property
+ async def layout(self) -> List[discore.ui.Item]:
+ guild = self.ctx.guild
+ # Nothing is left to delete the fixed links along with when the original message is deleted once fixed
+ deletes_original = guild.original_message == OriginalMessage.DELETE
+ delete_on_reaction = bool(guild.delete_on_reaction)
+ # (column, state, whether it can't be changed, state to describe instead of the actual one)
+ options = (
+ ('delete_with_original', bool(guild.delete_with_original) and not deletes_original, deletes_original,
+ 'unavailable' if deletes_original else None),
+ ('delete_on_reaction', delete_on_reaction, False, None),
+ ('add_delete_reaction', bool(guild.add_delete_reaction) and delete_on_reaction, not delete_on_reaction,
+ None),
+ )
+ items = [discore.ui.TextDisplay(f"**{t(self.description)}**")]
+ for column, state, disabled, described_state in options:
+ button = discore.ui.Button(
+ style=discore.ButtonStyle.primary if state else discore.ButtonStyle.secondary,
+ label=t(f'settings.filters.button.toggle.{l(state)}'),
+ custom_id=column,
+ disabled=disabled
+ )
+ edit_callback(button, self.view, self.action)
+ items.append(discore.ui.Section(
+ t(f'settings.removal.{column}.{described_state or l(state)}', bot=self.bot.user.display_name),
+ accessory=button))
+ if missing_perms := format_perms(self.perms, self.ctx.channel.discord_object).strip():
+ items.append(discore.ui.TextDisplay(missing_perms))
+ return items
+
+ async def action(self, view: SettingsView, interaction: discore.Interaction, button: discore.ui.Button) -> None:
+ guild = self.ctx.guild
+ column = button.custom_id
+ # A button of an outdated message can still be clicked after its option stopped being available
+ guild.db_object = guild.db_object.fresh()
+ if not ((column == 'delete_with_original' and guild.original_message == OriginalMessage.DELETE)
+ or (column == 'add_delete_reaction' and not guild.delete_on_reaction)):
+ changes = {column: not guild[column]}
+ if column == 'delete_on_reaction' and not changes[column]:
+ # A reaction that deletes nothing has no reason to be added
+ changes['add_delete_reaction'] = False
+ guild.update(changes)
+ await view.refresh(interaction)
+
+
class TwitterSetting(WebsiteBaseSetting):
"""Represents the twitter setting"""
@@ -1501,7 +1381,7 @@ class PinterestSetting(EmbedEZBaseSetting):
emoji = discore.config.emoji.pinterest
-class CustomWebsiteModal(discore.ui.Modal):
+class CustomWebsiteModal(Modal):
def __init__(self, website: CustomWebsite | None, website_setting: CustomWebsitesSetting, **kwargs):
super().__init__(
@@ -1511,27 +1391,29 @@ def __init__(self, website: CustomWebsite | None, website_setting: CustomWebsite
)
self.website = website
self.setting = website_setting
- self.add_item(discore.ui.TextInput(
- label=t('settings.custom_websites.modal.name.label'),
+ self.name = discore.ui.TextInput(
placeholder=t('settings.custom_websites.modal.name.placeholder'),
custom_id='name',
default=website.name if website else None
- ))
- self.add_item(discore.ui.TextInput(
- label=t('settings.custom_websites.modal.domain.label'),
+ )
+ self.domain = discore.ui.TextInput(
placeholder=t('settings.custom_websites.modal.domain.placeholder'),
custom_id='domain',
default=website.domain if website else None
- ))
- self.add_item(discore.ui.TextInput(
- label=t('settings.custom_websites.modal.fix_domain.label'),
+ )
+ self.fix_domain = discore.ui.TextInput(
placeholder=t('settings.custom_websites.modal.fix_domain.placeholder'),
custom_id='fix_domain',
- default=website.fix_domain if website else None
- ))
+ default=website.fix_domain if website else None,
+ max_length=255
+ )
+ for field, component in (('name', self.name), ('domain', self.domain), ('fix_domain', self.fix_domain)):
+ self.add_item(discore.ui.Label(
+ text=t(f'settings.custom_websites.modal.{field}.label'), component=component))
async def on_submit(self, interaction: discore.Interaction):
def clean_domain(domain: str) -> str:
+ domain = domain.strip()
if domain.startswith('http://') or domain.startswith('https://'):
domain = domain.split('://', 1)[1]
if domain.startswith('www.'):
@@ -1540,17 +1422,13 @@ def clean_domain(domain: str) -> str:
domain = domain[:-1]
return domain
- children = self.children
- name_field = str(children[0])
- domain_field = str(children[1])
- fix_domain_field = str(children[2])
-
- domain_field = clean_domain(domain_field)
- fix_domain_field = clean_domain(fix_domain_field)
+ name_field = self.name.value.strip()
+ domain_field = clean_domain(self.domain.value)
+ fix_domain_field = clean_domain(self.fix_domain.value)
if not domain_field or not fix_domain_field:
await interaction.response.send_message(
- t('settings.custom_websites.modal.error.length'), ephemeral=True, delete_after=10)
+ view=notice(t('settings.custom_websites.modal.error.length')), ephemeral=True, delete_after=10)
return
custom_website = CustomWebsite.where('guild_id', interaction.guild.id).where({
@@ -1559,34 +1437,32 @@ def clean_domain(domain: str) -> str:
}).first()
if custom_website and (not self.website or custom_website.id != self.website.id):
await interaction.response.send_message(
- t('settings.custom_websites.modal.error.exists'), ephemeral=True, delete_after=10)
+ view=notice(t('settings.custom_websites.modal.error.exists')), ephemeral=True, delete_after=10)
return
+ # A website is listed by its name: its domain stands for a blank one
+ name_field = name_field or domain_field[:36]
+
if len(name_field) > 36:
await interaction.response.send_message(
- t('settings.custom_websites.modal.error.length_name', max=36), ephemeral=True, delete_after=10)
+ view=notice(t('settings.custom_websites.modal.error.length_name', max=36)), ephemeral=True, delete_after=10)
return
if len(domain_field) > 61:
await interaction.response.send_message(
- t('settings.custom_websites.modal.error.length_domain', max=61), ephemeral=True, delete_after=10)
+ view=notice(t('settings.custom_websites.modal.error.length_domain', max=61)), ephemeral=True, delete_after=10)
return
+ values = {
+ 'name': name_field,
+ 'domain': domain_field,
+ 'fix_domain': fix_domain_field
+ }
if self.website:
- old_website = self.website
- self.website.update({
- 'name': name_field,
- 'domain': domain_field,
- 'fix_domain': fix_domain_field
- })
- self.setting.custom_websites._items.remove(old_website)
+ self.website.update(values)
+ self.setting.custom_websites._items.remove(self.website)
else:
- self.website = CustomWebsite.create(
- guild_id=interaction.guild.id,
- name=name_field,
- domain=domain_field,
- fix_domain=fix_domain_field
- )
+ self.website = CustomWebsite.create(guild_id=interaction.guild.id, **values)
self.setting.custom_websites._items.append(self.website)
self.setting.selected = self.website
await self.setting.view.refresh(interaction)
@@ -1606,7 +1482,7 @@ def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: Da
self.selected: CustomWebsite | None = None
@property
- async def embed(self) -> discore.Embed:
+ async def layout(self) -> List[discore.ui.Item]:
website_list = (
'\n'.join([
t(
@@ -1618,37 +1494,27 @@ async def embed(self) -> discore.Embed:
for website in self.custom_websites
])
)
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=(
- t('settings.custom_websites.content')
- + ((t('settings.custom_websites.list') + website_list) if website_list else '')
- )
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
+ items = [discore.ui.TextDisplay(
+ t('settings.custom_websites.content')
+ + ((t('settings.custom_websites.list') + website_list) if website_list else '')
+ )]
- @property
- async def items(self) -> List[discore.ui.Item]:
if self.custom_websites:
- options = [
- discore.SelectOption(
- label=f"{website.name} ({website.domain})",
- value=website.domain,
- default=website == self.selected
- )
- for website in self.custom_websites
- ]
- else:
- options = [discore.SelectOption(
- label=t('settings.custom_websites.empty'), default=True)]
+ selector = discore.ui.Select(
+ options=[
+ discore.SelectOption(
+ label=(website.name.strip() or website.domain)[:100],
+ description=f"{website.domain} → {website.fix_domain}"[:100],
+ value=website.domain,
+ default=website == self.selected
+ )
+ for website in self.custom_websites
+ ],
+ placeholder=t('settings.custom_websites.placeholder')
+ )
+ edit_callback(selector, self.view, self.select_action)
+ items.append(discore.ui.ActionRow(selector))
- selector = discore.ui.Select(
- options=options,
- placeholder=t('settings.custom_websites.placeholder'),
- disabled=not self.custom_websites
- )
- edit_callback(selector, self.view, self.select_action)
if len(self.custom_websites) >= 3 and not is_premium(self.interaction):
add_button = discore.ui.Button(
style=discore.ButtonStyle.primary,
@@ -1683,7 +1549,8 @@ async def items(self) -> List[discore.ui.Item]:
disabled=not self.selected
)
edit_callback(delete_button, self.view, self.delete_action)
- return [selector, add_button, edit_button, delete_button]
+ items.append(discore.ui.ActionRow(add_button, edit_button, delete_button))
+ return items
async def action(self, _, interaction: discore.Interaction, button: discore.ui.Button) -> None:
await self.view.reset_timeout(interaction)
@@ -1756,64 +1623,60 @@ def __init__(self, interaction: discore.Interaction, view: SettingsView, ctx: Da
self.current_page: int = 0
@property
- async def embed(self) -> discore.Embed:
- if self.selected_id is not None:
- return await self.settings[self.selected_id].embed
-
- embed = discore.Embed(
- title=f"{self.emoji} {t(self.name)}",
- description=t('settings.websites.content')
- )
- discore.set_embed_footer(self.bot, embed)
- return embed
+ def title(self) -> str:
+ return self.settings[self.selected_id].title if self.selected_id else super().title
@property
- async def items(self) -> List[discore.ui.Item]:
- selected_items = await self.settings[self.selected_id].items if self.selected_id else []
- options = [[]]
- for setting_id in self.settings:
- option = await self.settings[setting_id].option
- if setting_id == self.selected_id:
- option.default = True
- if len(options[-1]) >= 25:
- options.append([])
- options[-1].append(option)
-
- parameter_selection = discore.ui.Select(options=options[self.current_page], row=2, placeholder=t('settings.websites.placeholder'))
- edit_callback(parameter_selection, self.view, self.action)
-
- page_button = discore.ui.Button(
- style=discore.ButtonStyle.secondary,
- label=t('settings.websites.page_button',
- current_page=self.current_page + 1,
- total_pages=len(options),
- total_options=len(self.settings),
- options_count=len(options[self.current_page])),
- custom_id='page_button',
- row=3,
+ async def layout(self) -> List[discore.ui.Item]:
+ items = (
+ await self.settings[self.selected_id].layout if self.selected_id
+ else [discore.ui.TextDisplay(t('settings.websites.content'))]
)
- edit_callback(page_button, self.view, self.change_page)
-
- return selected_items + [parameter_selection, page_button]
+ options = [await setting.option for setting in self.settings.values()]
+ for option in options:
+ option.default = option.value == self.selected_id
+ placeholder = t('settings.websites.placeholder')
+
+ # A select holds 25 options at most: past that, the websites are listed page by page,
+ # the options to change page being part of the list itself
+ if len(options) > 25:
+ pages = [options[i:i + 23] for i in range(0, len(options), 23)]
+
+ def page_option(page: int, label: str, emoji: str) -> discore.SelectOption:
+ return discore.SelectOption(
+ label=t(label), value=f'page:{page}', emoji=emoji,
+ description=t('settings.websites.page', page=page + 1, pages=len(pages)))
+
+ options = pages[self.current_page]
+ if self.current_page > 0:
+ options.insert(0, page_option(self.current_page - 1, 'settings.websites.previous_page', '⬅️'))
+ if self.current_page < len(pages) - 1:
+ options.append(page_option(self.current_page + 1, 'settings.websites.next_page', '➡️'))
+ placeholder += f" ({t('settings.websites.page', page=self.current_page + 1, pages=len(pages))})"
+
+ website_selection = discore.ui.Select(options=options, placeholder=placeholder)
+ edit_callback(website_selection, self.view, self.action)
+ return items + [discore.ui.Separator(), discore.ui.ActionRow(website_selection)]
async def action(self, _, interaction: discore.Interaction, select: discore.ui.Select) -> None:
- self.selected_id = select.values[0]
+ value = select.values[0]
+ if value.startswith('page:'):
+ self.current_page = int(value.removeprefix('page:'))
+ else:
+ self.selected_id = value
await self.view.refresh(interaction)
- async def change_page(self, _, interaction: discore.Interaction, __) -> None:
- self.current_page = (self.current_page + 1) % math.ceil(len(self.settings) / 25)
- self.selected_id = None
- await self.view.refresh(interaction)
+class SettingsView(discore.ui.LayoutView):
-class SettingsView(discore.ui.View):
+ # Errors are reported the same way as in the other views
+ on_error = discore.ui.View.on_error
def __init__(self, i: discore.Interaction):
super().__init__()
self.bot: discore.Client = i.client
self.ctx = DataElements(i)
- self.embed: discore.Embed | None = None
self.settings: dict[str, BaseSetting] = BaseSetting.dict_from_settings((
TroubleshootingSetting(i, self, self.ctx),
ChannelSetting(i, self, self.ctx),
@@ -1823,35 +1686,23 @@ def __init__(self, i: discore.Interaction):
WebsiteSettings(i, self, self.ctx),
OriginalMessageBehaviorSetting(i, self, self.ctx),
ReplyMethodSetting(i, self, self.ctx),
+ RemovalSetting(i, self, self.ctx),
WebhooksSetting(i, self, self.ctx),
))
self.selected_id: str | None = None
self.timeout_task: asyncio.Task | None = None
- async def build(self) -> Self:
- """
- Build the interaction response (items and embed)
- :return: self
- """
- await self._build_items()
- default_embed = discore.Embed(
- title=t('settings.title'),
- description=t('settings.description')
- )
- discore.set_embed_footer(self.bot, default_embed)
- self.embed = await self.settings[self.selected_id].embed if self.selected_id else default_embed
- return self
+ async def interaction_check(self, interaction: discore.Interaction) -> bool:
+ # The texts are built from the global locale, which is otherwise only set when a command is invoked
+ discore.set_locale(interaction)
+ return True
- async def _build_items(self) -> Self:
+ async def build(self) -> Self:
"""
- Build the view items
+ Build the interaction response (the whole layout)
:return: self
"""
- self.clear_items()
-
- if self.selected_id is not None:
- for i in await self.settings[self.selected_id].items:
- self.add_item(i)
+ setting = self.settings.get(self.selected_id)
options = []
for setting_id in self.settings:
@@ -1860,12 +1711,37 @@ async def _build_items(self) -> Self:
option.default = True
options.append(option)
- parameter_selection = discore.ui.Select(options=options, row=4, placeholder=t('settings.placeholder'))
+ parameter_selection = discore.ui.Select(options=options, placeholder=t('settings.placeholder'))
# noinspection PyTypeChecker
edit_callback(parameter_selection, self, self.__class__.select_parameter)
- self.add_item(parameter_selection)
+
+ self.clear_items()
+ self.add_item(discore.ui.Container(
+ discore.ui.TextDisplay(
+ f"## {setting.title}" if setting else f"## {t('settings.title')}\n{t('settings.description')}"),
+ *(await setting.layout if setting else ()),
+ discore.ui.Separator(),
+ discore.ui.ActionRow(parameter_selection),
+ discore.ui.TextDisplay(footer(self.bot)),
+ accent_color=discore.config.color or None
+ ))
+ self._fit_texts()
return self
+ def _fit_texts(self) -> None:
+ """
+ Shorten the longest texts until the layout fits in the 4000 characters Discord allows per message
+ """
+ # This is a plain cut, which may split a markdown element
+ texts = [item for item in self.walk_children() if isinstance(item, discore.ui.TextDisplay)]
+ excess = self.content_length() - 4000
+ for item in sorted(texts, key=lambda text: len(text.content), reverse=True):
+ if excess <= 0:
+ break
+ kept = max(len(item.content) - excess - 1, 0)
+ excess -= len(item.content) - kept - 1
+ item.content = item.content[:kept] + '…'
+
@staticmethod
async def _message_delete_after(interaction: discore.Interaction, delay: float = 180.0) -> None:
"""
@@ -1910,14 +1786,15 @@ async def refresh(self, interaction: discore.Interaction) -> None:
# Even if the interaction is really not found, there's not much we can do (as the interaction is lost),
# so in both cases we just ignore the error.
try:
+ # Unlike in embeds, mentions in text components can ping
if interaction.message is not None:
# noinspection PyUnresolvedReferences
await interaction.response.edit_message(
- view=self, embed=self.embed)
+ view=self, allowed_mentions=discore.AllowedMentions.none())
else:
# noinspection PyUnresolvedReferences
await interaction.response.send_message(
- view=self, embed=self.embed, ephemeral=True)
+ view=self, ephemeral=True, allowed_mentions=discore.AllowedMentions.none())
except discore.NotFound:
pass
diff --git a/src/utils.py b/src/utils.py
index 1c13c5e..b024910 100644
--- a/src/utils.py
+++ b/src/utils.py
@@ -16,9 +16,9 @@
from database.models.DiscordRepresentation import DiscordRepresentation
__all__ = (
- 't', 'translate', 'object_format', 'edit_callback', 'is_premium',
+ 't', 'translate', 'object_format', 'edit_callback', 'notice', 'footer', 'is_premium',
'is_sku', 'format_perms', 'is_missing_perm', 'I18nTranslator', 'tstr',
- 'group_join', 'group_items', 'l', 'GuildChild', 'HybridElement', 'reply_to_member',
+ 'group_items', 'l', 'GuildChild', 'HybridElement', 'reply_to_member',
'session', 'safe_send_coro', 'entrypoint_context', 'Typing'
)
@@ -95,8 +95,8 @@ def object_format(object, **kwargs):
return object
-V = TypeVar('V', bound='discore.ui.View')
-I = TypeVar('I', bound='discore.ui.Item[discore.ui.View]')
+V = TypeVar('V', bound='discore.ui.LayoutView')
+I = TypeVar('I', bound='discore.ui.Item[discore.ui.LayoutView]')
def edit_callback(item: I, view: V, callback: discore.ui.item.ItemCallbackType[Any, Any]) -> I:
@@ -115,6 +115,31 @@ def edit_callback(item: I, view: V, callback: discore.ui.item.ItemCallbackType[A
return item
+def notice(content: str) -> discore.ui.LayoutView:
+ """
+ Build a components message made of a single text
+
+ :param content: The text to display
+ :return: The view to send
+ """
+ view = discore.ui.LayoutView()
+ view.add_item(discore.ui.Container(discore.ui.TextDisplay(content), accent_color=discore.config.color or None))
+ return view
+
+
+def footer(bot: discore.Client) -> str:
+ """
+ Build the footer of a components message: the bot's name and version, as a small text
+
+ :param bot: The bot instance
+ :return: The footer
+ """
+ info = [bot.user.name]
+ if discore.config.version:
+ info.append(i18n.t('footer.version', version=discore.config.version))
+ return '-# ' + ' | '.join(info)
+
+
def is_premium(i: discore.Interaction) -> bool | None:
"""
Check if the user is premium
@@ -234,18 +259,6 @@ def group_items(items: Iterable[T], max_group_size: int, sep: str = "\n") -> lis
return groups
-def group_join(strings: Iterable[str], max_group_size: int, sep: str = "\n") -> list[str]:
- """
- Group strings based on a maximum group size and a separator.
- Wrapper around group_items for simple string grouping.
-
- :param strings: The list of strings to group.
- :param max_group_size: The maximum allowed size (in characters) for each group.
- :param sep: The separator to use between items in a group. Default is a newline character.
- :return: A list of grouped strings.
- """
- return [group for group, _ in group_items(strings, max_group_size, sep)]
-
def l(e: Any) -> str:
"""
Lowers an element