aboutsummaryrefslogtreecommitdiff
path: root/cogs/admin.py
blob: ed7b7cceb76d627fbd8576bad26c7b57b7a907c2 (plain) (blame)
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
import asyncio
import json
import os

import discord
import git
from discord.ext import commands


class Admin(commands.Cog):
	def __init__(self, bot):
		self.bot = bot

	async def is_mod(ctx):
		return ctx.author.guild_permissions.manage_channels

	async def is_botmaster(ctx):
		return ctx.author.id in ctx.bot.config[str(
			ctx.message.guild.id)]["bot_masters"]

	@commands.command(aliases=['deleteEverything'], hidden=True)
	@commands.check(is_botmaster)
	async def purge(self, ctx):
		await ctx.message.channel.purge(limit=500)

	@commands.command(aliases=['quit'], hidden=True)
	@commands.check(is_botmaster)
	async def forceexit(self, ctx):
		await ctx.send('Self Destructing')
		await ctx.bot.close()

	@commands.command()
	@commands.check(is_mod)
	async def pull(self, ctx):
		"""Update the bot from github"""
		g = git.cmd.Git(os.getcwd())
		try:
			await ctx.send(f"Probably pulled.\n```bash\n{g.pull()}```")
		except git.exc.GitCommandError as e:
			await ctx.send(f"An error has occured when pulling```bash\n{e}```")

	@commands.command(aliases=['addcommand', 'newcommand'])
	@commands.check(is_mod)
	async def setcommand(self, ctx, command, *, message):
		"""Add a new simple command"""
		self.bot.custom_commands[ctx.prefix + command] = message
		with open('custom_commands.json', 'w') as f:
			json.dump(self.bot.custom_commands, f, indent=4)

		await ctx.send(f"Set message for command {command}")

	@commands.command(aliases=['deletecommand'])
	@commands.check(is_mod)
	async def removecommand(self, ctx, command):
		"""Remove a simple command"""
		del self.bot.custom_commands[ctx.prefix + command]
		with open('custom_commands.json', 'w') as f:
			json.dump(self.bot.custom_commands, f, indent=4)

		await ctx.send(f"Removed command {command}")

	@commands.command(name='reload', hidden=True, usage='<extension>')
	@commands.check(is_mod)
	async def _reload(self, ctx, ext):
		"""Reloads an extension"""
		try:
			self.bot.reload_extension(f'cogs.{ext}')
			await ctx.send(f'The extension {ext} was reloaded!')
		except commands.ExtensionNotFound:
			await ctx.send(f'The extension {ext} doesn\'t exist.')
		except commands.ExtensionNotLoaded:
			await ctx.send(
				f'The extension {ext} is not loaded! (use {ctx.prefix}load)')
		except commands.NoEntryPointError:
			await ctx.send(
				f'The extension {ext} doesn\'t have an entry point (try adding the setup function) '
			)
		except commands.ExtensionFailed:
			await ctx.send(
				f'Some unknown error happened while trying to reload extension {ext} (check logs)'
			)
			self.bot.logger.exception(f'Failed to reload extension {ext}:')

	@commands.command(name='load', hidden=True, usage='<extension>')
	@commands.check(is_mod)
	async def _load(self, ctx, ext):
		"""Loads an extension"""
		try:
			self.bot.load_extension(f'cogs.{ext}')
			await ctx.send(f'The extension {ext} was loaded!')
		except commands.ExtensionNotFound:
			await ctx.send(f'The extension {ext} doesn\'t exist!')
		except commands.ExtensionAlreadyLoaded:
			await ctx.send(f'The extension {ext} is already loaded.')
		except commands.NoEntryPointError:
			await ctx.send(
				f'The extension {ext} doesn\'t have an entry point (try adding the setup function)'
			)
		except commands.ExtensionFailed:
			await ctx.send(
				f'Some unknown error happened while trying to reload extension {ext} (check logs)'
			)
			self.bot.logger.exception(f'Failed to reload extension {ext}:')

	@commands.command(name='unload', hidden=True, usage='<extension>')
	@commands.check(is_mod)
	async def _unload(self, ctx, ext):
		"""Loads an extension"""
		try:
			self.bot.unload_extension(f'cogs.{ext}')
			await ctx.send(f'The extension {ext} was unloaded!')
		except commands.ExtensionNotFound:
			await ctx.send(f'The extension {ext} doesn\'t exist!')
		except commands.NoEntryPointError:
			await ctx.send(
				f'The extension {ext} doesn\'t have an entry point (try adding the setup function)'
			)
		except commands.ExtensionFailed:
			await ctx.send(
				f'Some unknown error happened while trying to reload extension {ext} (check logs)'
			)
			self.bot.logger.exception(f'Failed to unload extension {ext}:')

	@commands.command()
	@commands.check(is_mod)
	async def clear(self, ctx, number):
		"""Mass delete messages"""
		await ctx.message.channel.purge(limit=int(number) + 1,
										check=None,
										before=None,
										after=None,
										around=None,
										oldest_first=False,
										bulk=True)

	@commands.command()
	@commands.check(is_mod)
	async def mute(self,
				   ctx,
				   members: commands.Greedy[discord.Member] = False,
				   mute_minutes: int = 0,
				   *,
				   reason: str = "absolutely no reason"):
		"""Mass mute members with an optional mute_minutes parameter to time it"""

		if not members:
			await ctx.send("You need to name someone to mute")
			return
		elif type(members) == str:
			members = [self.bot.get_user(int(members))]

		#muted_role = discord.utils.find(ctx.guild.roles, name="Muted")
		muted_role = ctx.guild.get_role(
			int(self.bot.config[str(ctx.message.guild.id)]["mute_role"]))
		for member in members:
			if self.bot.user == member:  # what good is a muted bot?
				embed = discord.Embed(
					title="You can't mute me, I'm an almighty bot")
				await ctx.send(embed=embed)
				continue
			await member.add_roles(muted_role, reason=reason)
			await ctx.send(
				"{0.mention} has been muted by {1.mention} for *{2}*".format(
					member, ctx.author, reason))

		if mute_minutes > 0:
			await asyncio.sleep(mute_minutes * 60)
			for member in members:
				await member.remove_roles(muted_role, reason="time's up ")

	@commands.command()
	@commands.check(is_mod)
	async def unmute(self, ctx, members: commands.Greedy[discord.Member]):
		"""Remove the muted role"""
		if not members:
			await ctx.send("You need to name someone to unmute")
			return
		elif type(members) == str:
			members = self.bot.get_user(int(user))

		muted_role = ctx.guild.get_role(
			int(self.bot.config[str(ctx.message.guild.id)]["mute_role"]))
		for i in members:
			await i.remove_roles(muted_role)
			await ctx.send(
				"{0.mention} has been unmuted by {1.mention}".format(
					i, ctx.author))

	@commands.command()
	@commands.check(is_mod)
	async def ban(self,
				  ctx,
				  members: commands.Greedy[discord.Member] = False,
				  ban_minutes: int = 0,
				  *,
				  reason: str = "absolutely no reason"):
		"""Mass ban members with an optional mute_minutes parameter to time it"""

		if not members:
			await ctx.send("You need to name someone to ban")
			return
		elif type(members) == str:
			members = [self.bot.get_user(int(members))]
		for member in members:
			if self.bot.user == member:  # what good is a muted bot?
				embed = discord.Embed(
					title="You can't ban me, I'm an almighty bot")
				await ctx.send(embed=embed)
				continue
			try:
				await member.send(
					f"You have been banned from {ctx.guild.name} for {ban_minutes} minutes because: ```{reason}```"
				)
			except discord.Forbidden:
				pass
			await ctx.guild.ban(member, reason=reason, delete_message_days=0)
			await ctx.send(
				"{0.mention} has been banned by {1.mention} for *{2}*".format(
					member, ctx.author, reason))

		if ban_minutes > 0:
			await asyncio.sleep(ban_minutes * 60)
			for member in members:
				await ctx.guild.unban(member, reason="Time is up")

	@commands.command()
	@commands.check(is_botmaster)
	async def logs(self, ctx):
		"""Send the discord.log file"""
		await ctx.message.delete()
		file = discord.File("discord.log")
		await ctx.send(file=file)

	@commands.command(hidden=True)
	@commands.check(is_botmaster)
	async def blacklist(self,
						ctx,
						members: commands.Greedy[discord.Member] = None):
		"""Ban someone from using the bot"""
		if not members:
			await ctx.send("You need to name someone to blacklist")
			return
		elif type(members) == "str":
			members = self.bot.get_user(int(user))

		with open('blacklist.json', 'w') as f:
			for i in members:
				if i.id in self.bot.blacklist:
					self.bot.blacklist.remove(i.id)
					json.dump(self.bot.blacklist, f, indent=4)
					await ctx.send(f"{i} has been un-blacklisted.")
				else:
					self.bot.blacklist.append(i.id)
					json.dump(self.bot.blacklist, f, indent=4)
					await ctx.send(f"{i} has been blacklisted.")

	@commands.command()
	@commands.check(is_mod)
	async def activity(self, ctx, *, activity=None):
		"""Change the bot's activity"""
		if activity:
			game = discord.Game(activity)
		else:
			activity = "Mining away"
			game = discord.Game(activity)
		await self.bot.change_presence(activity=game)
		await ctx.send(f"Activity changed to {activity}")

	@commands.command()
	@commands.check(is_botmaster)
	async def setvar(self, ctx, key, *, value):
		"""Set a config variable, ***use with caution**"""
		with open('config.json', 'w') as f:
			if value[0] == '[' and value[len(value) - 1] == ']':
				value = list(map(int, value[1:-1].split(',')))
			self.bot.config[str(ctx.message.guild.id)][key] = value
			json.dump(self.bot.config, f, indent=4)

	@commands.command()
	@commands.check(is_mod)
	async def printvar(self, ctx, key=None):
		"""Print config variables, use for testing"""
		if key == None:
			for key, value in self.bot.config[str(
					ctx.message.guild.id)].items():
				await ctx.send(f'Key: {key} | Value: {value}')
		else:
			await ctx.send(self.bot.config[str(ctx.message.guild.id)][key])

	@commands.command(aliases=['rmvar'])
	@commands.check(is_botmaster)
	async def delvar(self, ctx, key):
		"""Deletes a config variable, be careful"""
		with open('config.json', 'w') as f:
			await ctx.send(
				f"Removed {self.bot.config[str(ctx.message.guild.id)].pop(key)}"
			)
			json.dump(self.bot.config, f, indent=4)

	@commands.command()
	@commands.check(is_mod)
	async def blacklistvideo(self, ctx, uri):
		"""Set runs from a specific url to be auto rejected"""
		video_id = uri.split('/')[-1].split('=')[-1]
		with open('runs_blacklist.json', 'w') as f:
			self.bot.runs_blacklist["videos"].append(video_id)
			json.dump(self.bot.runs_blacklist, f, indent=4)
		await ctx.send(f'Blacklisted runs from `{uri}`')

	@commands.command()
	@commands.check(is_mod)
	async def blacklistplayer(self, ctx, player):
		"""Set runs from a specific player to be auto rejected"""
		with open('runs_blacklist.json', 'w') as f:
			self.bot.runs_blacklist["players"].append(player)
			json.dump(self.bot.runs_blacklist, f, indent=4)
		await ctx.send(f'Blacklisted runs from `{player}`')

	@commands.command()
	@commands.check(is_mod)
	async def runs_blacklist(self, ctx):
		"""Sends a list of blacklisted videos and players"""
		message = '```The following videos are blacklisted:\n'
		for uri in self.bot.runs_blacklist["videos"]:
			message += f'{uri}, '
		await ctx.send(f'{message[:-2]}```')

		message = '```The following players are blacklisted:\n'
		for player in self.bot.runs_blacklist["players"]:
			message += f'{player}, '
		await ctx.send(f'{message[:-2]}```')

	@commands.command()
	@commands.check(is_botmaster)
	async def give_role(self, ctx, role_id):
		the_role = ctx.guild.get_role(int(role_id))
		await ctx.author.add_roles(the_role)


def setup(bot):
	bot.add_cog(Admin(bot))