Skip to content

Commit

Permalink
feat(quote): improve markdown escaping
Browse files Browse the repository at this point in the history
  • Loading branch information
ZRunner committed Feb 8, 2024
1 parent b3f0023 commit e65dc95
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
3 changes: 2 additions & 1 deletion fcts/quote.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from libs.arguments import args
from libs.bot_classes import Axobot
from libs.quote.generator import QuoteGeneration, QuoteStyle
from libs.text_cleanup import remove_markdown


class Quote(commands.Cog):
Expand Down Expand Up @@ -70,7 +71,7 @@ async def quote_message(
self, message: discord.Message, channel: discord.abc.Messageable, style: QuoteStyle
) -> Optional[discord.Message]:
"Generate a Quote card from a message and post it to the channel"
text = discord.utils.remove_markdown(message.clean_content)
text = remove_markdown(message.clean_content)
while '\n\n' in text:
text = text.replace('\n\n', '\n')
author_name = message.author.display_name
Expand Down
31 changes: 31 additions & 0 deletions libs/text_cleanup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import re

_MKD_LINE_BEGINNING = r'^([#>]{1,3} ?)(?P<lb_text>\S+)'
_MKD_CODE = r'(`+)(?P<code_text>[^`]+)(`+)'
_MKD_UNDERSCORE = r'(_+)(?P<underscore_text>[^_\n]+)(_+)'
_MKD_ASTERISK = r'(\*+)(?P<asterisk_text>[^*\n]+)(\*+)'
_MKD_SPOILER = r'(\|\|)(?P<spoiler_text>[^|\n]+)(\|\|)'
_MKD_TILDE = r'(~~)(?P<tilde_text>[^~\n]+)(~~)'
_MKD_FULL_REGEX = re.compile(
'(?:' +
'|'.join([
_MKD_LINE_BEGINNING,
_MKD_CODE,
_MKD_UNDERSCORE,
_MKD_ASTERISK,
_MKD_SPOILER,
_MKD_TILDE,
])
+ ')',
flags=re.MULTILINE
)

def _replacement(match: re.Match) -> str:
"""Replace a markdown match with its content"""
for text in match.groupdict().values():
if text:
return text
return ""

def remove_markdown(source: str):
return _MKD_FULL_REGEX.sub(_replacement, source)

0 comments on commit e65dc95

Please sign in to comment.