Browse Source

Add ignore_links and as_needed options to utils.escape_markdown.

This allows for URLs to be left alone since they can include markdown
characters and allows for total escaping of all markdown characters
by default to prevent some form of data manipulation.
pull/2049/head
Rapptz 6 years ago
parent
commit
4d06879669
  1. 35
      discord/utils.py

35
discord/utils.py

@ -369,15 +369,26 @@ def resolve_invite(invite):
_MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c) _MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c)
for c in ('*', '`', '_', '~', '|')) for c in ('*', '`', '_', '~', '|'))
_MARKDOWN_ESCAPE_REGEX = re.compile('(%s)' % _MARKDOWN_ESCAPE_SUBREGEX) _MARKDOWN_ESCAPE_REGEX = re.compile(r'(?P<markdown>%s)' % _MARKDOWN_ESCAPE_SUBREGEX)
def escape_markdown(text): def escape_markdown(text, *, as_needed=False, ignore_links=True):
"""A helper function that escapes Discord's markdown. r"""A helper function that escapes Discord's markdown.
Parameters Parameters
----------- -----------
text: :class:`str` text: :class:`str`
The text to escape markdown from. The text to escape markdown from.
as_needed: :class:`bool`
Whether to escape the markdown characters as needed. This
means that it does not escape extraneous characters if it's
not necessary, e.g. ``**hello**`` is escaped into ``\*\*hello**``
instead of ``\*\*hello\*\*``. Note however that this can open
you up to some clever syntax abuse. Defaults to ``False``.
ignore_links: :class:`bool`
Whether to leave links alone when escaping markdown. For example,
if a URL in the text contains characters such as ``_`` then it will
be left alone. This option is not supported with ``as_needed``.
Defaults to ``True``.
Returns Returns
-------- --------
@ -385,8 +396,22 @@ def escape_markdown(text):
The text with the markdown special characters escaped with a slash. The text with the markdown special characters escaped with a slash.
""" """
text = re.sub(r'\\', r'\\\\', text) if not as_needed:
return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text) url_regex = r'(?P<url>(?:https?|steam)://(?:-\.)?(?:[^\s/?\.#-]+\.?)+(?:/[^\s]*)?)'
def replacement(match):
groupdict = match.groupdict()
is_url = groupdict.get('url')
if is_url:
return is_url
return '\\' + groupdict['markdown']
regex = r'(?P<markdown>[_\\~|\*])'
if ignore_links:
regex = '(?:%s|%s)' % (url_regex, regex)
return re.sub(regex, replacement, text)
else:
text = re.sub(r'\\', r'\\\\', text)
return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)
def escape_mentions(text): def escape_mentions(text):
"""A helper function that escapes everyone, here, role, and user mentions. """A helper function that escapes everyone, here, role, and user mentions.

Loading…
Cancel
Save