-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfunctions.py
563 lines (496 loc) · 15.5 KB
/
functions.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
import re
import os
import sys
import uuid
import yaml
import random
import sqlite3
import discord
import logging as log
import hashlib as hash
from datetime import datetime, timezone
def load_yaml(yaml_file_name):
with open(
os.path.join(sys.path[0], yaml_file_name), "r", encoding="utf8"
) as yaml_file:
return yaml.safe_load(yaml_file)
def paginate(text):
pages = []
lines = text.split("\n")
page = ""
for line in lines:
if len(page + line + "\n") < 1024:
page = page + line + "\n"
else:
pages.append(page)
page = line + "\n"
pages.append(page)
return pages
def sha_256(file):
BLOCKSIZE = 65536
sha = hash.sha256()
file_buffer = file.read(BLOCKSIZE)
while len(file_buffer) > 0:
sha.update(file_buffer)
file_buffer = file.read(BLOCKSIZE)
file.close()
return sha.hexdigest()
def spongify(text):
sponged_text = ""
for character in text:
if random.choice([True, False]):
sponged_text = sponged_text + character.upper()
else:
sponged_text = sponged_text + character.lower()
return sponged_text
def sentence_case(text):
return ". ".join(i.capitalize() for i in text.split(". "))
def chance(percent):
return random.randint(0, 99) < percent
def replace_ignore_case(text, find, replace):
pattern = re.compile(find, re.IGNORECASE)
return pattern.sub(replace, text)
def ascii_only(text):
stripped = (c for c in text if 0 < ord(c) < 127)
return "".join(stripped)
def format_delta_long(delta):
years = int(delta.days / 365)
days = int(delta.days % 365)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
seconds = int(delta.seconds % 60)
formatted_delta = ""
if years == 1:
formatted_delta = formatted_delta + f"{years} Year, "
elif years > 1:
formatted_delta = formatted_delta + f"{years} Years, "
if days == 1:
formatted_delta = formatted_delta + f"{days} Day, "
elif days > 1:
formatted_delta = formatted_delta + f"{days} Days, "
if hours == 1:
formatted_delta = formatted_delta + f"{hours} Hour, "
elif hours > 1:
formatted_delta = formatted_delta + f"{hours} Hours, "
if minutes == 1:
formatted_delta = formatted_delta + f"{minutes} Minute, "
elif minutes > 1:
formatted_delta = formatted_delta + f"{minutes} Minutes, "
if seconds == 1:
formatted_delta = formatted_delta + f"{seconds} Second"
else:
formatted_delta = formatted_delta + f"{seconds} Seconds"
return formatted_delta
def format_delta(delta):
years = int(delta.days / 365)
days = int(delta.days % 365)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
seconds = int(delta.seconds % 60)
formatted_delta = ""
if years != 0:
formatted_delta = formatted_delta + f"{years}y "
if days != 0:
formatted_delta = formatted_delta + f"{days}d "
if hours != 0:
formatted_delta = formatted_delta + f"{hours}h "
if minutes != 0:
formatted_delta = formatted_delta + f"{minutes}m "
formatted_delta = formatted_delta + f"{seconds}s"
return formatted_delta
def format_countdown(delta):
years = int(delta.days / 365)
days = int(delta.days % 365)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds % 3600) / 60)
formatted_delta = ""
if years != 0:
formatted_delta = formatted_delta + f"{years}Y "
if days != 0:
formatted_delta = formatted_delta + f"{days}D "
if hours != 0:
formatted_delta = formatted_delta + f"{hours}H "
else:
if minutes != 0:
formatted_delta = formatted_delta + f"{minutes}M"
return formatted_delta
def time_since(date_time):
return datetime.utcnow() - date_time
def time_until(date_time):
return date_time - datetime.utcnow()
def date_time_from_str(timestamp):
timestamp = re.sub("[^0-9]", "", timestamp)[:14]
return datetime.strptime(timestamp[:19], "%Y%m%d%H%M%S")
def seconds_since(then):
return abs((datetime.now(timezone.utc) - then).total_seconds())
def open_database():
return sqlite3.connect(database_file_path)
def store_hash(bytes_hash, message):
with open_database() as database:
cursor = database.cursor()
date_time = message.created_at.strftime("%Y%m%d%H%M%S")
author_id = message.author.id
author_name = message.author.display_name
channel_name = message.channel.name
channel_category = message.channel.category.name
sql = """
INSERT
INTO hashes
VALUES (?,?,?,?,?,?,?)
"""
cursor.execute(
sql,
(
None,
bytes_hash,
date_time,
author_id,
author_name,
channel_name,
channel_category,
),
)
database.commit()
return
def get_hashes(bytes_hash, channel_category):
with open_database() as database:
cursor = database.cursor()
sql = """
SELECT *
FROM hashes
WHERE hash = ?
AND channel_category = ?
ORDER BY date_time DESC
"""
cursor.execute(sql, (bytes_hash, channel_category))
return cursor.fetchall()
def store_description(role_name, role_description):
with open_database() as database:
cursor = database.cursor()
role_name = role_name.lower()
sql = """
INSERT OR REPLACE
INTO descriptions
VALUES (?,?)
"""
cursor.execute(sql, (role_name, role_description))
database.commit()
return
def get_description(role_name):
with open_database() as database:
cursor = database.cursor()
role_name = role_name.lower()
sql = """
SELECT role_description
FROM descriptions
WHERE role_name = ?
"""
cursor.execute(sql, (role_name,))
return cursor.fetchone()
def store_invite_details(invite, inviter, reason, event):
with open_database() as database:
cursor = database.cursor()
id = invite.id
date_time_created = invite.created_at
date_time_used = None
inviter_id = inviter.id
inviter_name = str(inviter)
invitee_id = None
invitee_name = None
sql = """
INSERT
INTO invites
VALUES (?,?,?,?,?,?,?,?,?)
"""
cursor.execute(
sql,
(
id,
date_time_created,
date_time_used,
inviter_id,
inviter_name,
invitee_id,
invitee_name,
reason,
event,
),
)
database.commit()
return
def get_invite_details(invite):
with open_database() as database:
cursor = database.cursor()
id = invite.id
sql = """
SELECT *
FROM invites
WHERE id = ?
"""
cursor.execute(sql, (id,))
return cursor.fetchone()
def update_invite_details(invite, invitee):
with open_database() as database:
cursor = database.cursor()
id = invite.id
date_time_used = datetime.utcnow()
invitee_id = invitee.id
invitee_name = str(invitee)
sql = """
UPDATE invites
SET date_time_used = ?, invitee_id = ?, invitee_name = ?
WHERE id = ?
"""
cursor.execute(sql, (date_time_used, invitee_id, invitee_name, id))
database.commit()
return
def quote_exists(id):
with open_database() as database:
cursor = database.cursor()
sql = """
SELECT *
FROM quotes
WHERE id = ?
"""
cursor.execute(sql, (id,))
if cursor.fetchone() is None:
return False
return True
def store_quote(message, ctx):
with open_database() as database:
cursor = database.cursor()
id = message.id
channel_name = message.channel.name
date_time = datetime.now().isoformat()
author_id = message.author.id
author_name = str(message.author.display_name)
stored_by_id = ctx.author.id
stored_by_name = str(ctx.author.display_name)
quote_text = message.clean_content.replace('"', "'")
if quote_text[:1] == "'" and quote_text[-1:] == "'":
quote_text = quote_text[1:-1]
sql = """
INSERT
INTO quotes
VALUES (?,?,?,?,?,?,?,?)
"""
cursor.execute(
sql,
(
id,
channel_name,
date_time,
author_id,
author_name,
stored_by_id,
stored_by_name,
quote_text,
),
)
database.commit()
return quote_text
def get_quote(channel, phrase):
with open_database() as database:
channel_name = channel.name
cursor = database.cursor()
if channel_name == "general_chat":
if phrase == None:
sql = """
SELECT *
FROM quotes
WHERE channel_name = ?
ORDER BY RANDOM()
LIMIT 1
"""
cursor.execute(sql, (channel_name,))
else:
pattern = "%" + phrase + "%"
sql = """
SELECT *
FROM quotes
WHERE (quote_text LIKE ? OR author_name LIKE ?)
AND channel_name = ?
ORDER BY RANDOM()
LIMIT 1
"""
cursor.execute(sql, (pattern, pattern, channel_name))
else:
if phrase == None:
sql = """
SELECT *
FROM quotes
ORDER BY RANDOM()
LIMIT 1
"""
cursor.execute(sql)
else:
pattern = "%" + phrase + "%"
sql = """
SELECT *
FROM quotes
WHERE (quote_text LIKE ? OR author_name LIKE ?)
ORDER BY RANDOM()
LIMIT 1
"""
cursor.execute(sql, (pattern, pattern))
return cursor.fetchone()
def delete_quote(id):
with open_database() as database:
cursor = database.cursor()
sql = """
SELECT *
FROM quotes
WHERE id = ?
"""
cursor.execute(sql, (id,))
quote = cursor.fetchone()
sql = """
DELETE
FROM quotes
WHERE id=?
"""
cursor.execute(sql, (id,))
database.commit()
return quote
def veto_quote(id):
with open_database() as database:
cursor = database.cursor()
sql = """
UPDATE quotes
SET channel_name = 'vetoed'
WHERE id = ?
"""
cursor.execute(sql, (id,))
database.commit()
return
def create_key(member_id, member_name, key_type):
with open_database() as database:
cursor = database.cursor()
key = str(uuid.uuid1())
active = True
sql = """
INSERT
INTO keys
VALUES (?,?,?,?,?,?)
"""
cursor.execute(sql, (None, member_id, member_name, key, key_type, active))
database.commit()
return key
def get_key(member_id, key_type, active):
with open_database() as database:
cursor = database.cursor()
sql = """SELECT id, member_id, member_name, key, key_type, active
FROM keys
WHERE member_id = ?
AND key_type = ?
AND active = ?
"""
cursor.execute(sql, (member_id, key_type, active))
return cursor.fetchall()
def delete_key(member_id, key_type):
with open_database() as database:
cursor = database.cursor()
sql = """
UPDATE keys
SET active = 0
WHERE member_id = ?
AND key_type = ?
"""
cursor.execute(sql, (member_id, key_type))
database.commit()
return
def create_database():
if os.path.isfile(database_file_path):
log.info(f"Database {database_file_path} found.")
else:
log.warning(
f"Database {database_file_path} not found, an empty database is being created."
)
with open_database() as database:
cursor = database.cursor()
sql = """
CREATE TABLE IF NOT EXISTS "invites" (
"id" TEXT,
"date_time_created" TEXT,
"date_time_used" TEXT,
"inviter_id" INTEGER,
"inviter_name" TEXT,
"invitee_id" INTEGER,
"Invitee_name" TEXT,
"reason" TEXT,
"event" TEXT,
PRIMARY KEY("id")
)
"""
cursor.execute(sql)
database.commit()
sql = """
CREATE TABLE IF NOT EXISTS "quotes" (
"id" INTEGER,
"channel_name" TEXT,
"date_time" TEXT,
"author_id" INTEGER,
"author_name" TEXT,
"stored_by_id" INTEGER,
"stored_by_name" TEXT,
"quote_text" TEXT,
PRIMARY KEY("id")
)
"""
cursor.execute(sql)
database.commit()
sql = """
CREATE TABLE IF NOT EXISTS "hashes" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
"hash" INTEGER,
"date_time" TEXT,
"author_id" INTEGER,
"author_name" TEXT,
"channel_name" TEXT,
"channel_category" TEXT
)
"""
cursor.execute(sql)
database.commit()
sql = """
CREATE TABLE IF NOT EXISTS "descriptions" (
"role_name" TEXT UNIQUE,
"role_description" TEXT
)
"""
cursor.execute(sql)
database.commit()
sql = """
CREATE TABLE IF NOT EXISTS "keys" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
"member_id" INTEGER,
"member_name" TEXT,
"key" TEXT,
"key_type" TEXT,
"active" INTEGER
)
"""
cursor.execute(sql)
database.commit()
sql = """
CREATE TABLE IF NOT EXISTS "voice_activity" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE,
"member_id" INTEGER,
"member_name" TEXT,
"date_time" TEXT,
"channel_name" TEXT,
"status" INTEGER
)
"""
cursor.execute(sql)
database.commit()
return
log.basicConfig(
format="[%(asctime)s] [%(levelname)s] %(message)s",
level=log.INFO,
stream=sys.stdout,
)
config = load_yaml("config.yaml")
strings = load_yaml("strings.yaml")
waifu_pink = discord.Color.from_rgb(255, 63, 180)
database_file_path = os.path.join(sys.path[0], "data", "waifubot.db")