-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcog.py
565 lines (497 loc) · 20.2 KB
/
cog.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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import nextcord
import sqlalchemy
import database
import constants
from nextcord.ext import commands
from sqlalchemy.orm import Session
from utils import discord_utils, logging_utils, command_predicates
from database import models
from typing import Union
"""
Admin module. Bundle of commands related to Bot management and permission categories,
as well as other commands useful for bot owners and admins generally.
"""
class AdminCog(commands.Cog, name="Admin"):
"""
Commands for bot owners and bot management commands for server admins.
"""
def __init__(self, bot):
self.bot = bot
################################
# PERMISSION CATEGORY COMMANDS #
################################
@command_predicates.is_bot_owner_or_admin()
@commands.command(
name="addperm", aliases=["addverifieds", "addverified", "addperms"]
)
async def addperm(
self, ctx, role_permissions: str, role_or_rolename: Union[nextcord.Role, str]
):
"""Add a new Permission Category for a given role on this server. Only available to server admins or bot owners.
This command is necessary before most to all bot commands. Nearly all commands are restricted to some Permission Category or the other.
The Permission Categories available are - Verified, Trusted, Solver, Tester.
See `~permcathelp` for more info.
Permission Category : Admin or Bot Owner Roles only.
Usage: `~addperm Verified @VerifiedRoleName`
Usage: `~addperm Trusted @everyone`
"""
await logging_utils.log_command("addperm", ctx.guild, ctx.channel, ctx.author)
embed = discord_utils.create_embed()
if role_permissions not in database.VERIFIED_CATEGORIES:
embed = discord_utils.create_embed()
embed.add_field(
name=f"{constants.FAILED}",
value=f"`role_permissions` must be in {', '.join(database.VERIFIED_CATEGORIES)}, "
f"but you supplied {role_permissions}",
)
await ctx.send(embed=embed)
return
role_to_assign = await discord_utils.find_role(ctx, role_or_rolename)
# Ensure role exists
if role_to_assign is None:
embed = discord_utils.create_embed()
embed.add_field(
name=f"Error!",
value=f"I couldn't find role {role_or_rolename}",
inline=False,
)
await ctx.send(embed=embed)
return
with Session(database.DATABASE_ENGINE) as session:
result = (
session.query(database.Verifieds)
.filter_by(
role_id_permissions=f"{role_to_assign.id}_{role_permissions}"
)
.first()
)
if result is None:
stmt = sqlalchemy.insert(database.Verifieds).values(
role_id=role_to_assign.id,
role_name=role_to_assign.name,
server_id=ctx.guild.id,
server_name=ctx.guild.name,
permissions=role_permissions,
role_id_permissions=f"{role_to_assign.id}_{role_permissions}",
)
session.execute(stmt)
session.commit()
else:
embed = discord_utils.create_embed()
embed.add_field(
name=f"{constants.FAILED}!",
value=f"Role {role_to_assign.mention} is already `{result.permissions}`!",
)
await ctx.send(embed=embed)
return
if role_permissions == models.VERIFIED:
if ctx.guild.id in database.VERIFIEDS:
database.VERIFIEDS[ctx.guild.id].append(role_to_assign.id)
else:
database.VERIFIEDS[ctx.guild.id] = [role_to_assign.id]
elif role_permissions == models.TRUSTED:
if ctx.guild.id in database.TRUSTEDS:
database.TRUSTEDS[ctx.guild.id].append(role_to_assign.id)
else:
database.TRUSTEDS[ctx.guild.id] = [role_to_assign.id]
elif role_permissions == models.SOLVER:
if ctx.guild.id in database.SOLVERS:
database.SOLVERS[ctx.guild.id].append(role_to_assign.id)
else:
database.SOLVERS[ctx.guild.id] = [role_to_assign.id]
elif role_permissions == models.TESTER:
if ctx.guild.id in database.TESTERS:
database.TESTERS[ctx.guild.id].append(role_to_assign.id)
else:
database.TESTERS[ctx.guild.id] = [role_to_assign.id]
embed.add_field(
name=f"{constants.SUCCESS}",
value=f"Added the role {role_to_assign.mention} for this server set to `{role_permissions}`",
inline=False,
)
await ctx.send(embed=embed)
@command_predicates.is_bot_owner_or_admin()
@commands.command(
name="listperm",
aliases=[
"lsperms",
"listperms",
"lsperm",
],
)
async def listperm(self, ctx, role_permissions: str):
"""List all roles in the given Permission Category within the server.
See also: `~addperms`
Permission Category : Admin or Bot Owner Roles only.
Usage: `~listperm Verified`
"""
await logging_utils.log_command("listperm", ctx.guild, ctx.channel, ctx.author)
embed = discord_utils.create_embed()
if role_permissions not in database.VERIFIED_CATEGORIES:
embed = discord_utils.create_embed()
embed.add_field(
name=f"{constants.FAILED}",
value=f"`role_permissions` must be in `{', '.join(database.VERIFIED_CATEGORIES)}`, "
f"but you supplied `{role_permissions}`",
)
await ctx.send(embed=embed)
return
cache_map = {
models.VERIFIED: database.VERIFIEDS,
models.TRUSTED: database.TRUSTEDS,
models.SOLVER: database.SOLVERS,
models.TESTER: database.TESTERS,
}
if (
ctx.guild.id in cache_map[role_permissions]
and len(cache_map[role_permissions][ctx.guild.id]) > 0
):
embed.add_field(
name=f"{role_permissions}s for {ctx.guild.name}",
value=f"{' '.join([ctx.guild.get_role(role).mention for role in cache_map[role_permissions][ctx.guild.id]])}",
inline=False,
)
else:
embed.add_field(
name=f"No {role_permissions} roles for {ctx.guild.name}",
value=f"Set up `{role_permissions}` roles with `{ctx.prefix}addverified`",
inline=False,
)
await ctx.send(embed=embed)
@command_predicates.is_bot_owner_or_admin()
@commands.command(
name="removeperm",
aliases=["removeperms", "rmperms", "rmverified", "rmperm"],
)
async def removeperm(
self, ctx, role_permissions: str, role_or_rolename: Union[nextcord.Role, str]
):
"""Remove a role from the given Permission Category within the server.
Only available to server admins or bot owners.
Permission Category : Admin or Bot Owner Roles only.
Usage: `~removeperm Verified @VerifiedRoleName`
Usage: `~removeperm Trusted @everyone`
"""
await logging_utils.log_command(
"removeperm", ctx.guild, ctx.channel, ctx.author
)
embed = discord_utils.create_embed()
if role_permissions not in database.VERIFIED_CATEGORIES:
embed.add_field(
name=f"{constants.FAILED}",
value=f"`role_permissions` must be in {', '.join(database.VERIFIED_CATEGORIES)}, "
f"but you supplied {role_permissions}",
)
await ctx.send(embed=embed)
return
role_to_remove = await discord_utils.find_role(ctx, role_or_rolename)
if role_to_remove is None:
embed.add_field(
name=f"{constants.FAILED}",
value=f"Sorry, I can't find role `{role_or_rolename}`.",
)
await ctx.send(embed=embed)
return
with Session(database.DATABASE_ENGINE) as session:
result = (
session.query(database.Verifieds)
.filter_by(
server_id=ctx.guild.id,
role_id_permissions=f"{role_to_remove.id}_{role_permissions}",
)
.first()
)
if result is None:
embed.add_field(
name=f"{constants.FAILED}",
value=f"Role {role_to_remove.mention} is not `{role_permissions}` in `{ctx.guild.name}`",
)
await ctx.send(embed=embed)
return
else:
session.delete(result)
session.commit()
if (
role_permissions == models.VERIFIED
and role_to_remove.id in database.VERIFIEDS[ctx.guild.id]
):
database.VERIFIEDS[ctx.guild.id].pop(
database.VERIFIEDS[ctx.guild.id].index(role_to_remove.id)
)
elif (
role_permissions == models.TRUSTED
and role_to_remove.id in database.TRUSTEDS[ctx.guild.id]
):
database.TRUSTEDS[ctx.guild.id].pop(
database.TRUSTEDS[ctx.guild.id].index(role_to_remove.id)
)
elif (
role_permissions == models.SOLVER
and role_to_remove.id in database.SOLVERS[ctx.guild.id]
):
database.SOLVERS[ctx.guild.id].pop(
database.SOLVERS[ctx.guild.id].index(role_to_remove.id)
)
elif (
role_permissions == models.TESTER
and role_to_remove.id in database.TESTERS[ctx.guild.id]
):
database.TESTERS[ctx.guild.id].pop(
database.TESTERS[ctx.guild.id].index(role_to_remove.id)
)
embed.add_field(
name=f"{constants.SUCCESS}",
value=f"Removed {role_to_remove.mention} from `{role_permissions}` in `{ctx.guild.name}`",
)
await ctx.send(embed=embed)
##################
# GUILD COMMANDS #
##################
@command_predicates.is_bot_owner()
@commands.command(
name="commonmemberguilds",
aliases=["commonguild", "guildcommon"],
)
async def commonmemberguilds(
self,
ctx,
guild_1: Union[nextcord.Guild, str],
guild_2: Union[nextcord.Guild, str],
):
"""List all users in common between 2 guilds that the bot is in.
Permission Category : Bot Owner Roles only.
See also : `~lsguilds`
Usage: `~commonmemberguilds "Guild1" "Guild2"`
"""
await logging_utils.log_command(
"commonmemberguilds", ctx.guild, ctx.channel, ctx.author
)
embed = discord_utils.create_embed()
guild_1_guild = await discord_utils.find_guild(ctx, guild_1)
guild_2_guild = await discord_utils.find_guild(ctx, guild_2)
if guild_1_guild is None:
embed.add_field(
name=f"{constants.FAILED}!",
value=f"There is no guild named `{guild_1}`. Please double check the spelling.",
)
await ctx.send(embed=embed)
return
if guild_2_guild is None:
embed.add_field(
name=f"{constants.FAILED}!",
value=f"There is no guild named `{guild_2}`. Please double check the spelling.",
)
await ctx.send(embed=embed)
return
members_guild_1 = guild_1_guild.members
members_guild_2 = guild_2_guild.members
members_common = [
member for member in members_guild_1 if member in members_guild_2
]
if len(members_common) > 0:
embed.add_field(
name=f"Members common",
value=f"Members common in `{guild_1}` and `{guild_2}`\n"
f"{' '.join([member.mention for member in members_common])}",
inline=False,
)
else:
embed.add_field(
name=f"No members in common",
value=f"The bot has no members in common between `{guild_1}` and `{guild_2}`",
inline=False,
)
await ctx.send(embed=embed)
@command_predicates.is_bot_owner()
@commands.command(
name="guildowner",
aliases=["ownerguild"],
)
async def guildowner(
self,
ctx,
guild_name: Union[nextcord.Guild, str],
):
"""Mentions the guild owner for a specific guild the bot is in.
Note - This command is planned to be used extremely sparingly and for important (usually notification related) reasons only.
Permission Category : Bot Owner Roles only.
Usage: `~guildowner "Guild1"`
"""
await logging_utils.log_command(
"guildowner", ctx.guild, ctx.channel, ctx.author
)
embed = discord_utils.create_embed()
guild = await discord_utils.find_guild(ctx, guild_name)
if guild is None:
embed.add_field(
name=f"{constants.FAILED}!",
value=f"There is no guild named `{guild_name}`. Please double check the spelling.",
)
await ctx.send(embed=embed)
return
owner = guild.owner
embed.add_field(
name=f"Guild owner : ",
value=f"Guild owner for `{guild}` : {owner.mention} : `{owner.display_name}` : `{owner.name}`",
inline=False,
)
await ctx.send(embed=embed)
@command_predicates.is_bot_owner()
@commands.command(
name="lsguilds",
aliases=["listguilds"],
)
async def lsguilds(self, ctx):
"""List all guilds that the bot is in.
Permission Category : Bot Owner Roles only.
Usage: `~lsguilds`
"""
await logging_utils.log_command("lsguilds", ctx.guild, ctx.channel, ctx.author)
embed = discord_utils.create_embed()
guilds = ctx.bot.guilds
guilds = sorted(guilds, key=lambda guild: guild.name)
if len(guilds) > 0:
guilds_string = " ".join(["`" + guild.name + "` - \n" for guild in guilds])
embed.add_field(
name=f"Guilds for {ctx.bot.user.name} = {len(guilds)}",
value=f"Guilds for {ctx.bot.user.mention}\n" f"{guilds_string}",
inline=False,
)
else:
embed.add_field(
name=f"No guilds for the bot",
value="The bot is currently not in any guilds.",
inline=False,
)
await ctx.send(embed=embed)
@command_predicates.is_bot_owner()
@commands.command(
name="quitguild",
)
async def quitguild(self, ctx, guild_name: Union[nextcord.Guild, str]):
"""Quit a guild.
Permission Category : Bot Owner Roles only.
Usage: `~quitguild "Guildname"`
"""
await logging_utils.log_command("quitguild", ctx.guild, ctx.channel, ctx.author)
embed = discord_utils.create_embed()
guild = await discord_utils.find_guild(ctx, guild_name)
if guild is None:
embed.add_field(
name=f"{constants.FAILED}!",
value=f"There is no guild named `{guild_name}`. Please double check the spelling.",
)
await ctx.send(embed=embed)
return
try:
await guild.leave()
except nextcord.HTTPException:
embed.add_field(
name=f"{constants.FAILED}",
value=f"Could not leave guild `{guild_name}`",
)
await ctx.send(embed=embed)
return
embed.add_field(
name=f"{constants.SUCCESS}",
value=f"Successfully left guild `{guild_name}`",
inline=False,
)
await ctx.send(embed=embed)
@command_predicates.is_bot_owner_or_admin()
@commands.command(name="setprefix")
async def setprefix(self, ctx, prefix: str):
"""Sets the bot prefix for the server.
Permission Category : Admin or Bot Owner Roles only.
Usage: `~setprefix !`
"""
await logging_utils.log_command("setprefix", ctx.guild, ctx.channel, ctx.author)
embed = discord_utils.create_embed()
with Session(database.DATABASE_ENGINE) as session:
session.query(database.Prefixes).filter_by(server_id=ctx.guild.id).update(
{"prefix": prefix}
)
session.commit()
database.PREFIXES[ctx.message.guild.id] = prefix
embed.add_field(
name=f"{constants.SUCCESS}",
value=f"Prefix for this server set to {prefix}",
inline=False,
)
await ctx.send(embed=embed)
######################
# BOT CACHE COMMANDS #
######################
@command_predicates.is_bot_owner_or_admin()
@commands.command(
name="reloaddatabasecache", aliases=["reloaddbcache", "dbcachereload"]
)
async def reloaddatabasecache(self, ctx):
"""Reloads the custom command cache. This is useful when we're editing commands or playing with the Database.
Permission Category : Admin or Bot Owner Roles only.
Usage: `~reloaddatabasecache`
"""
await logging_utils.log_command(
"reloaddatabasecache", ctx.guild, ctx.channel, ctx.author
)
embed = discord_utils.create_embed()
# Reset custom commands, verifieds, and prefixes for that server
database.CUSTOM_COMMANDS[ctx.guild.id] = {}
database.VERIFIEDS[ctx.guild.id] = []
database.TRUSTEDS[ctx.guild.id] = []
database.SOLVERS[ctx.guild.id] = []
database.TESTERS[ctx.guild.id] = []
with Session(database.DATABASE_ENGINE) as session:
custom_command_result = (
session.query(database.CustomCommands)
.filter_by(server_id=ctx.guild.id)
.all()
)
if custom_command_result is not None:
for custom_command in custom_command_result:
# Populate custom command dict
database.CUSTOM_COMMANDS[ctx.guild.id][
custom_command.command_name.lower()
] = (custom_command.command_return, custom_command.image)
embed.add_field(
name=f"{constants.SUCCESS}",
value="Successfully reloaded command cache.",
inline=False,
)
verified_result = (
session.query(database.Verifieds)
.filter_by(server_id=ctx.guild.id)
.all()
)
if verified_result is not None:
for verified in verified_result:
if verified.permissions == models.VERIFIED:
database.VERIFIEDS[ctx.guild.id].append(verified.role_id)
elif verified.permissions == models.TRUSTED:
database.TRUSTEDS[ctx.guild.id].append(verified.role_id)
elif verified.permissions == models.SOLVER:
database.SOLVERS[ctx.guild.id].append(verified.role_id)
elif verified.permissions == models.TESTER:
database.TESTERS[ctx.guild.id].append(verified.role_id)
embed.add_field(
name=f"{constants.SUCCESS}!",
value="Successfully reloaded verifieds cache.",
inline=False,
)
prefix_result = (
session.query(database.Prefixes)
.filter_by(server_id=ctx.guild.id)
.first()
)
if prefix_result is not None:
database.PREFIXES[ctx.guild.id] = prefix_result.prefix
else:
database.PREFIXES[ctx.guild.id] = constants.DEFAULT_BOT_PREFIX
embed.add_field(
name=f"{constants.SUCCESS}!",
value="Successfully reloaded prefixes cache.",
inline=False,
)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(AdminCog(bot))