[retrigger] Add ability to search Embeds (#318)

* [retrigger] Add ability to search Embeds

- Add ability to search embeds in messages
- Normal embeds or recently posted URL embeds still cached work normally
- on_message_edit was added due to auto-generated URL preview embeds not cached being edited into the message AFTER the on_message is triggered.
- In order to process the above the logic is configured such that you require edits AND embeds enabled to search these generated embeds

* Update Embed Option Naming and Rework Parsing of Embed Content

- Renamed the option to variants of Read Embeds to avoid confusion
- Removed superfluous on_message_edit listener
- Added parsing of embed content to remove any unwanted fields
- Properly format the embed contents into a sensible string structure

* Remove Extra Print

- Removing extra print inserted for output string confirmation

* Handle "Fields" of Embeds and Fix Missed embeds -> read_embeds

- Added handling of `Fields` field of embeds
- Removed `inline` from blacklist, due to Name/Value mapping of `Fields` it made more sense to direct reference them and ignore `inline`
- Fixed `trigger.embeds` not updated to `trigger.read_embeds` not picked up in previous testing due to trigger cache

* Apply suggestions from code review

Co-authored-by: TrustyJAID <TrustyJAID@gmail.com>

* Makefile Reformat Cleanup

---------

Co-authored-by: TrustyJAID <TrustyJAID@gmail.com>
This commit is contained in:
XxInvictusandTrustyJAID authored and GitHub committed 2023-06-03 00:02:39 -06:00
1 parent e6982a62d1
commit d18cc68f40
11 files changed
+83 -4

No files matched your search

+1
View File
@@ -49,3 +49,4 @@ __pycache__/
audiotest/
trusty-cogs.sublime-workspace
*.sublime-workspace
.idea/
-1
View File
@@ -144,7 +144,6 @@ class Memes(discord.app_commands.Transformer):
async def autocomplete(
self, interaction: discord.Interaction, current: str
) -> List[discord.app_commands.Choice]:
if not self.meme_list:
cog: Optional[Imgflip] = interaction.client.get_cog("Imgflip")
if cog is None:
+1
View File
@@ -242,6 +242,7 @@ Edit various settings in a set trigger.
- **readfilenames** Edit whether or not a trigger will append filenames of attachments to the search.
- **deleteafter** Text triggers can have an optional delete_after time set, this can be used to edit it.
- **chance** Triggers can be setup with a chance to occur in form of `1 in chance`.
- **readembeds** Toggle whether the bot will search the contents of embeds. **Requires `edited` also be enabled.**
### **modlog**
Set which events to record in the modlog. ReTrigger has a built in modlog setup which can be used to track when and how ReTrigger is performing automated moderation actions.
+4
View File
@@ -247,6 +247,10 @@ class ReTriggerMixin(ABC):
async def toggle_nsfw(self, ctx: commands.Context, trigger: TriggerExists) -> None:
raise NotImplementedError()
@abstractmethod
async def toggle_read_embeds(self, ctx: commands.Context, trigger: TriggerExists) -> None:
raise NotImplementedError()
@abstractmethod
async def toggle_filename_search(self, ctx: commands.Context, trigger: TriggerExists) -> None:
raise NotImplementedError()
+3
View File
@@ -269,6 +269,7 @@ class Trigger:
"role_mention",
"everyone_mention",
"nsfw",
"read_embeds",
"_created_at",
"thread",
"remove_roles",
@@ -316,6 +317,7 @@ class Trigger:
self.role_mention: bool = kwargs.get("role_mention", False)
self.everyone_mention: bool = kwargs.get("everyone_mention", False)
self.nsfw: bool = kwargs.get("nsfw", False)
self.read_embeds: bool = kwargs.get("embeds", False)
self.thread: TriggerThread = kwargs.get("thread", TriggerThread())
self.remove_roles: List[int] = kwargs.get("remove_roles", [])
self.add_roles: List[int] = kwargs.get("add_roles", [])
@@ -473,6 +475,7 @@ class Trigger:
"everyone_mention": self.everyone_mention,
"role_mention": self.role_mention,
"nsfw": self.nsfw,
"read_embeds": self.read_embeds,
"thread": self.thread.to_json(),
"remove_roles": self.remove_roles,
"add_roles": self.add_roles,
+2
View File
@@ -211,6 +211,8 @@ class ReTriggerPages(menus.ListPageSource):
except Exception as e:
pattern_error = str(e)
pattern = trigger._raw_regex
if trigger.read_embeds:
info += _("__Read Embeds__: **Enabled**\n")
if embeds:
# info += _("__Regex__: ") + box(trigger.regex.pattern, lang="bf")
em = discord.Embed(
+2
View File
@@ -41,6 +41,8 @@ class ReTriggerMessage(discord.Message):
self.pinned = False
# suport for attachments somehow later maybe?
self.attachments: List[discord.Attachment] = message.attachments
# support for embed search
self.embeds = message.embeds
# mentions
self.mention_everyone = self.channel.permissions_for(
self.author
+26
View File
@@ -758,6 +758,32 @@ class ReTrigger(
msg = _("Trigger {name} NSFW set to: {nsfw}").format(name=trigger.name, nsfw=trigger.nsfw)
await ctx.send(msg)
@_edit.command(name="readembeds")
@checks.mod_or_permissions(manage_messages=True)
async def toggle_read_embeds(self, ctx: commands.Context, trigger: TriggerExists) -> None:
"""
Toggle whether a trigger will check embeds.
This will allow the additional searching of Embed content.
`<trigger>` is the name of the trigger.
See https://regex101.com/ for help building a regex pattern.
See `[p]retrigger explain` or click the link below for more details.
[For more details click here.](https://github.com/TrustyJAID/Trusty-cogs/blob/master/retrigger/README.md)
"""
if type(trigger) is str:
return await self._no_trigger(ctx, trigger)
if not await self.can_edit(ctx.author, trigger):
return await self._not_authorized(ctx)
trigger.read_embeds = not trigger.read_embeds
async with self.config.guild(ctx.guild).trigger_list() as trigger_list:
trigger_list[trigger.name] = await trigger.to_json()
# await self.remove_trigger_from_cache(ctx.guild.id, trigger)
# self.triggers[ctx.guild.id].append(trigger)
msg = _("Trigger {name} embeds set to: {embeds}").format(
name=trigger.name, embeds=trigger.read_embeds
)
await ctx.send(msg)
@_edit.command(name="readfilenames", aliases=["filenames"])
@checks.mod_or_permissions(manage_messages=True)
async def toggle_filename_search(self, ctx: commands.Context, trigger: TriggerExists) -> None:
+11
View File
@@ -266,6 +266,17 @@ class ReTriggerSlash(ReTriggerMixin):
ctx = await interaction.client.get_context(interaction)
await self.toggle_nsfw(ctx, trigger)
@edit_slash.command(name="readembeds")
@app_commands.checks.has_permissions(manage_messages=True)
async def toggle_read_embeds_slash(
self,
interaction: discord.Interaction,
trigger: app_commands.Transform[Trigger, TriggerTransformer],
):
"""Toggle whether to include embed contents in searched text."""
ctx = await interaction.client.get_context(interaction)
await self.toggle_read_embeds(ctx, trigger)
@edit_slash.command(name="readfilenames")
@app_commands.checks.has_permissions(manage_messages=True)
async def toggle_filename_search_slash(
+33 -2
View File
@@ -243,7 +243,7 @@ class TriggerHandler(ReTriggerMixin):
@commands.Cog.listener()
async def on_raw_message_edit(self, payload: discord.RawMessageUpdateEvent) -> None:
if "content" not in payload.data:
if "content" not in payload.data and "embeds" not in payload.data:
return
if "guild_id" not in payload.data:
return
@@ -257,7 +257,7 @@ class TriggerHandler(ReTriggerMixin):
if not any(t.check_edits for t in self.triggers[guild.id].values()):
# log.debug(f"No triggers in {guild=} have check_edits enabled")
return
if "bot" in payload.data["author"]:
if "bot" in payload.data.get("author", []):
return
channel = guild.get_channel(int(payload.data["channel_id"]))
try:
@@ -367,6 +367,11 @@ class TriggerHandler(ReTriggerMixin):
if trigger.ocr_search and ALLOW_OCR:
content += await self.get_image_text(message)
if trigger.read_embeds and len(message.embeds) > 0:
content += "\n".join(
self.convert_embed_to_string(embed, index)
for index, embed in enumerate(message.embeds)
)
if trigger.regex is None:
log.debug(
"ReTrigger: Trigger %r must have invalid regex.",
@@ -386,6 +391,32 @@ class TriggerHandler(ReTriggerMixin):
await self.perform_trigger(message, trigger, search[1])
return
@staticmethod
def convert_embed_to_string(embed: discord.Embed, embed_index: int = 0) -> str:
embed_dict = embed.to_dict()
flattened_embed_dict = {}
field_blacklist = ["type", "color", "proxy_url", "height", "width", "proxy_icon_url"]
for field, value in embed_dict.items():
if field in field_blacklist:
continue
if isinstance(value, dict):
for subfield in value:
if subfield in field_blacklist:
continue
flattened_embed_dict[f"{field.lower()}-{subfield.lower()}"] = value[subfield]
elif isinstance(value, list):
for field_index, embedfields in enumerate(value):
emfield_name = embedfields["name"].lower()
flattened_embed_dict[
f"{field.lower()}-{field_index}-{emfield_name}"
] = embedfields["value"]
else:
flattened_embed_dict[field.lower()] = value
return "\n".join(
f"embed-{embed_index}-{field}: {value}"
for field, value in flattened_embed_dict.items()
)
async def get_image_text(self, message: discord.Message) -> str:
"""
This function is built to asynchronously search images for text using pytesseract
-1
View File
@@ -148,7 +148,6 @@ class RoleTools(
self._ready.set()
async def cog_load(self) -> None:
if await self.config.version() < "1.0.1":
sticky_role_config = Config.get_conf(
None, identifier=1358454876, cog_name="StickyRoles"