-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRainbowBot.py
424 lines (400 loc) · 18.2 KB
/
RainbowBot.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
import discord
import aiosqlite
import logging
import traceback
import os
from discord.ext import commands
from dotenv import load_dotenv
from datetime import datetime, timezone
from RainbowBotHelp import RainbowBotHelp
load_dotenv()
token = os.getenv("token")
class RainbowBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix = commands.when_mentioned_or("rb!"),
help_command = RainbowBotHelp(),
description = "A multi-purpose Discord bot made by GitHub user gemhue.",
intents = discord.Intents.all(),
activity = discord.Activity(type=discord.ActivityType.listening, name="rb!help"),
status = discord.Status.online
)
self.blurple = discord.Colour.blurple()
self.green = discord.Colour.green()
self.yellow = discord.Colour.yellow()
self.red = discord.Colour.red()
async def setup_hook(self):
# Connect to database
try:
self.database = await aiosqlite.connect("rainbowbot.db")
print("Connected to Database: rainbowbot.db")
except Exception:
print("There was an error connecting to the database.")
print(traceback.format_exc())
# Clear the global command tree
try:
self.tree.clear_commands(guild=None)
print("Global Command Tree: Cleared")
except Exception:
print("There was an error clearing the global command tree.")
print(traceback.format_exc())
# Load all extensions
try:
cogs = []
for cog in await allcogs(x="cogs"):
await self.load_extension(cog)
cogs.append(cog)
list = ", ".join(cogs)
print(f"Extensions Loaded: {list}")
except Exception:
print("There was an error loading the extensions.")
print(traceback.format_exc())
# Sync the global command tree
try:
await self.tree.sync(guild=None)
print("Global Command Tree: Synced")
except Exception:
print("There was an error syncing the global command tree.")
print(traceback.format_exc())
bot = RainbowBot()
handler = logging.FileHandler(filename="rainbowbot.log", encoding="utf-8", mode="w")
@bot.command(name="sync", hidden=True)
@commands.is_owner()
async def sync(ctx: commands.Context, where: str):
"""(Bot Owner Only) Syncs the bot's command tree either locally or globally.
"""
await ctx.defer()
guild = ctx.guild
if where == "here" or where == "local":
await bot.tree.sync(guild=guild)
embed = discord.Embed(color=bot.green, title="Success", description=f"The bot's local command tree has been **synced**!")
elif where == "all" or where == "global":
await bot.tree.sync(guild=None)
embed = discord.Embed(color=bot.green, title="Success", description=f"The bot's global command tree has been **synced**!")
else:
embed = discord.Embed(color=bot.red, title="Error", description=f"The bot's command tree has not been synced! Please specify if you would like to sync `here` or `all`.")
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
now = datetime.now(tz=timezone.utc)
if isinstance(logging_channel, discord.TextChannel):
log = discord.Embed(
color=bot.blurple,
title="Command Tree Synced",
timestamp=now
)
if where == "here" or where == "local":
log.add_field(name="Local Tree", value=f"{ctx.author.mention} has just **synced** the bot's local command tree.")
if where == "all" or where == "global":
log.add_field(name="Global Tree", value=f"{ctx.author.mention} has just **synced** the bot's global command tree.")
log.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
log.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=log)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
@bot.command(name="clear", hidden=True)
@commands.is_owner()
async def clear(ctx: commands.Context, where: str):
"""(Bot Owner Only) Clears the bot's command tree either locally or globally.
"""
await ctx.defer()
guild = ctx.guild
if where == "here" or where == "local":
bot.tree.clear_commands(guild=guild)
embed = discord.Embed(color=bot.green, title="Success", description=f"The bot's local command tree has been **cleared**!")
elif where == "all" or where == "global":
bot.tree.clear_commands(guild=None)
embed = discord.Embed(color=bot.green, title="Success", description=f"The bot's global command tree has been **cleared**!")
else:
embed = discord.Embed(color=bot.red, title="Error", description=f"The bot's command tree has not been cleared! Please specify if you would like to clear `here` or `all`.")
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
now = datetime.now(tz=timezone.utc)
if isinstance(logging_channel, discord.TextChannel):
log = discord.Embed(
color=bot.blurple,
title="Command Tree Cleared",
timestamp=now
)
if where == "here" or where == "local":
log.add_field(name="Local Tree", value=f"{ctx.author.mention} has just **cleared** the bot's local command tree.")
if where == "all" or where == "global":
log.add_field(name="Global Tree", value=f"{ctx.author.mention} has just **cleared** the bot's global command tree.")
log.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
log.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=log)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
async def allcogs(x):
files = []
cogs = []
cogsdict = {}
folder = "./cogs"
for file in os.listdir(folder):
if file.endswith(".py"):
files.append(file[:-3])
for file in files:
if x == "cogs":
cogs.append(f"cogs.{file}")
elif x == "modules":
title = file.title()
cogs.append(f"{file}.{title}")
elif x == "names":
cogs.append(file)
elif x == "names_lower":
name = file.lower()
cogs.append(name)
elif x == "names_dict":
lower = file.lower()
cogsdict[lower] = file
if len(cogs) > 0:
return cogs
elif len(cogsdict) > 0:
return cogsdict
else:
return None
@bot.command(name="get", hidden=True)
@commands.is_owner()
async def get(ctx: commands.Context):
"""(Bot Owner Only) Returns a list of all of the bot's cogs.
"""
await ctx.defer()
now = datetime.now(tz=timezone.utc)
embed = discord.Embed(color=bot.blurple, title="Cogs", timestamp=now)
for cog in await allcogs(x="names"):
embed.add_field(name=cog, value="Retreived successfully!")
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (ctx.guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
if isinstance(logging_channel, discord.TextChannel):
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=embed)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
@bot.command(name="load", hidden=True)
@commands.is_owner()
async def load(ctx: commands.Context, extension: str):
"""(Bot Owner Only) Loads one or all of the bot's cogs.
Parameters
-----------
extension : str
Provide the extension that you would like to load (or all).
"""
await ctx.defer()
now = datetime.now(tz=timezone.utc)
embed = discord.Embed(color=bot.blurple, title="Load Cogs", timestamp=now)
lower = extension.lower()
if lower == "all":
for cog in await allcogs(x="cogs"):
try:
await bot.load_extension(cog)
embed.add_field(name=cog, value="Loaded successfully!")
except Exception as e:
embed.add_field(name=cog, value=f"Error: {e}")
print(traceback.format_exc())
elif lower in await allcogs(x="names_lower"):
for cog in await allcogs(x="cogs"):
if cog.lower() == f"cogs.{lower}":
try:
await bot.load_extension(cog)
embed.add_field(name=cog, value="Loaded successfully!")
except Exception as e:
embed.add_field(name=cog, value=f"Error: {e}")
print(traceback.format_exc())
else:
embed.add_field(name="Error", value="No cogs could be loaded.")
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (ctx.guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
if isinstance(logging_channel, discord.TextChannel):
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=embed)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
@bot.command(name="unload", hidden=True)
@commands.is_owner()
async def unload(ctx: commands.Context, extension: str):
"""(Bot Owner Only) Unloads one or all of the bot's cogs.
Parameters
-----------
extension : str
Provide the extension that you would like to unload (or all).
"""
await ctx.defer()
now = datetime.now(tz=timezone.utc)
embed = discord.Embed(color=bot.blurple, title="Unload Cogs", timestamp=now)
lower = extension.lower()
if lower == "all":
for cog in await allcogs(x="cogs"):
try:
await bot.unload_extension(cog)
embed.add_field(name=cog, value="Unloaded successfully!")
except Exception as e:
embed.add_field(name=cog, value=f"Error: {e}")
print(traceback.format_exc())
elif lower in await allcogs(x="names_lower"):
for cog in await allcogs(x="cogs"):
if cog.lower() == f"cogs.{lower}":
try:
await bot.unload_extension(cog)
embed.add_field(name=cog, value="Unloaded successfully!")
except Exception as e:
embed.add_field(name=cog, value=f"Error: {e}")
print(traceback.format_exc())
else:
embed.add_field(name="Error", value="No cogs could be unloaded.")
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (ctx.guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
if isinstance(logging_channel, discord.TextChannel):
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=embed)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
@bot.command(name="reload", hidden=True)
@commands.is_owner()
async def reload(ctx: commands.Context, extension: str):
"""(Bot Owner Only) Reloads one or all of the bot's cogs.
Parameters
-----------
extension : str
Provide the extension that you would like to reload (or all).
"""
await ctx.defer()
now = datetime.now(tz=timezone.utc)
embed = discord.Embed(color=bot.blurple, title="Reload Cogs", timestamp=now)
lower = extension.lower()
if lower == "all":
for cog in await allcogs(x="cogs"):
try:
await bot.reload_extension(cog)
embed.add_field(name=cog, value="Reloaded successfully!")
except Exception as e:
embed.add_field(name=cog, value=f"Error: {e}")
print(traceback.format_exc())
elif lower in await allcogs(x="names_lower"):
for cog in await allcogs(x="cogs"):
if cog.lower() == f"cogs.{lower}":
try:
await bot.reload_extension(cog)
embed.add_field(name=cog, value="Reloaded successfully!")
except Exception as e:
embed.add_field(name=cog, value=f"Error: {e}")
print(traceback.format_exc())
else:
embed.add_field(name="Error", value="No cogs could be reloaded.")
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (ctx.guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
if isinstance(logging_channel, discord.TextChannel):
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=embed)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
@bot.command(name="ping")
async def ping(ctx: commands.Context):
"""Retrieve the bot's current latency.
"""
await ctx.defer()
try:
now = datetime.now(tz=timezone.utc)
latency = bot.latency*1000
embed = discord.Embed(color=bot.blurple, title="Pong", description=f"The bot's current latency is {latency} seconds!", timestamp=now)
except Exception as e:
embed = discord.Embed(color=bot.red, title="Error", description=f"{e}")
print(traceback.format_exc())
await ctx.send(embed=embed, delete_after=10.0)
await ctx.message.delete()
# Send a log to the logging channel
cur = await bot.database.execute("SELECT logging_channel_id FROM guilds WHERE guild_id = ?", (ctx.guild.id,))
row = await cur.fetchone()
fetched_logging = row[0]
if fetched_logging is not None:
logging_channel = ctx.guild.get_channel(fetched_logging)
if isinstance(logging_channel, discord.TextChannel):
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
embed.set_thumbnail(url=ctx.author.display_avatar)
await logging_channel.send(embed=embed)
else:
log = discord.Embed(
color=bot.red,
title="Logging Channel Not Found",
description=f"A logging channel with the ID {fetched_logging} was not found! Please set a new logging channel by re-running the `/start` command.",
timestamp=now
)
await ctx.send(embed=log, delete_after=10.0)
@bot.event
async def on_ready(bot=bot):
print(f'Logged in as {bot.user}! (ID: {bot.user.id})')
bot.run(token, log_handler=handler, log_level=logging.DEBUG)