/
commandstats.py
379 lines (343 loc) · 12.9 KB
/
commandstats.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
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
import asyncio
import datetime
import logging
from collections import OrderedDict
from copy import deepcopy
from io import StringIO
from typing import Counter, Optional
import discord
import pandas
from redbot.core import Config, commands
from .menus import EmbedFormat, GenericMenu, LeaderboardSource
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i : i + n]
log = logging.getLogger("red.flare.commandstats")
class CommandStats(commands.Cog):
"""Command Statistics."""
__version__ = "0.1.1"
def format_help_for_context(self, ctx):
"""Thanks Sinbad."""
pre_processed = super().format_help_for_context(ctx)
return f"{pre_processed}\nCog Version: {self.__version__}"
def __init__(self, bot):
self.bot = bot
self.config = Config.get_conf(self, 1398467138476, force_registration=True)
default_global = {"globaldata": Counter({}), "guilddata": {}, "automated": Counter({})}
self.config.register_global(**default_global)
self.cache = {"guild": {}, "session": Counter({}), "automated": Counter({})}
self.session = Counter()
self.session_time = datetime.datetime.utcnow()
self.bg_loop_task = self.bot.loop.create_task(self.bg_loop())
async def red_get_data_for_user(self, *, user_id: int):
# this cog does not story any data
return {}
async def red_delete_data_for_user(self, *, requester, user_id: int) -> None:
# this cog does not story any data
pass
async def bg_loop(self):
await self.bot.wait_until_ready()
while True:
try:
await self.update_global()
await self.update_data()
await asyncio.sleep(300)
except Exception as exc:
log.error("Exception in bg_loop: ", exc_info=exc)
self.bg_loop_task.cancel()
def cog_unload(self):
if self.bg_loop_task:
self.bg_loop_task.cancel()
asyncio.create_task(self.update_data())
asyncio.create_task(self.update_global())
def record(self, ctx, name):
guild = ctx.message.guild
if not ctx.message.author.bot:
if getattr(ctx, "assume_yes", False):
if name not in self.cache["automated"]:
self.cache["automated"][name] = 1
else:
self.cache["automated"][name] += 1
return
if guild is not None:
if str(guild.id) not in self.cache["guild"]:
self.cache["guild"][str(guild.id)] = Counter({})
if name not in self.cache["guild"][str(guild.id)]:
self.cache["guild"][str(guild.id)][name] = 1
else:
self.cache["guild"][str(guild.id)][name] += 1
if name not in self.cache["session"]:
self.cache["session"][name] = 1
else:
self.cache["session"][name] += 1
if name not in self.session:
self.session[name] = 1
else:
self.session[name] += 1
@commands.Cog.listener()
async def on_command_completion(self, ctx):
"""Record standard command events."""
if not ctx.valid:
return
name = str(ctx.command)
self.record(ctx, name)
@commands.Cog.listener()
async def on_commandstats_action(self, ctx):
"""Record action events (i.e. other cog emits 'commandstats_action')."""
name = str(ctx.command)
self.record(ctx, name)
def build_data(self, data):
data = OrderedDict(sorted(data.items(), key=lambda t: t[1], reverse=True))
stats = []
for cmd, amount in data.items():
stats.append([f"{cmd}", f"{amount} time{'s' if amount != 1 else ''}"])
return list(chunks(stats, 15))
@commands.is_owner()
@commands.group(invoke_without_command=True)
async def cmd(self, ctx, *, command: str = None):
"""Group command for command stats.
This command does not log the issuing command.
"""
await self.update_global()
data = await self.config.globaldata()
if not data:
return await ctx.send("No commands have been used yet.")
if command is None:
await GenericMenu(
source=EmbedFormat(self.build_data(data)),
title="Commands Used",
_type="Command",
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
else:
if command in data:
await ctx.send(f"`{command}` has been used {data[command]} times!")
else:
await ctx.send(f"`{command}` hasn't been used yet!")
@cmd.command()
async def automated(self, ctx):
"""Automated command stats.
Commands that have `ctx.assume_yes` will qualify as automated."""
await self.update_global()
data = await self.config.automated()
if not data:
return await ctx.send("No commands have been used yet.")
await GenericMenu(
source=EmbedFormat(self.build_data(data)),
title="Automatic Commands Used",
_type="Command",
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
@cmd.command(aliases=["server"])
async def guild(
self,
ctx,
server: Optional[commands.GuildConverter] = None,
*,
command: str = None,
):
"""Guild Command Stats."""
if not server:
server = ctx.guild
await self.update_data()
data = await self.config.guilddata()
try:
data = data[str(server.id)]
except KeyError:
return await ctx.send(f"No commands have been used in {server.name} yet.")
if command is None:
await GenericMenu(
source=EmbedFormat(self.build_data(data)),
title=f"Commands Used in {server.name}",
_type="Command",
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
else:
if command in data:
await ctx.send(
f"`{command}` has been used {data[command]} time{'s' if data[command] > 1 else ''} in {ctx.guild}!"
)
else:
await ctx.send(f"`{command}` hasn't been used in {server.name}!")
@cmd.command()
async def session(self, ctx, *, command: str = None):
"""Session command stats."""
data = deepcopy(self.session)
if str(ctx.command) in data:
data[str(ctx.command)] += 1
else:
data[str(ctx.command)] = 1
if not data:
return await ctx.send("No commands have been used in this session")
if command is None:
await GenericMenu(
source=EmbedFormat(self.build_data(data)),
title="Commands Used during session",
_type="Command",
ctx=ctx,
timestamp=self.session_time,
).start(
ctx=ctx,
wait=False,
)
else:
if command in data:
await ctx.send(
f"`{command}` has been used {data[command]} time{'s' if data[command] > 1 else ''} in this session!"
)
else:
await ctx.send(f"`{command}` hasn't been used in this session!")
@cmd.group(invoke_without_command=True)
async def cogstats(self, ctx, *, cogname: str = None):
"""Show command stats per cog, all cogs or per session."""
await self.update_global()
if cogname is not None:
cog = self.bot.get_cog(cogname)
if cog is None:
await ctx.send("No such cog.")
return
commands = set([x.qualified_name for x in cog.walk_commands()])
data = await self.config.globaldata()
a = {}
for command in data:
if command in commands:
a[command] = data[command]
if not a:
await ctx.send(f"No commands used from {cogname} as of yet.")
return
await GenericMenu(
source=EmbedFormat(self.build_data(a)),
title=f"{cogname} Commands Used",
_type="Command",
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
else:
data = await self.config.globaldata()
a = {}
for cogn in self.bot.cogs:
cog = self.bot.get_cog(cogn)
commands = set([x.qualified_name for x in cog.walk_commands()])
a[cogn] = 0
for command in data:
if command in commands:
a[cogn] += data[command]
if not a:
await ctx.send(f"No commands used from any cog as of yet.")
return
await GenericMenu(
source=EmbedFormat(self.build_data(a)),
title="Cogs Used",
_type="Cog",
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
@cogstats.command(name="session")
async def _session(self, ctx, *, cogname: str = None):
"""Cog stats in this session."""
await self.update_global()
if cogname is not None:
cog = self.bot.get_cog(cogname)
if cog is None:
await ctx.send("No such cog.")
return
commands = set([x.qualified_name for x in cog.walk_commands()])
data = deepcopy(self.session)
a = {}
for command in data:
if command in commands:
a[command] = data[command]
if not a:
await ctx.send(f"No commands used from {cogname} as of yet.")
return
await GenericMenu(
source=EmbedFormat(self.build_data(a)),
title=f"{cogname} Commands Used During Session",
_type="Command",
ctx=ctx,
timestamp=self.session_time,
).start(
ctx=ctx,
wait=False,
)
else:
data = deepcopy(self.session)
a = {}
for cogn in self.bot.cogs:
cog = self.bot.get_cog(cogn)
commands = set([x.qualified_name for x in cog.walk_commands()])
a[cogn] = 0
for command in data:
if command in commands:
a[cogn] += data[command]
if not a:
await ctx.send(f"No commands used from any cog as of yet.")
return
await GenericMenu(
source=EmbedFormat(self.build_data(a)),
title="Cogs Used During Session",
_type="Cog",
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
@cmd.command()
async def csv(self, ctx):
"""Return a CSV of all command actions."""
await self.update_global()
data = await self.config.globaldata()
df = pandas.DataFrame.from_dict(data, orient="index", columns=["Usage"])
df.index.name = "Commands"
s_buf = StringIO()
df.to_csv(s_buf)
s_buf.name = "commandstats.csv"
s_buf.seek(0)
await ctx.send(file=discord.File(s_buf))
@cmd.command()
@commands.is_owner()
async def guilds(self, ctx):
"""Leaderboard of guilds by most commands used."""
await self.update_data()
data = await self.config.guilddata()
guildata = [(k, sum(data[k].values())) for k in data]
await GenericMenu(
source=LeaderboardSource(sorted(guildata, key=lambda x: x[1], reverse=True)),
ctx=ctx,
).start(
ctx=ctx,
wait=False,
)
async def update_data(self):
async with self.config.guilddata() as guilddata:
for guild in self.cache["guild"]:
if guild in guilddata:
olddata = Counter(guilddata[guild])
else:
olddata = Counter({})
data = Counter(olddata + self.cache["guild"][guild])
self.cache["guild"][guild] = Counter()
guilddata[guild] = data
async def update_global(self):
globaldata = await self.config.globaldata()
data = globaldata + self.cache["session"]
await self.config.globaldata.set(data)
self.cache["session"] = Counter({})
autodata = await self.config.automated()
data = autodata + self.cache["automated"]
await self.config.automated.set(data)
self.cache["automated"] = Counter({})