Skip to content

Commit e1ef0b3

Browse files
author
Simon Berger
committed
ascii escape
1 parent ecc6aa5 commit e1ef0b3

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

gisi/cogs/ascii.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from discord.ext.commands import command
55

66
from gisi import SetDefaults
7+
from gisi.utils import text_utils
78

89
log = logging.getLogger(__name__)
910

@@ -21,7 +22,7 @@ def get_asciimoji(self, key):
2122

2223
def asciiemojify(self, text, require_wrapping=True):
2324
prog = r"(?<!\\)-(\w+)-" if require_wrapping else r"(\w+)"
24-
return re.sub(prog, lambda m: self.get_asciimoji(m.group(1).lower()) or m.group(0),
25+
return re.sub(prog, lambda m: text_utils.escape(self.get_asciimoji(m.group(1).lower())) or m.group(0),
2526
text)
2627

2728
@command()

gisi/utils/text_utils.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""Text utilities."""
2+
3+
from functools import partial
4+
5+
DISCORD_FORMATTING_CHARS = {"*", "_", "~", "`", "\\"}
6+
BOLD_SEQ = "**"
7+
ITALIC_SEQ = "*"
8+
STRIKETHROUGH_SEQ = "~~"
9+
CODE_SEQ = "```"
10+
URL_ESCAPE_SEQ = ("<", ">")
11+
12+
QUOTE_CHAR = "\""
13+
ESCAPE_CHAR = "\\"
14+
15+
16+
def wrap(s, wrap):
17+
"""Wrap around text."""
18+
if isinstance(wrap, (tuple, list, set)):
19+
start, end = wrap
20+
return start + s + end
21+
return wrap + s + wrap
22+
23+
24+
bold = partial(wrap, wrap=BOLD_SEQ)
25+
italic = partial(wrap, wrap=ITALIC_SEQ)
26+
strikethrough = partial(wrap, wrap=STRIKETHROUGH_SEQ)
27+
quote = partial(wrap, wrap=QUOTE_CHAR)
28+
escape_url = partial(wrap, wrap=URL_ESCAPE_SEQ)
29+
30+
31+
def code(s, lang):
32+
"""Put it in a code block."""
33+
return f"{CODE_SEQ}{lang}\n{s}{CODE_SEQ}"
34+
35+
36+
def escape(s):
37+
"""Escape discord formatting in string."""
38+
res = ""
39+
for c in s:
40+
if c in DISCORD_FORMATTING_CHARS:
41+
res += ESCAPE_CHAR
42+
res += c
43+
return res

0 commit comments

Comments
 (0)