-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.py
252 lines (189 loc) · 6.79 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import asyncio
from datetime import datetime
import logging
import os
import re
import subprocess
import sys
import discord
from discord.ext.commands import errors
log = logging.getLogger(__name__)
def snakify(name):
"""Turn CamelCase into snake_case."""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
def fix_unicode():
"""Make python not crash when logging trivial statements."""
if os.name == "nt":
sys.stdout = sys.__stdout__ = open(
sys.stdout.detach().fileno(), 'w', encoding=sys.stdout.encoding,
errors="backslashreplace")
sys.stderr = sys.__stderr__ = open(
sys.stderr.detach().fileno(), 'w', encoding=sys.stderr.encoding,
errors="backslashreplace")
class AsyncContextWrapper:
def __init__(self, coro):
self.coro = coro
async def __aenter__(self):
self.wrapped = await self.coro
return await self.wrapped.__aenter__()
async def __aexit__(self, *args, **kwargs):
return await self.wrapped.__aexit__(*args, **kwargs)
async def run_subprocess(cmd, loop=None):
try:
proc = await asyncio.create_subprocess_shell(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
res = await proc.communicate()
except NotImplementedError:
loop = loop or asyncio.get_event_loop()
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
res = await loop.run_in_executor(None, proc.communicate)
return [s.decode('utf8') for s in res]
class TypeMap:
"""Dict that looks up based on a class's bases.
In the case of conflict, will return the first matching base.
Lookup time is O(n), where n is # of bases a class has.
"""
def __init__(self, dct=None):
self._dict = dct or {}
def put(self, cls, obj):
self._dict[cls] = obj
def lookup(self, cls):
for base in cls.__mro__:
try:
return self._dict[base]
except KeyError:
pass
def clean_invite_embed(line):
"""Makes invites not embed"""
return line.replace("discord.gg/", "discord.gg/\u200b")
def clean_single_backtick(line):
"""Clean string for insertion in single backtick code section."""
if re.search('[^`]`[^`]', line) is not None:
raise ValueError("Cannot be cleaned")
if (line[:2] == '``'):
line = '\u200b' + line
if (line[-1] == '`'):
line = line + '\u200b'
return line
def clean_double_backtick(line):
"""Clean string for isnertion in double backtick code section."""
line.replace('``', '`\u200b`')
if (line[0] == '`'):
line = '\u200b' + line
if (line[-1] == '`'):
line = line + '\u200b'
return line
def clean_triple_backtick(line):
"""Clean string for insertion in triple backtick code section."""
if not line:
return line
i = 0
n = 0
while i < len(line):
if (line[i]) == '`':
n += 1
if n == 3:
line = line[:i] + '\u200b' + line[i:]
n = 1
i += 1
i += 1
if line[-1] == '`':
line += '\u200b'
return line
def clean_newline(line):
"""Cleans string so formatting does not cross lines when joined with \\n.
Just looks for unpaired '`' characters, other formatting characters do not
seem to be joined across newlines.
For reference, discord uses:
https://github.com/Khan/simple-markdown/blob/master/simple-markdown.js
"""
match = None
for match1 in re.finditer(r'(`+)\s*([\s\S]*?[^`])\s*\1(?!`)', line):
match = match1
idx = match.end() if match else 0
line = line[:idx] + line[idx:].replace('`', '\`')
return line
def clean_formatting(line):
"""Escape formatting items in a string."""
return re.sub(r"([`*_])", r"\\\1", line)
def clean_mentions(line):
"""Escape anything that could resolve to mention."""
return line.replace("@", "@\u200b")
def log_task(fut):
try:
if fut.exception():
e = fut.exception()
log.warn("", exc_info=(type(e), e, e.__traceback__))
except asyncio.CancelledError as e:
log.debug("", exc_info=(type(e), e, e.__traceback__))
def create_task(thing):
task = asyncio.ensure_future(thing)
task.add_done_callback(log_task)
return task
class InfoBuilder:
def __init__(self, fields=None, description=""):
self.description = description
self.fields = fields or []
def add_field(self, name, value):
self.fields.append((name, value))
def code_block(self):
col_len = max(len(name) for name, _ in self.fields)
return "```prolog\n\u200b{}```".format(
clean_invite_embed(clean_triple_backtick(clean_mentions(
"\n".join("{}: {}".format(
k.rjust(col_len), v) for k, v in self.fields)))))
def embed(self):
e = discord.Embed()
for k, v in self.fields:
e.add_field(name=k, value=v)
return e
def resolve_color(value):
"""Resolve a custom or pre-defined color.
This allows html style #123456.
"""
if value.startswith('#'):
value = value[1:] # assumes no named color starts with #
try:
intval = int(value, 16)
except ValueError:
pass
else:
if intval >= (1 << 24):
raise errors.BadArgument("Invalid color {} is too big!".format(value))
return discord.Colour(intval)
try:
return getattr(discord.Colour, value)()
except AttributeError:
raise errors.BadArgument("Invalid color {}".format(value))
def convert_date(argument):
formats = (
'%Y/%m/%d',
'%Y-%m-%d',
)
for fmt in formats:
try:
return datetime.strptime(argument, fmt)
except ValueError:
continue
raise errors.BadArgument(
'Cannot convert to date. Expected YYYY/MM/DD or YYYY-MM-DD.')
def emoji_url(emoji):
return "http://twemoji.maxcdn.com/2/72x72/{}.png".format(
"-".join("{:x}".format(ord(c)) for c in emoji))
class _LoadingEmojiContext():
def __init__(self, ctx):
self.ctx = ctx
async def __aenter__(self):
await self.ctx.message.add_reaction("a:loading:393852367751086090")
async def __aexit__(self, exc_type, exc, tb):
await self.ctx.message.remove_reaction("a:loading:393852367751086090", self.ctx.me)
if exc is None:
await self.ctx.message.add_reaction(":helYea:236243426662678528")
else:
await self.ctx.message.add_reaction(":discordok:293495010719170560")
def loading_emoji(ctx):
return _LoadingEmojiContext(ctx)
def jump_url(message):
return "<https://discordapp.com/channels/{0.channel.guild.id}/{0.channel.id}/{0.id}>".format(message)