-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauthl.py
691 lines (483 loc) · 19.2 KB
/
authl.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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
#######################################################
# digital_pet #
# p r e s e n t s #
# A fucking something awful authbot fucking shit. #
#######################################################
###
# Imports
###
import logging
import asyncio
import os
import re
import interactions
import sqlite3
import crypt
from configparser import ConfigParser
from awfulpy import *
from contextlib import closing
from datetime import datetime
###
# Config
###
secrets = ConfigParser()
secrets.read('secrets.ini')
config = ConfigParser()
config.read('config.ini')
bbuserid = secrets['SAForums']['bbuserid']
bbpassword = secrets['SAForums']['bbpassword']
sessionid = secrets['SAForums']['sessionid']
sessionhash = secrets['SAForums']['sessionhash']
bottoken = secrets['Discord']['token']
dbfile=config['Database']['file']
goonrole=config['Discord']['roleID']
guildid=config['Discord']['guildID']
bschan=config['Discord']['botspamID']
###
# instantiate awful scraper and bot
###
profile = AwfulProfile(bbuserid, bbpassword, sessionid, sessionhash)
bot = interactions.Client(token=bottoken)
#db_cursor.execute('''CREATE TABLE goons (userID TEXT NOT NULL, discordID TEXT NOT NULL, secret TEXT NOT NULL, is_banned INTEGER NOT NULL CHECK (is_banned IN (0, 1)), is_authed INTEGER NOT NULL CHECK (is_authed IN (0, 1)), is_sus INTEGER NOT NULL CHECK (is_sus IN (0, 1))) ''')
###
# Setup logging
###
loglevelDict = {
'debug' : logging.DEBUG,
'info' : logging.INFO,
'warning' : logging.WARNING,
'error' : logging.ERROR,
'critical' : logging.CRITICAL}
logging.basicConfig(filename=config['Logging']['file'], encoding='utf-8', level=loglevelDict[config['Logging']['level']])
###
# db wrapper for parameterized queries
###
def query(db_name, querystring, params):
with closing(sqlite3.connect(db_name)) as con, con, closing(con.cursor()) as cur:
cur.execute(querystring, params)
return cur.fetchall()
###
# Auth worker loop
###
async def auth_processor():
get_query = '''SELECT * FROM goons WHERE is_banned=0 AND is_authed=0 AND is_sus=0'''
get_params = {}
auth_query = '''UPDATE goons SET is_authed=1 WHERE userID=:userid LIMIT 1'''
await asyncio.sleep(10)
botspamchannel = interactions.Channel(**await bot._http.get_channel(bschan), _client=bot._http)
while True:
await asyncio.sleep(10)
logging.info("auth worker running")
results = query(dbfile, get_query, get_params)
if results:
success = ""
displaymessage = False
for r in results:
userid = r[0]
user = interactions.Member(**await bot._http.get_member(guildid,r[1]), _client=bot._http)
if user.user is None:
logging.info(f"User with discord id {r[1]} is not in the server, skipping.")
continue
result = await profile.fetch_profile_by_id(userid)
fulltext = result.raw_profile_text
position = fulltext.find(r[2])
if position > -1:
auth_params = {"userid":userid}
try:
#await get(bot, interactions.Member, parent_id=guildid, object_id=r[1])
await user.add_role(goonrole,guildid)
success = success + "\n" + user.mention
displaymessage = True
query(dbfile, auth_query, auth_params)
except Exception:
logging.error("Could not auth user", exc_info=True)
await botspamchannel.send("Authenticating user " + user.mention + " failed.")
await asyncio.sleep(10)
continue
await asyncio.sleep(10)
if displaymessage:
await botspamchannel.send("Gave goon role to the following users " + success)
logging.info("auth worker waiting")
await asyncio.sleep(890)
###
# Exceptions that may be encountered during authentication
###
class DuplicateEntry(Exception):
pass
class UserMismatch(Exception):
pass
class DiscordMismatch(Exception):
pass
class BannedUser(Exception):
pass
###
# Authentication functions
###
async def get_userid(username):
result = await profile.fetch_profile(username)
return result.userid
async def calculate_suspicion(userid):
result = await profile.fetch_profile_by_id(userid)
fulltext = result.raw_profile_text
sus = 0
#sub 300 postcount is sus
re_res = re.search(r"en \<b\>-?([0-9]*)\<\/b\> po", fulltext)
postcount = int(re_res.group(1))
if postcount < 300:
sus = 1
#regdate less than 3 months is sus
result = re.search(r"registering on \<b\>(.*)\<\/b\>", fulltext)
regdate = datetime.strptime(result.group(1), "%b %d, %Y")
threshhold = datetime.timestamp(datetime.now()) - (2629800*3)
if datetime.timestamp(regdate) > threshhold:
sus = 1
return sus
async def get_user(userid,discordid):
get_query = '''SELECT * FROM goons WHERE userID=:userid OR discordID=:discordid'''
get_params = {"userid": userid, "discordid":discordid}
kos_check_query = '''SELECT * FROM kos WHERE userID=:userid LIMIT 1'''
kos_params = {"userid":userid}
results = query(dbfile, get_query, get_params)
if len(results) > 1:
raise DuplicateEntry("Expected 1 result, got " + len(results))
if not results:
#If there isn't an existing user, add it.
sus = await calculate_suspicion(userid)
# TODO: log in botspam if sus
secret = crypt.crypt(f"{discordid}{userid}")
minsecret = "HONK!" + secret[20:32]
ban = 1 if len(query(dbfile,kos_check_query,kos_params)) else 0
ins_query = '''INSERT INTO goons values (:userid,:discordid,:secret,:ban,0,:sus)'''
ins_params = {"userid": userid,"discordid": discordid,"secret":minsecret,"ban":ban,"sus":sus}
query(dbfile, ins_query,ins_params)
results = query(dbfile, get_query, get_params)
if results[0][0] != userid:
logging.error("UserMismatch - " + str(results))
raise UserMismatch("User provided " + userid + ", db contained " + results[0][0])
if results[0][1] != discordid:
logging.error("DiscordMismatch - " + str(results))
raise DiscordMismatch("User provided " + discordid + ", db contained " + results[0][1])
if results[0][3]:
logging.error("BannedUser - " + str(results))
raise BannedUser("User is banned!")
return results
###
# Bot commands
###
'''
'''
@bot.command(
name="authme",
description="Get authorized in this discord",
dm_permission=False,
options = [
interactions.Option(
name = "username",
description = "Your username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def authme(ctx: interactions.CommandContext, username: str):
botspamchannel = interactions.Channel(**await bot._http.get_channel(bschan), _client=bot._http)
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
response = f"Found {username} with ID {userid}"
try:
results = await get_user(userid,str(ctx.author.id))
except BannedUser:
response = "You are banned! Contact leadership if you wish to appeal your ban."
await ctx.send(response)
return
except UserMismatch:
response = "An error occured. Please ping leadership."
await ctx.send(response)
return
except DiscordMismatch:
response = "An error occured. Please ping leadership."
await ctx.send(response)
return
except DuplicateEntry:
response = "A duplicate entry was encountered. This should never happen. The database is corrupted."
await ctx.send(response)
return
response = response + "\n" + f"Put the following key in your SA profile: {results[0][2]}"
if results[0][5]:
await botspamchannel.send("User " + ctx.author.mention + " needs attention to complete authentication.")
response = response + "\n\nA member of leadership may contact you to complete your authentication."
else:
response = response + "\n\nYou will be automatically authenticated within 24 hours."
await ctx.send(response)
'''
'''
@bot.command(
name="authem",
description="Auth someone else on this discord",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,
options = [
interactions.Option(
name = "user",
description = "The discord user who should be authed",
type=interactions.OptionType.USER,
required=True),
interactions.Option(
name = "username",
description = "Your username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def authem(ctx: interactions.CommandContext, user: interactions.User, username: str):
botspamchannel = interactions.Channel(**await bot._http.get_channel(bschan), _client=bot._http)
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
response = f"Found {username} with ID {userid}"
try:
results = await get_user(userid,str(user.id))
except BannedUser:
response = "They are banned!"
await ctx.send(response)
return
except UserMismatch:
response = "An error occured: This discord account is registered to another SA user."
await ctx.send(response)
return
except DiscordMismatch:
response = "An error occured. This SA account is registered to another discord user."
await ctx.send(response)
return
response = response + "\n" + user.mention + f" Put the following key in your SA profile: {results[0][2]}"
if results[0][5]:
await botspamchannel.send("User " + user.mention + " needs attention to complete authentication.")
response = response + "\n\nA member of leadership may contact you to complete your authentication."
else:
response = response + "\n\nYou will be automatically authenticated within 24 hours."
await ctx.send(response)
'''
'''
@bot.command(
name="listsus",
description="List all sus goons",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,)
async def listsus(ctx: interactions.CommandContext):
querystr = '''SELECT * FROM goons WHERE is_sus = 1 AND is_banned = 0'''
params = {}
result = query(dbfile, querystr, params)
if result:
response = str(len(result)) + " goons are sus:"
for r in result:
user = interactions.Member(**await bot._http.get_member(guildid,r[1]), _client=bot._http)
try:
response = response + "\n" + user.mention + " (ID: " + r[0] + ")"
except Exception:
response = response + "\n User not in discord (ID: " + r[0] + ")"
else:
response = "No goons are currently being sus."
await ctx.send(response)
'''
'''
@bot.command(
name="listunauth",
description="List all unauthed goons",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,)
async def listunauth(ctx: interactions.CommandContext):
querystr = '''SELECT * FROM goons WHERE is_authed = 0 AND is_sus = 0 AND is_banned = 0'''
params = {}
result = query(dbfile, querystr, params)
if result:
response = str(len(result)) + " goons haven't put the code in:"
for r in result:
user = interactions.Member(**await bot._http.get_member(guildid,r[1]), _client=bot._http)
try:
response = response + "\n" + user.mention + " (ID: " + r[0] + ")"
except Exception:
response = response + "\n User not in discord (ID: " + r[0] + ")"
else:
response = "All the goons have followed instructions."
await ctx.send(response)
'''
'''
@bot.command(
name="listban",
description="List all banned goons",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,)
async def listban(ctx: interactions.CommandContext):
querystr = '''SELECT * FROM goons WHERE is_banned = 1'''
params = {}
result = query(dbfile, querystr, params)
if result:
response = str(len(result)) + " goons are banned:"
for r in result:
user = interactions.Member(**await bot._http.get_member(guildid,r[1]), _client=bot._http)
try:
response = response + "\n" + user.mention + " (ID: " + r[0] + ")"
except Exception:
response = response + "\n User not in discord (ID: " + r[0] + ")"
else:
response = "Nobody's banned!"
await ctx.send(response)
'''
'''
@bot.command(
name="unsus",
description="Remove the sus hold on a goon",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,
options = [
interactions.Option(
name = "username",
description = "Their username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def unsus(ctx: interactions.CommandContext, username: str):
querystr = '''UPDATE goons SET is_sus = 0 WHERE userID=:userid LIMIT 1'''
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
params = {"userid": userid}
query(dbfile, querystr, params)
response = f"{str(username)} with id {userid} has been cleared to authenticate."
await ctx.send(response)
'''
'''
@bot.command(
name="kline",
description="Ban a goon before they join",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,
options = [
interactions.Option(
name = "username",
description = "Their username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def kline(ctx: interactions.CommandContext, username: str):
querystr = '''INSERT INTO kos VALUES (:userid)'''
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
params = {"userid": userid}
query(dbfile, querystr, params)
response = f"{str(username)} with id {userid} has been k-lined."
await ctx.send(response)
'''
'''
@bot.command(
name="unkline",
description="Unban a goon before they join",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,
options = [
interactions.Option(
name = "username",
description = "Their username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def unkline(ctx: interactions.CommandContext, username: str):
querystr = '''DELETE FROM kos WHERE userID=:userid LIMIT 1'''
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
params = {"userid": userid}
query(dbfile, querystr, params)
response = f"{str(username)} with id {userid} has been unk-lined."
await ctx.send(response)
'''
'''
@bot.command(
name="bangoon",
description="Ban a goon from getting the goon role",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,
options = [
interactions.Option(
name = "username",
description = "Their username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def bangoon(ctx: interactions.CommandContext, username: str):
querystr = '''UPDATE goons SET is_banned = 1, is_authed=0 WHERE userID=:userid LIMIT 1'''
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
params = {"userid": userid}
query(dbfile, querystr, params)
response = f"{username} with id {userid} is banned. Be sure to strip their roles."
await ctx.send(response)
'''
'''
@bot.command(
name="unbangoon",
description="Allow a banned goon to get the goon role",
dm_permission=False,
default_member_permissions=interactions.Permissions.MANAGE_ROLES,
options = [
interactions.Option(
name = "username",
description = "Their username on the Something Awful Forums",
type=interactions.OptionType.STRING,
required=True),],)
async def unbangoon(ctx: interactions.CommandContext, username: str):
querystr = '''UPDATE goons SET is_banned = 0 WHERE userID=:userid LIMIT 1'''
response = ""
userid = await get_userid(username)
if userid is None:
response = f"{username} is not registered on SA."
await ctx.send(response)
return
params = {"userid": userid}
query(dbfile, querystr, params)
response = f"{username} with id {userid} is unbanned."
await ctx.send(response)
## TODO: Purge command
###
# Exception handler, crash fast for unhandled exceptions inside async functions
###
def handle_exception(loop, context):
# context["message"] will always be there; but context["exception"] may not
msg = context.get("exception", context["message"])
print("Please wait, crashing...")
logging.critical(f"Caught exception: {msg}", exc_info=True)
logging.info("Shutting down...")
os._exit(2)
###
# Main program starts here
###
logging.info('===Startup===')
loop = asyncio.get_event_loop()
loop.set_exception_handler(handle_exception)
# Backend Init
asyncio.ensure_future(auth_processor())
# Discord init
logging.info('Initializing Discord')
asyncio.ensure_future(bot._ready())
try:
loop.run_forever()
except KeyboardInterrupt:
print('\nCtrl-C received, quitting immediately')
logging.critical('Ctrl-C received, quitting immediately')
os._exit(1)
except Exception:
print("Please wait, crashing...")
logging.critical("Fatal error in main loop", exc_info=True)
os._exit(2)