-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcog.py
More file actions
525 lines (475 loc) · 20.5 KB
/
cog.py
File metadata and controls
525 lines (475 loc) · 20.5 KB
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
from __future__ import annotations
import asyncio
import linecache
import logging
import tracemalloc
from io import StringIO
from pathlib import Path
import discord
from discord import AppCommandType
from redbot.core import commands
from redbot.core.i18n import Translator, cog_i18n
from redbot.core.utils.chat_formatting import box, humanize_number, inline, pagify
from rich.console import Console
from rich.tree import Tree
from tabulate import tabulate
from pylav.compat import json
from pylav.core.context import PyLavContext
from pylav.exceptions.request import HTTPException
from pylav.extension.red.utils.decorators import requires_player
from pylav.helpers.discord.converters.queries import QueryConverter
from pylav.helpers.format.ascii import EightBitANSI
from pylav.logging import getLogger
from pylav.type_hints.bot import DISCORD_BOT_TYPE, DISCORD_COG_TYPE_MIXIN
LOGGER = getLogger("PyLav.cog.Utils")
_ = Translator("PyLavUtils", Path(__file__))
def get_top(snapshot, key_type="lineno", limit=10):
snapshot = snapshot.filter_traces(
(
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
)
)
top_stats = snapshot.statistics(key_type)
response = ""
response += f"Top {limit} lines"
for index, stat in enumerate(top_stats[:limit], 1):
frame = stat.traceback[0]
response += f"\n\n#{index}: {frame.filename}:{frame.lineno}: {stat.size / 1024:.1f} KiB"
if line := linecache.getline(frame.filename, frame.lineno).strip():
response += f"\n {line}"
if other := top_stats[limit:]:
size = sum(stat.size for stat in other)
response += f"\n\n{len(other)} other: {size / 1024:.1f} KiB"
total = sum(stat.size for stat in top_stats)
response += f"\n\nTotal allocated size: {total / 1024:.1f} KiB"
return response
@cog_i18n(_)
class PyLavUtils(DISCORD_COG_TYPE_MIXIN):
"""Utility commands for PyLav"""
__version__ = "1.0.0"
def __init__(self, bot: DISCORD_BOT_TYPE, *args, **kwargs):
super().__init__(*args, **kwargs)
self.bot = bot
@commands.group(name="plutils")
async def command_plutils(self, context: PyLavContext):
"""Utility commands for PyLav"""
@command_plutils.command(name="version")
async def command_plutils_version(self, context: PyLavContext) -> None:
"""Show the version of the Cog and PyLav"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
data = [
(EightBitANSI.paint_white(self.__class__.__name__), EightBitANSI.paint_blue(self.__version__)),
(EightBitANSI.paint_white("PyLav"), EightBitANSI.paint_blue(context.pylav.lib_version)),
]
await context.send(
embed=await context.pylav.construct_embed(
description=box(
tabulate(
data,
headers=(
EightBitANSI.paint_yellow(_("Library / Cog"), bold=True, underline=True),
EightBitANSI.paint_yellow(_("Version"), bold=True, underline=True),
),
tablefmt="fancy_grid",
),
lang="ansi",
),
messageable=context,
),
ephemeral=True,
)
@command_plutils.command(name="slashes")
async def command_plutils_slashes(self, context: PyLavContext):
"""Show the slashes available in the bot.
Author: TrustyJAID#0001 via code block on Discord channel.
"""
def rich_walk_commands(group: list, tree: Tree):
for command in group:
if isinstance(command, discord.app_commands.Group):
branch = tree.add(command.name, style="green")
rich_walk_commands(command.commands, branch)
elif isinstance(command, discord.app_commands.Command):
tree.add(command.name, style="not bold white")
elif isinstance(command, discord.app_commands.ContextMenu):
if command.type == AppCommandType.user:
tree.add(
_("{command_name_do_not_translate} # User menu").format(
command_name_do_not_translate=command.name
),
style="not bold cyan",
)
elif command.type == AppCommandType.message:
tree.add(
_("{command_name_do_not_translate} # Message menu").format(
command_name_do_not_translate=command.name
),
style="not bold magenta",
)
else:
tree.add(
_("{command_name_do_not_translate} # Unknown menu").format(
command_name_do_not_translate=command.name
),
style="not bold yellow",
)
else:
tree.add(command.name, style="not bold red")
all_commands = self.bot.tree.get_commands()
rich_tree = Tree("Slash Commands", style="bold yellow")
rich_walk_commands(all_commands, rich_tree)
temp_console = Console( # Prevent messing with STDOUT's console
color_system="standard", # Discord only supports 8-bit in colors
file=StringIO(),
force_terminal=True,
force_interactive=False,
width=40,
)
temp_console.print(rich_tree)
msg = "\n".join(line.rstrip() for line in temp_console.file.getvalue().split("\n")) # type: ignore
await context.send_interactive(messages=pagify(msg), box_lang="ansi")
@command_plutils.group(name="get")
@requires_player()
async def command_plutils_get(self, context: PyLavContext):
"""Get info about specific things"""
@command_plutils_get.command(name="b64")
async def command_plutils_get_b64(self, context: PyLavContext):
"""Get the base64 of the current track"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
if not context.player:
await context.send(
embed=await context.pylav.construct_embed(
description=_("You must be in a voice channel, so I can connect to it."), messageable=context
),
ephemeral=True,
)
return
if not context.player.current:
await context.send(
embed=await context.pylav.construct_embed(
description=_("I am not currently playing anything on this server."), messageable=context
),
ephemeral=True,
)
return
await context.send(
embed=await context.pylav.construct_embed(
description=inline(context.player.current.encoded),
messageable=context,
),
ephemeral=True,
)
@command_plutils_get.command(name="author")
async def command_plutils_get_author(self, context: PyLavContext):
"""Get the author of the current track"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
if not context.player:
await context.send(
embed=await context.pylav.construct_embed(
description=_("You must be in a voice channel, so I can connect to it."), messageable=context
),
ephemeral=True,
)
return
if not context.player.current:
await context.send(
embed=await context.pylav.construct_embed(
description=_("I am not currently playing anything on this server."), messageable=context
),
ephemeral=True,
)
return
await context.send(
embed=await context.pylav.construct_embed(
description=inline(await context.player.current.author()),
messageable=context,
),
ephemeral=True,
)
@command_plutils_get.command(name="title")
async def command_plutils_get_title(self, context: PyLavContext):
"""Get the title of the current track"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
if not context.player:
await context.send(
embed=await context.pylav.construct_embed(
description=_("You must be in a voice channel, so I can connect to it."), messageable=context
),
ephemeral=True,
)
return
if not context.player.current:
await context.send(
embed=await context.pylav.construct_embed(
description=_("I am not currently playing anything on this server."), messageable=context
),
ephemeral=True,
)
return
await context.send(
embed=await context.pylav.construct_embed(
description=inline(await context.player.current.title()),
messageable=context,
),
ephemeral=True,
)
@command_plutils_get.command(name="source")
async def command_plutils_get_source(self, context: PyLavContext):
"""Get the source of the current track"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
if not context.player:
await context.send(
embed=await context.pylav.construct_embed(
description=_("You must be in a voice channel, so I can connect to it."), messageable=context
),
ephemeral=True,
)
return
if not context.player.current:
await context.send(
embed=await context.pylav.construct_embed(
description=_("I am not currently playing anything on this server."), messageable=context
),
ephemeral=True,
)
return
await context.send(
embed=await context.pylav.construct_embed(
description=inline(await context.player.current.source()),
messageable=context,
),
ephemeral=True,
)
@command_plutils_get.command(name="player")
@commands.is_owner()
async def command_plutils_get_api(self, context: PyLavContext):
"""Get the API of the current track"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
if not context.player:
await context.send(
embed=await context.pylav.construct_embed(
description=_("You must be in a voice channel, so I can connect to it."), messageable=context
),
ephemeral=True,
)
return
try:
node_player = await context.player.fetch_node_player()
except Exception: # noqa
await context.send(
embed=await context.pylav.construct_embed(
description=_("Unable to get player info."), messageable=context
),
ephemeral=True,
)
return
if isinstance(node_player, HTTPException):
await context.send(
embed=await context.pylav.construct_embed(
description=_("Unable to get player info."), messageable=context
),
ephemeral=True,
)
return
data = node_player.to_dict()
await context.send(
embed=await context.pylav.construct_embed(
description=box(json.dumps(data, indent=2), lang="json"),
messageable=context,
),
ephemeral=True,
)
@command_plutils.command(name="decode")
async def command_plutils_decode(self, context: PyLavContext, *, base64: str):
"""Decode the track base64 string into a JSON object"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
try:
data = await self.pylav.decode_track(base64, raise_on_failure=True)
except Exception: # noqa
await context.send(
embed=await context.pylav.construct_embed(description=_("Invalid base64 string."), messageable=context),
ephemeral=True,
)
return
else:
await context.send(
embed=await context.pylav.construct_embed(
description=box(lang="json", text=json.dumps(data.info.to_dict(), indent=2, sort_keys=True)),
messageable=context,
),
ephemeral=True,
)
@commands.is_owner()
@command_plutils.group(name="cache")
async def command_plutils_cache(self, context: PyLavContext):
"""Manage the query cache"""
@command_plutils_cache.command(name="clear")
async def command_plutils_cache_clear(self, context: PyLavContext):
"""Clear the query cache"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
await self.pylav.query_cache_manager.wipe()
await context.send(
embed=await context.pylav.construct_embed(description=_("Query cache cleared."), messageable=context),
ephemeral=True,
)
@command_plutils_cache.command(name="older")
async def command_plutils_cache_older(self, context: PyLavContext, days: int):
"""Clear the query cache older than a number of days"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
if days > 31:
await context.send(
embed=await context.pylav.construct_embed(
description=_("Days must be less than 31."), messageable=context
),
ephemeral=True,
)
return
elif days < 1:
await context.send(
embed=await context.pylav.construct_embed(
description=_("Days must be greater than 1."), messageable=context
),
ephemeral=True,
)
return
await self.pylav.query_cache_manager.delete_older_than(days=days)
await context.send(
embed=await context.pylav.construct_embed(description=_("Query cache cleared."), messageable=context),
ephemeral=True,
)
@command_plutils_cache.command(name="query")
async def command_plutils_cache_query(self, context: PyLavContext, *, query: QueryConverter):
"""Clear the query cache for a query"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
await self.pylav.query_cache_manager.delete_query(query)
await context.send(
embed=await context.pylav.construct_embed(description=_("Query cache cleared."), messageable=context),
ephemeral=True,
)
@command_plutils_cache.command(name="size")
async def command_plutils_cache_size(self, context: PyLavContext):
"""Get the size of the query cache"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
await context.send(
embed=await context.pylav.construct_embed(
description=_("Query cache size: `{size_variable_do_not_translate}`.").format(
size_variable_do_not_translate=humanize_number(await self.pylav.query_cache_manager.size())
),
messageable=context,
),
ephemeral=True,
)
@commands.is_owner()
@command_plutils.command(name="trace", hidden=True)
async def command_plutils_trace(self, context: PyLavContext, value: int = -1):
"""Start memory tracing
`[p]plutils trace 0` turns off tracing
`[p]plutils trace 1` turns on tracing
`[p]plutils trace` shows the current status of tracing
"""
import tracemalloc
if tracemalloc.is_tracing():
snap = await asyncio.to_thread(tracemalloc.take_snapshot)
if value == 0:
tracemalloc.stop()
await context.send(
embed=await context.pylav.construct_embed(
description=_("I have stopped memory tracing"),
messageable=context,
),
ephemeral=True,
)
elif not tracemalloc.is_tracing() and value == 1:
tracemalloc.start(25)
await context.send(
embed=await context.pylav.construct_embed(
description=_("I have started memory tracing."),
messageable=context,
),
ephemeral=True,
)
return
if not tracemalloc.is_tracing():
await context.send(
embed=await context.pylav.construct_embed(
description=_("You need to start tracing first."),
messageable=context,
),
ephemeral=True,
)
else:
messages = pagify(await asyncio.to_thread(get_top, snap, limit=10), page_length=3500) # noqa
await context.send_interactive(messages, box_lang="py")
@commands.is_owner()
@command_plutils.command(name="logger")
async def command_plutils_logger(self, context: PyLavContext, *, level: int):
"""Set the logger level
Levels are the following:
0: Critical
1: Error
2: Warning
3: Info
4: Debug
5: Verbose
6: Trace
"""
if isinstance(context, discord.Interaction):
context = await self.bot.get_context(context)
if context.interaction and not context.interaction.response.is_done():
await context.defer(ephemeral=True)
level_map = {
0: logging.CRITICAL,
1: logging.ERROR,
2: logging.WARNING,
3: logging.INFO,
4: logging.DEBUG,
5: logging.DEBUG - 3,
6: logging.DEBUG - 5,
}
if level not in level_map:
await context.send_help()
return
logger = getLogger("PyLav")
logger.setLevel(level_map[level])
await context.send(
embed=await context.pylav.construct_embed(
description=_("Logger level set to `{level_variable_do_not_translate}`.").format(
level_variable_do_not_translate=logging.getLevelName(logger.level)
),
messageable=context,
),
ephemeral=True,
)