-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
487 lines (427 loc) · 16.2 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
import discord
import asyncio
import logging
import json
import time
import io
import sys
import random
import datetime
import re
import markov
from discord.ext import commands
from pathlib import Path
description = '''An automod bot for auto modding
'''
mark = markov.Markov
reminders = []
polls = []
TESTING = True
if TESTING:
settings = open('testing.json', 'r')
else:
settings = open('settings.json', 'r')
ds = json.load(settings)
prefix = ds['bot']['prefix']
bot = commands.Bot(command_prefix=prefix, description=description)
loop = bot.loop
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='dicord.log', encoding="utf-8", mode='w')
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logger.addHandler(handler)
logger.info("Starting SCSI {0} using discord.py {1}".format(ds['bot']["version"], discord.__version__))
print("Starting SCSI {0} using discord.py {1}".format(ds['bot']['version'], discord.__version__))
def findServer(ident):
return bot.get_server(ident)
def findChannel(server, channel):
'''finds the channel'''
for all in ds['servers']:
if all['id'] == server:
return bot.get_channel(all[channel])
## may not get used but I'm just keeping it
def findUser(id):
users = list(bot.get_all_members())
for all in users:
name = ''.join(str(all).split('#').pop(0))
if name == id:
return all
return -1
def checkRole(user, roleRec):
'''Checks if the user has the recuired role'''
ok = False
for all in list(user.roles):
if all.name == roleRec:
ok = True
return ok
def timeToTicks(time):
'''converts time into seconds than to ticks'''
time = time.lower()
time = time.split(',')
timeSec = 0
for all in time:
if "w" in all or "week" in all or "weeks" in all:
tmp = all.strip('weks')
timeSec += datetime.timedelta(weeks=int(tmp)).total_seconds()
elif "d" in all or "day" in all or "days" in all:
tmp = all.strip('days')
timeSec += datetime.timedelta(days=int(tmp)).total_seconds()
elif "h" in all or "hour" in all or "hours" in all:
tmp = all.strip('hours')
timeSec += datetime.timedelta(hours=int(tmp)).total_seconds()
elif "m" in all or "minute" in all or "minutes" in all:
tmp = all.strip('minutes')
timeSec += datetime.timedelta(minutes=int(tmp)).total_seconds()
elif "s" in all or "second" in all or "seconds" in all:
tmp = all.strip('second')
timeSec += int(tmp)
else:
tmp = all.strip('ticks')
timeSec += int(tmp) * ds['bot']['ticklength']
return timeSec // ds['bot']['ticklength']
@asyncio.coroutine
async def timer():
await bot.wait_until_ready()
while not bot.is_closed:
loop.create_task(on_tick())
await asyncio.sleep(ds['bot']['ticklength'])
@bot.event
async def on_channel_delete(channel):
server = channel.server.id
msg = "Channel {0} has been deleted!".format(channel.mention)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_channel_create(channel):
server = channel.server.id
msg = "Channel {0} has been created!".format(channel.mention)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_member_join(member):
server = member.server.id
msg = "New member {0} has joined the server!".format(member.mention)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_member_remove(member):
server = member.server.id
msg = "Member {0} has left the server!".format(member.name)
try:
await bot.send_message(findChannel(server, 'announcements'), msg, tts=ds['bot']['tts'])
except discord.Forbidden:
msg = "Missing Permissions for announcements!"
await bot.send_message(findChannel(server, 'botspam'), msg, tts=ds['bot']['tts'])
@bot.event
async def on_command(command, ctx):
message = ctx.message
destination = None
if message.channel.is_private:
destination = "Private Message"
else:
destination = "#{0.channel.name} ({0.server.name})".format(message)
@bot.group(pass_context = True)
async def markov(ctx):
'''the markov command group'''
if ctx.invoked_subcommand == None:
await bot.say("Must be used with a sub command!")
@markov.command()
async def read(*text):
'''has the makrkov chain read text'''
try:
mark.readText(" ".join(text))
await bot.say("Read text!")
except TypeError as e:
print(e)
@markov.command(pass_contect=True)
async def readChan(ctx, n = "100"):
'''do the same thing as backup but have the markov chain read the channel'''
await bot.say("This feature has not been implemented yet!")
@markov.command()
async def save():
mark.save()
await bot.say("Saved current vocab!")
@markov.command()
async def write(n: str = '100'):
n = int(n)
await bot.say("Markov incoming!")
msg = "```" + mark.writeText(n) + "```"
await bot.say(msg)
@bot.command()
async def test():
'''Prints a test message'''
await bot.say("HELLO WORLD!")
@bot.command(pass_context=True)
async def poll(ctx, time, description, *options):
'''Creates a poll'''
pollNum = ds['bot']['pollNum']
ds['bot']['pollNum'] += 1
try:
## time = int(time)
time = timeToTicks(time)
desc = description
pos = {}
server = ctx.message.server.id
for all in options:
pos[all] = 0
polls.append({"time":time, 'pollNum':pollNum, "desc":desc, "pos":pos, "server":server})
await bot.say("New poll created! #{0}, possibilities: {1}".format(pollNum, pos))
except:
await bot.say('Incorrect number format')
@bot.command()
async def vote(number, option):
'''Votes on a poll'''
try:
pollNum = int(number)
pos = option
for all in polls:
if all['pollNum'] == pollNum:
if pos in all['pos'].keys():
all['pos'][pos] += 1
break # Why waste valuable processing cycles?
await bot.say('Invalid option for that poll')
except ValueError:
await bot.say('Incorrect number format')
@bot.command()
async def timeto(ticks):
'''says how much time will pass in <ticks> ticks
!!obsolite!!'''
try:
ticks = int(''.join(ticks))
seconds = ds['bot']['ticklength'] * ticks
hours = seconds // 36000
seconds %= 36000
minutes = seconds // 60
seconds %= 60
seconds = round(seconds, 0)
msg = "{0} ticks is {1} hours, {2} minutes, {3} seconds long".format(ticks, hours, minutes, seconds)
await bot.say(msg)
except ValueError:
await bot.say("Invalid arguments")
@bot.command(pass_context=True)
async def shutdown(ctx):
'''Shuts down the bot'''
author = ctx.message.author
if checkRole(author, ds['bot']['botmin']):
msg = "Shutting down now!"
await bot.say(msg)
timerTask.cancel()
bot.logout()
settings.close()
sys.exit()
else:
await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin']))
@bot.command()
async def timeup():
'''Displays time up'''
timeUp = time.time() - startTime
hoursUp = timeUp // 36000
timeUp %= 36000
minutesUp = timeUp // 60
timeUp = round(timeUp % 60, 0)
msg = "Time up is: *{0} Hours, {1} Minutes and, {2} Seconds*".format(hoursUp, minutesUp, timeUp)
await bot.say(msg)
#the following code does not work, and so we will not keep it
#@bot.command(pass_context=True)
#async def tts(ctx):
# '''Turns TTS on or off'''
# if ctx.message.content[len(prefix) + 4:] == "on":
# ds['bot']['tts'] = True
# await bot.say("TTS is now on!")
# elif ctx.message.content[len(prefix) + 4:] == "off":
# ds['bot']['tts'] = False
# await bot.say("TTS is now off!")
@bot.command()
async def echo(*, message):
'''Echos a message'''
print('Echoing: ', message)
logger.info('Echoing: {0}'.format(message))
await bot.say(message)
@bot.command(pass_context=True)
async def changegame(ctx, *game):
'''Changes the game being displayed'''
author = ctx.message.author
if checkRole(author, ds['bot']['botmin']):
gameName = ' '.join(game)
await bot.change_presence(game=discord.Game(name=gameName))
await bot.say("Changing game to: \"{0}\"!".format(gameName))
else:
await bot.say("User is not {0}, ask a {0} to use this command!".format(ds['bot']['botmin']))
@bot.command(pass_context=True)
async def remind(ctx, delay, *message):
'''Sets a reminder for several seconds in the future'''
msg = ' '.join(message)
chan = ctx.message.channel
try:
## following code kept for posterity
## delay = int(float(delay) / ds['bot']['ticklength'])
## if delay == 0:
## delay = 1
## reminders.append([delay, chan, msg])
## await bot.say("Reminder set")
delay = timeToTicks(delay)
if delay == 0:
delay = 1
reminders.append([delay, chan, msg])
await bot.say("Reminder set")
except ValueError:
await bot.say("Incorrect format for the delay")
@bot.command()
async def about():
try:
msg = "```Version: {0}\nPrefix: {1}\n\"Game\": {2}\nContributors: {3}```".format(ds['bot']['version'], ds['bot']['prefix'], ds['bot']['game'], str(ds['contrib']).strip("[]"))
await bot.say(msg)
except:
pass
@bot.command(pass_context=True)
async def backup(ctx, num="1000"):
'''Backs up <num> messages in the current channel. "all" will back up the entire channel. If num is not provided, defaults to 1000'''
try:
msg = ctx.message
# Assuming not Wham!DOS paths, although those may work as well
servPath = msg.server.id + ' - ' + msg.server.name + '/'
chanPath = msg.channel.id + ' - ' + msg.channel.name + '/'
p = Path(servPath)
if not p.exists(): p.mkdir()
p = Path(servPath + chanPath)
if not p.exists(): p.mkdir()
newliner = re.compile('\n')
end = last_backup_time(servPath + chanPath)
if num.lower() == "all":
await bot.send_message(msg.channel, "Starting backup")
count = 1000
total = 0
start_time = None
now_time = None
# Probably a better way to do this, but I don't know it
async for m in bot.logs_from(msg.channel, limit=1):
now_time = m.timestamp
while count == 1000:
count = 0
first = True
f = open(servPath + chanPath + 'temp', 'w')
async for message in bot.logs_from(msg.channel, limit=1000, before=now_time, after=end):
if first:
start_time = message.timestamp
first = False
m = message.clean_content
m = newliner.sub('\n\t', m)
f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.display_name) + '):\n\t' + m + '\n')
f.write('attachments:\n')
for a in message.attachments:
f.write('\t')
f.write(a['url'])
f.write('\n')
f.write('\n')
now_time = message.timestamp
count += 1
total += 1
f.close()
Path(servPath + chanPath + 'temp').rename(servPath + chanPath + str(now_time) + ' -- ' + str(start_time) + '.log')
await bot.say("Backed up " + str(total) + " messages")
await bot.say("Backup finished")
else:
num = int(num)
f = open(servPath + chanPath + 'temp', 'w')
await bot.say('Starting backup')
first = True
start_time = None
end_time = None
async for message in bot.logs_from(msg.channel, limit=num + 1, after=end):
if first:
start_time = message.timestamp
first = False
else:
m = message.clean_content
m = newliner.sub('\n\t', m)
f.write(str(message.timestamp) + ': ' + message.author.name + ' (' + str(message.author.nick) + '):\n\t' + m + '\n')
f.write('attachments:\n')
for a in message.attachments:
f.write('\t')
f.write(a['url'])
f.write('\n')
f.write('\n')
end_time = message.timestamp
f.close()
Path(servPath + chanPath + 'temp').rename(servPath + chanPath + str(end_time) + ' -- ' + str(start_time) + '.log')
await bot.say('Backup finished')
except ValueError:
await bot.say('Incorrect number format')
except e:
await bot.send_message()
@bot.command(pass_context=True)
async def who(ctx, user):
'''Gives info on a mentioned user'''
try:
users = list(bot.get_all_members())
for all in users:
if all.mentioned_in(ctx.message):
user = all
break
if user == None:
await bot.say("mention a user!")
msg = "```Name: {0}\nID: {1}\nDiscriminator: {2}\nBot: {3}\nCreated: {5}\nNickname: {6}```Avatar URL: {4}\n".format(user.name, user.id, user.discriminator, user.bot, user.avatar_url, user.created_at, user.display_name)
await bot.say(str(user))
await bot.say(msg)
except:
await bot.say("Please mention a user!")
@asyncio.coroutine
async def on_tick():
for rem in reminders:
rem[0] -= 1
if rem[0] == 0:
await bot.send_message(rem[1], rem[2])
reminders.remove(rem)
for poll in polls:
poll["time"] -= 1
if poll["time"] == 0:
server = poll['server']
channel = findChannel(server, "poll")
await bot.send_message(channel, poll['pos'])
await bot.send_message(channel, "poll #{0} is now over!".format(poll['pollNum']))
polls.remove(poll)
def last_backup_time(backup_dir):
p = Path(backup_dir)
last_file = None
for f in p.iterdir():
last_file = f
if last_file is None: return None
file_name = str(last_file)
split_name = file_name.split('-- ')
date_str = split_name[1]
return string_to_datetime(date_str)
def string_to_datetime(s):
date_and_time = s.split()
date = date_and_time[0].split('-')
time = date_and_time[1].split(':')
seconds_and_micro = time[2].split('.')
return datetime.datetime(year=int(date[0]), month=int(date[1]), day=int(date[2]), hour=int(time[0]), minute=int(time[1]), second=int(seconds_and_micro[0]), microsecond=int(seconds_and_micro[1]))
@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('Game set to:')
print(ds['bot']['game'])
print('------')
logger.info('Logged in as')
logger.info(bot.user.name)
logger.info(bot.user.id)
logger.info('Game set to:')
logger.info(ds['bot']['game'])
logger.info('------')
await bot.change_presence(game=discord.Game(name=ds['bot']['game']))
startTime = time.time()
timerTask = loop.create_task(timer())
bot.run(ds['bot']["token"])
settings.close()
mark.stop()