aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRapptz <[email protected]>2019-04-06 20:14:05 -0400
committerRapptz <[email protected]>2019-04-06 20:14:05 -0400
commit9833ea82e247c0a01218d221293c9ed56b89d505 (patch)
tree70ab5a9d4fc94eab176b2170adc11bcd0d0cfed4
parent[commands] Disallow bot_ or cog_ commands or listeners in cogs. (diff)
downloaddiscord.py-9833ea82e247c0a01218d221293c9ed56b89d505.tar.xz
discord.py-9833ea82e247c0a01218d221293c9ed56b89d505.zip
Add helpers to escape markdown and mentions from text.
Fixes #1673
-rw-r--r--discord/ext/commands/converter.py8
-rw-r--r--discord/utils.py40
-rw-r--r--docs/api.rst5
3 files changed, 47 insertions, 6 deletions
diff --git a/discord/ext/commands/converter.py b/discord/ext/commands/converter.py
index 8676329c..0ca9096b 100644
--- a/discord/ext/commands/converter.py
+++ b/discord/ext/commands/converter.py
@@ -474,14 +474,10 @@ class clean_content(Converter):
result = pattern.sub(repl, argument)
if self.escape_markdown:
- result = re.sub(r'\\', r'\\\\', result)
- for c in ('*', '`', '_', '~', '|'):
- regex = r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c)
- replace = '\{0}'.format(c)
- result = re.sub(regex, replace, result)
+ result = discord.utils.escape_markdown(result)
# Completely ensure no mentions escape:
- return re.sub(r'@(everyone|here|[!&]?[0-9]{17,21})', '@\u200b\\1', result)
+ return discord.utils.escape_mentions(result)
class _Greedy:
__slots__ = ('converter',)
diff --git a/discord/utils.py b/discord/utils.py
index 96a26918..e277e56c 100644
--- a/discord/utils.py
+++ b/discord/utils.py
@@ -366,3 +366,43 @@ def resolve_invite(invite):
return m.group(1)
return invite
+_MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(c)
+ for c in ('*', '`', '_', '~', '|'))
+
+_MARKDOWN_ESCAPE_REGEX = re.compile('(%s)' % _MARKDOWN_ESCAPE_SUBREGEX)
+
+def escape_markdown(text):
+ """A helper function that escapes Discord's markdown.
+
+ Parameters
+ -----------
+ text: :class:`str`
+ The text to escape markdown from.
+
+ Returns
+ --------
+ :class:`str`
+ The text with the markdown special characters escaped with a slash.
+ """
+
+ text = re.sub(r'\\', r'\\\\', text)
+ return _MARKDOWN_ESCAPE_REGEX.sub(r'\\\1', text)
+
+def escape_mentions(text):
+ """A helper function that escapes everyone, here, role, and user mentions.
+
+ .. note::
+
+ This does not include channel mentions.
+
+ Parameters
+ -----------
+ text: :class:`str`
+ The text to escape mentions from.
+
+ Returns
+ --------
+ :class:`str`
+ The text with the mentions removed.
+ """
+ return re.sub(r'@(everyone|here|[!&]?[0-9]{17,21})', r'@\u200b\1', text)
diff --git a/docs/api.rst b/docs/api.rst
index 7ba1a996..9208dafd 100644
--- a/docs/api.rst
+++ b/docs/api.rst
@@ -583,6 +583,11 @@ Utility Functions
.. autofunction:: discord.utils.oauth_url
+.. autofunction:: discord.utils.escape_markdown
+
+.. autofunction:: discord.utils.escape_mentions
+
+
Application Info
------------------