aboutsummaryrefslogtreecommitdiff
path: root/discord/utils.py
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 /discord/utils.py
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
Diffstat (limited to 'discord/utils.py')
-rw-r--r--discord/utils.py40
1 files changed, 40 insertions, 0 deletions
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)