-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathMain.py
501 lines (462 loc) · 15.1 KB
/
Main.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
import asyncio, discord, time, sys, os, random, traceback, json
from discord.ext import commands
from discord import errors
from Cogs import DisplayName
# Let's migrate any specific txt settings files into a single json file
# called settings_dict.json
if os.path.exists("settings_dict.json"):
try: settings_dict = json.load(open("settings_dict.json"))
except Exception as e:
print("Could not load settings_dict.json!")
print(" - {}".format(e))
# Kill the process to avoid constant reloads
os._exit(3)
else:
settings_dict = {"token":""}
print("Migrating .txt files to settings_dict.json...")
for x in ["prefix.txt","corpSiteAuth.txt","token.txt","igdbKey.txt","weather.txt","discogs.txt","currency.txt"]:
if not os.path.exists(x): continue # Didn't find it
try:
with open(x,"rb") as f:
setting = f.read().strip().decode("utf-8")
except Exception as e:
print("Failed to migrate setting from {}! Ignoring.".format(x))
print(" - {}".format(e))
continue
settings_dict[x[:-4].lower()] = setting
json.dump(settings_dict,open("settings_dict.json","w"),indent=4)
async def get_prefix(bot, message):
# Check commands against some things and do stuff or whatever...
prefixes = ["<@!{}> ".format(bot.user.id), "<@{}> ".format(bot.user.id)]
try:
# Set the settings var up
settings = bot.get_cog("Settings")
serverPrefix = settings.getServerStat(message.guild,"Prefix")
except Exception:
serverPrefix = None
if not serverPrefix:
# No custom prefix - use the default
serverPrefix = settings_dict.get("prefix","$") # prefix
if isinstance(serverPrefix,(list,tuple)):
prefixes.extend(serverPrefix)
else:
prefixes.append(serverPrefix)
# Ensure all elements are strings
prefixes = [x for x in prefixes if isinstance(x,str)]
return tuple(prefixes)
# This should be the main soul of the bot - everything should load from here
# bot = commands.Bot(command_prefix=get_prefix, pm_help=None, description='A bot that does stuff.... probably')
# Let's SHARD!
allowed_mentions = discord.AllowedMentions(
users=False,
everyone=False,
roles=False,
replied_user=False
)
try:
# Setup intents
intents = discord.Intents().all()
bot = commands.AutoShardedBot(
command_prefix=get_prefix,
pm_help=None,
description='A bot that does stuff.... probably',
shard_count=settings_dict.get("shard_count",4),
intents=intents,
allowed_mentions=allowed_mentions,
case_insensitive=settings_dict.get("case_insensitive",True)
)
except:
# Possibly using the old gateway?
print("Using the old gateway - this may not be around forever...\n")
bot = commands.AutoShardedBot(
command_prefix=get_prefix,
pm_help=None,
description='A bot that does stuff.... probably',
shard_count=settings_dict.get("shard_count",4),
allowed_mentions=allowed_mentions,
case_insensitive=settings_dict.get("case_insensitive",True)
)
bot.settings_dict = settings_dict
bot.ready_dispatched = False
bot.local_client = None
async def return_message():
# Set the settings var up
settings = bot.get_cog("Settings")
if not settings:
return
stat_check = "{}-ReturnChannel".format(bot.user.id)
return_channel = settings.getGlobalStat(stat_check,None)
if return_channel:
settings.delGlobalStat(stat_check)
message_to = bot.get_channel(return_channel)
if not message_to:
# No channel - try getting a user, possibly rebooted in dm
message_to = bot.get_user(return_channel)
if not message_to:
return
return_options = [
"I'm back!",
"I have returned!",
"Guess who's back?",
"Fear not! I have returned!",
"I'm alive!"
]
await message_to.send(random.choice(return_options))
# Main bot events
@bot.event
async def on_ready():
# Special workaround for the bot saying it's ready before all shards are ready.
# The bot seems to dispatch the ready event every 2 shards or so.
if not bot.ready_dispatched:
print(" - {} of {} ready...".format(len(bot.shards), bot.shard_count))
if len(bot.shards) >= bot.shard_count:
print("\nAll shards ready!\n")
bot.ready_dispatched = True
bot.dispatch("all_shards_ready")
@bot.event
# async def on_ready():
async def on_all_shards_ready():
if not bot.get_cog("CogManager"):
# We need to load shiz!
print('Logged in as:\n{0} (ID: {0.id})\n'.format(bot.user))
print("Invite Link:\nhttps://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=8\n".format(bot.user.id))
# Let's try to use the CogManager class to load things
print("Loading CogManager...")
bot.load_extension("Cogs.CogManager")
cg_man = bot.get_cog("CogManager")
# Load up the rest of the extensions
cog_loaded, cog_count = cg_man._load_extension()
# Output the load counts
if cog_count == 1:
print("Loaded {} of {} cog.".format(cog_loaded, cog_count))
else:
print("Loaded {} of {} cogs.".format(cog_loaded, cog_count))
await return_message()
if bot.settings_dict.get("local_server_enabled"):
# Start the local listening server/client
try:
import LocalServer
asyncio.create_task(LocalServer.start_server(bot))
except ImportError:
pass
'''@bot.event
async def on_command_error(context, exception):
if type(exception) is commands.CommandInvokeError:
print("Command invoke error")
print(exception.original)
print(type(exception.original))
if type(exception.original) is discord.Forbidden:
print("Can't do that yo")
return
cog = context.cog
if cog:
attr = '_{0.__class__.__name__}__error'.format(cog)
if hasattr(cog, attr):
return
print('Ignoring exception in command {}:'.format(context.command), file=sys.stderr)
traceback.print_exception(type(exception), exception, exception.__traceback__, file=sys.stderr)'''
'''@bot.event
async def on_error(event_method, *args, **kwargs):
exc_str = "Ignoring exception in {}:\n ".format(event_method)
exc_str += "{}: {}".format(sys.exc_info()[0].__name__, sys.exc_info()[1])
#print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
#traceback.print_exc()
print(exc_str)'''
@bot.event
async def on_voice_state_update(user, beforeState, afterState):
return
@bot.event
async def on_typing(channel, user, when):
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.ontyping(channel, user, when)
except AttributeError:
continue
@bot.event
async def on_member_remove(member):
server = member.guild
# Set the settings var up
settings = bot.get_cog("Settings")
settings.removeUser(member, server)
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.onleave(member, server)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_member_ban(guild, member):
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.onban(guild, member)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_member_unban(member, server):
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.onunban(member, server)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_guild_join(server):
didLeave = False
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
if await cog.onserverjoin(server):
didLeave = True
except AttributeError:
# Onto the next
continue
if didLeave:
return
# Set the settings var up
settings = bot.get_cog("Settings")
owner = server.owner
# Let's message hello in the main chat - then pm the owner
prefixes = await get_prefix(bot,None)
prefix = prefixes[0] if len(prefixes) else "$"
msg = 'Hello there! Thanks for having me on your server! ({})\n\nFeel free to put me to work.\n\nYou can get a list of my commands by typing `{}help` either in chat or in PM.\n\n'.format(server.name, prefix)
msg += 'Whenever you have a chance, maybe take the time to set me up by typing `{}setup` in the main chat. Thanks!'.format(settings_dict.get("prefix","$"))
try:
await owner.send(msg)
except Exception:
pass
@bot.event
async def on_guild_remove(server):
# Set the settings var up
settings = bot.get_cog("Settings")
settings.removeServer(server)
@bot.event
async def on_member_join(member):
server = member.guild
# Set the settings var up
settings = bot.get_cog("Settings")
rules = settings.getServerStat(server, "Rules")
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.onjoin(member, server)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_presence_update(before, after):
# Workaround to keep all member/presence updates in the on_member_update() check
await on_member_update(before,after)
@bot.event
async def on_member_update(before, after):
# Check for cogs that accept updates
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.member_update(before, after)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_message(message):
# Post the context too
context = await bot.get_context(message)
bot.dispatch("message_context", context, message)
if not message.guild:
# This wasn't said in a server, process commands, then return
await bot.process_commands(message)
return
if message.author.bot:
# We don't need other bots controlling things we do.
return
try:
message.author.roles
except AttributeError:
# Not a User
await bot.process_commands(message)
return
# Check if we need to ignore or delete the message
# or respond or replace
ignore = delete = react = respond = False
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
check = await cog.message(message)
except AttributeError:
# Onto the next
continue
# Make sure we have things formatted right
if not type(check) is dict:
check = {}
if check.get("Delete",False):
delete = True
if check.get("Ignore",False):
ignore = True
try: respond = check['Respond']
except KeyError: pass
try: react = check['Reaction']
except KeyError: pass
if delete:
# We need to delete the message - top priority
await message.delete()
if not ignore:
# We're processing commands here
if respond:
# We have something to say
await message.channel.send(respond)
if react:
# We have something to react with
for r in react:
await message.add_reaction(r)
await bot.process_commands(message)
@bot.event
async def on_command(command):
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.oncommand(command)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_command_completion(command):
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.oncommandcompletion(command)
except AttributeError:
# Onto the next
continue
'''@bot.event
async def on_command_error(ctx, error):
# if isinstance(error, (commands.MissingRequiredArgument, commands.BadArgument)):
if not isinstance(error, (commands.CommandNotFound)):
await ctx.send("{}: {}".format(type(error).__name__, error))
formatted_help = await bot.formatter.format_help_for(ctx, ctx.command)
for page in formatted_help:
await ctx.send(page)
#print("".join(traceback.format_exception(etype=type(error),value=error,tb=error.__traceback__)))
if traceback.print_tb(error.__traceback__):
print(traceback.print_tb(error.__traceback__))'''
@bot.event
async def on_message_delete(message):
# Run through the on_message commands, but on deletes.
if not message.guild:
# This wasn't in a server, return
return
try:
message.author.roles
except AttributeError:
# Not a User
return
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
await cog.message_delete(message)
except AttributeError:
# Onto the next
continue
@bot.event
async def on_message_edit(before, message):
# Run through the on_message commands, but on edits.
if not message.guild:
# This wasn't said in a server, return
return
try:
message.author.roles
except AttributeError:
# Not a User
return
# Check if we need to ignore or delete the message
# or respond or replace
ignore = delete = False
respond = None
for cog in bot.cogs:
cog = bot.get_cog(cog)
try:
check = await cog.message_edit(before, message)
except AttributeError:
# Onto the next
continue
if check.get("Delete",False):
delete = True
if check.get("Ignore",False):
ignore = True
try: respond = check['Respond']
except KeyError: pass
if respond:
# We have something to say
await message.channel.send(respond)
if delete:
# We need to delete the message - top priority
await message.delete()
async def watchinput():
# Get our input asynchronously
while True:
i = (await asyncio.get_running_loop().run_in_executor(None, sys.stdin.readline)).rstrip("\n")
if i.lower() in ("?","-h","--help","/h","/help","help","/?"):
print(" - Console commands:")
print(" - 'help': show this help message")
print(" - 'shutdown', 'exit', or 'quit': shut down and exit the bot (returns 3)")
print(" - 'reboot' or 'restart': reboot the bot (returns 2)")
print(" - 'install': reboot the bot and install dependencies (returns 4)")
print(" - 'update': reboot the bot and update dependencies (returns 5)")
elif i.lower() in ("shutdown","exit","quit","reboot","restart","install","update"):
try:
task_list = asyncio.Task.all_tasks()
except AttributeError:
task_list = asyncio.all_tasks()
for task in task_list:
try: task.cancel()
except: continue
try:
await bot.close()
bot.loop.stop()
bot.loop.close()
except:
pass
# Try to flush settings first
settings = bot.get_cog("Settings")
if settings:
print("Flushing settings...")
if os.path.isfile(os.path.join("Cogs","PandorasDB.py")):
# Flush the redis branch
settings.flushSettings()
else:
# Flush the rewrite branch to file
settings.flushSettings(settings.file)
# Kill this process
returncode = 2
if i.lower() in ("shutdown","exit","quit"):
returncode = 3
elif i.lower() == "install":
returncode = 4
elif i.lower() == "update":
returncode = 5
os._exit(returncode)
# Run the bot
print("Starting up {} shard{}...".format(bot.shard_count,"" if bot.shard_count == 1 else "s"))
bot.loop.create_task(watchinput())
try:
bot.run(settings_dict.get("token",""))
except errors.LoginFailure as e:
print("\nSomething went wrong logging in: {}\n".format(e))
if "token" in str(e).lower():
print("You can create/reset your token in the Developer Portal:\n")
print("1. Go to https://discord.com/developers/applications")
print("2. Select your bot under 'My Applications' or click 'New Application' to")
print(" create a new bot")
print("3. Click 'Bot' in the menu on the left side of the page")
print("4. Click 'Reset Token'")
print(" - DO NOT SHARE THIS TOKEN WITH ANYONE")
print(" - YOU CAN ONLY VIEW IT ONCE")
print("5. Copy the token to the clipboard")
print("")
os._exit(6)
os._exit(3)
except RuntimeError as e:
print("Dirty shutdown - runtime error minimized:\n - {}".format(e))