-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.py
6730 lines (5925 loc) · 378 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
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# coding=utf-8
import pymysql
import pydle
import random
from random import choice
import datetime
import time
from threading import Timer, Thread
import urllib.request
import requests
import json
import threading
import math
import functools
from string import ascii_letters
from collections import defaultdict, OrderedDict
from private_functions import validateWaifuURL, processWaifuURL, validateBadgeURL, processBadgeURL, tokenGachaRoll
import sys
import re
import logging
import base64
import websocket
import _thread as thread
formatter = logging.Formatter('[%(asctime)s][%(name)s][%(levelname)s] %(message)s')
logger = logging.getLogger('nepbot')
logger.setLevel(logging.DEBUG)
logger.propagate = False
fh = logging.handlers.TimedRotatingFileHandler('debug.log', when='midnight', encoding='utf-8')
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)
logger.addHandler(ch)
logging.getLogger('tornado.application').addHandler(fh)
logging.getLogger('tornado.application').addHandler(ch)
ffzws = 'wss://andknuckles.frankerfacez.com'
pool = pydle.ClientPool()
current_milli_time = lambda: int(round(time.time() * 1000))
pymysql.install_as_MySQLdb()
dbpw = None
dbname = None
dbhost = None
dbuser = None
silence = False
debugMode = False
streamlabsclient = None
twitchclientsecret = None
bannedWords = []
t = None
# read config values from file (db login etc)
try:
f = open("nepbot.cfg", "r")
lines = f.readlines()
for line in lines:
name, value = line.split("=", 1)
value = str(value).strip("\n")
logger.info("Reading config value '%s' = '<redacted>'", name)
if name == "dbpassword":
dbpw = value
if name == "database":
dbname = value
if name == "dbhost":
dbhost = value
if name == "dbuser":
dbuser = value
if name == "streamlabsclient":
streamlabsclient = value
if name == "twitchclientsecret":
twitchclientsecret = value
if name == "log":
logger.info("Setting new console log level to %s", value)
ch.setLevel(logging.getLevelName(value))
if name == "silent" and value == "True":
logger.warning("Silent mode enabled")
silence = True
if name == "debugMode" and value == "True":
logger.warning("Debug mode enabled, !as command is available")
debugMode = True
if name == "bannedWords":
bannedWords = [word.lower() for word in value.split(",")]
if dbpw is None:
logger.error("Database password not set. Please add it to the config file, with 'dbpassword=<pw>'")
sys.exit(1)
if dbname is None:
logger.error("Database name not set. Please add it to the config file, with 'database=<name>'")
sys.exit(1)
if dbhost is None:
logger.error("Database host not set. Please add it to the config file, with 'dbhost=<host>'")
sys.exit(1)
if dbuser is None:
logger.error("Database user not set. Please add it to the config file, with 'dbuser=<user>'")
sys.exit(1)
if twitchclientsecret is None:
logger.error("Twitch Client Secret not set. Please add it to the conig file, with 'twitchclientsecret=<pw>'")
sys.exit(1)
f.close()
except Exception:
logger.error("Error reading config file (nepbot.cfg), aborting.")
sys.exit(1)
db = pymysql.connect(host=dbhost, user=dbuser, passwd=dbpw, db=dbname, autocommit="True", charset="utf8mb4")
admins = []
superadmins = []
activitymap = {}
marathonActivityMap = {}
blacklist = []
config = {}
packAmountRewards = {}
emotewaremotes = []
revrarity = {}
visiblepacks = ""
validalertconfigvalues = []
discordhooks = []
cpuVoters = []
busyLock = threading.Lock()
discordLock = threading.Lock()
streamlabsLock = threading.Lock()
streamlabsauthurl = "https://www.streamlabs.com/api/v1.0/authorize?client_id=" + streamlabsclient + "&redirect_uri=https://marenthyu.de/cgi-bin/waifucallback.cgi&response_type=code&scope=alerts.create&state="
streamlabsalerturl = "https://streamlabs.com/api/v1.0/alerts"
alertheaders = {"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"}
time_regex = re.compile('(?P<hours>[0-9]*):(?P<minutes>[0-9]{2}):(?P<seconds>[0-9]{2})([\.:](?P<ms>[0-9]{1,3}))?')
waifu_regex = None
def loadConfig():
global revrarity, blacklist, visiblepacks, admins, superadmins, validalertconfigvalues, waifu_regex, emotewaremotes, discordhooks, packAmountRewards
with db.cursor() as curg:
curg.execute("SELECT * FROM config")
logger.info("Importing config from database")
for row in curg.fetchall():
config[row[0]] = row[1]
logger.debug("Config: %s", str(config))
if int(config["emoteWarStatus"]) == 1:
# emote war active, get its emotes
curg.execute("SELECT name FROM emoteWar")
emotewaremotes = [row[0] for row in curg.fetchall()]
else:
emotewaremotes = []
alertRarityRange = range(int(config["drawAlertMinimumRarity"]), int(config["numNormalRarities"]))
validalertconfigvalues = ["color", "alertChannel", "defaultLength", "defaultSound", "setClaimSound",
"setClaimLength"] \
+ ["rarity%dLength" % rarity for rarity in alertRarityRange] \
+ ["rarity%dSound" % rarity for rarity in alertRarityRange]
waifu_regex = re.compile('(\[(?P<id>[0-9]+?)])?(?P<name>.+?) *- *(?P<series>.+) *- *(?P<rarity>[0-' + str(
int(config["numNormalRarities"]) + int(config["numSpecialRarities"]) - 1) + ']) *- *(?P<link>.+?)$')
logger.debug("Alert config values: %s", str(validalertconfigvalues))
logger.debug("Waifu regex: %s", str(waifu_regex))
logger.info("Fetching admin list...")
curg.execute("SELECT name, super FROM admins")
admins = []
superadmins = []
for row in curg.fetchall():
admins.append(row[0])
if row[1] != 0:
superadmins.append(row[0])
logger.debug("Admins: %s", str(admins))
logger.debug("SuperAdmins: %s", str(superadmins))
revrarity = {config["rarity" + str(i) + "Name"]: i for i in
range(int(config["numNormalRarities"]) + int(config["numSpecialRarities"]))}
curg.execute("SELECT id FROM banned_users WHERE banned = 1")
blacklist = [int(row[0]) for row in curg.fetchall()]
# visible packs
curg.execute("SELECT name FROM boosters WHERE listed = 1 AND buyable = 1 ORDER BY sortIndex ASC")
packrows = curg.fetchall()
visiblepacks = "/".join(row[0] for row in packrows)
# discord hooks
with discordLock:
curg.execute("SELECT url FROM discordHooks ORDER BY priority DESC")
discrows = curg.fetchall()
discordhooks = [row[0] for row in discrows]
# pack amount rewards
packAmountRewards = {}
curg.execute("SELECT boostername, de_amount, reward_booster FROM pack_amount_rewards")
rewardRows = curg.fetchall()
for row in rewardRows:
if row[0] not in packAmountRewards:
packAmountRewards[row[0]] = {}
packAmountRewards[row[0]][int(row[1])] = row[2]
def checkAndRenewAppAccessToken():
global config, headers
r = requests.get("https://id.twitch.tv/oauth2/validate", headers={"Authorization": "Bearer %s" % config["appAccessToken"], "Client-ID": config["clientID"]})
resp = r.json()
if "client_id" not in resp or ("status" in resp and resp["status"] == 401):
# app access token has expired, get a new one
logger.debug("Requesting new token")
url = 'https://id.twitch.tv/oauth2/token?client_id=%s&client_secret=%s&grant_type=client_credentials' % (
config["clientID"], twitchclientsecret)
r = requests.post(url)
try:
jsondata = r.json()
if 'access_token' not in jsondata or 'expires_in' not in jsondata:
raise ValueError("Invalid Twitch API response, can't get an app access token.")
config["appAccessToken"] = jsondata['access_token']
logger.debug("request done")
cur = db.cursor()
cur.execute("UPDATE config SET value = %s WHERE name = 'appAccessToken'", [jsondata['access_token']])
cur.close()
headers = {"Authorization": "Bearer %s" % config["appAccessToken"], "Client-ID": config["clientID"]}
except ValueError as error:
logger.error("Access Token renew/get request was not successful")
raise error
def booleanConfig(name):
return name in config and config[name].strip().lower() not in ["off", "no", "false"]
def placeBet(channel, userid, betms):
cur = db.cursor()
cur.execute("SELECT id FROM bets WHERE channel = %s AND status = 'open' LIMIT 1", [channel])
row = cur.fetchone()
if row is None:
cur.close()
return False
cur.execute("REPLACE INTO placed_bets (betid, userid, bet, updated) VALUE (%s, %s, %s, %s)",
[row[0], userid, betms, current_milli_time()])
cur.close()
return True
def endBet(channel):
# find started bet data
cur = db.cursor()
cur.execute("SELECT id FROM bets WHERE channel = %s AND status = 'started' LIMIT 1", [channel])
row = cur.fetchone()
if row is None:
cur.close()
return None
# mark the bet as closed
endTime = current_milli_time()
cur.execute("UPDATE bets SET status = 'completed', endTime = %s WHERE id = %s", [endTime, row[0]])
# calculate preliminary results
cur.close()
return getBetResults(row[0])
def getBetResults(betid):
# get bet data
cur = db.cursor()
cur.execute("SELECT status, startTime, endTime FROM bets WHERE id = %s", [betid])
betrow = cur.fetchone()
if betrow is None:
cur.close()
return None
if betrow[0] != 'completed' and betrow[0] != 'paid':
cur.close()
return None
timeresult = betrow[2] - betrow[1]
cur.execute(
"SELECT bet, userid, users.name FROM placed_bets INNER JOIN users ON placed_bets.userid = users.id WHERE betid = %s ORDER BY updated ASC",
[betid])
rows = cur.fetchall()
placements = sorted(rows, key=lambda row: abs(int(row[0]) - timeresult))
actualwinners = [{"id": row[1], "name": row[2], "bet": row[0], "timedelta": row[0] - timeresult} for row in
placements]
cur.close()
return {"result": timeresult, "winners": actualwinners}
class NotEnoughBetsException(Exception):
pass
class NoBetException(Exception):
pass
class NotOpenLongEnoughException(Exception):
pass
def startBet(channel, confirmed=False):
with db.cursor() as cur:
cur.execute("SELECT id, openedTime FROM bets WHERE channel = %s AND status = 'open' LIMIT 1", [channel])
row = cur.fetchone()
if row is not None:
if not confirmed:
cur.execute("SELECT COUNT(*) FROM placed_bets WHERE betid = %s", [row[0]])
if cur.fetchone()[0] < int(config["betMinimumEntriesForPayout"]):
raise NotEnoughBetsException()
if row[1] is not None and int(row[1]) + int(config["betMinimumMinutesOpen"])*60000 > current_milli_time():
raise NotOpenLongEnoughException()
cur.execute("UPDATE bets SET startTime = %s, status = 'started' WHERE id = %s", [current_milli_time(), row[0]])
else:
raise NoBetException()
def openBet(channel):
cur = db.cursor()
cur.execute("SELECT COUNT(*) FROM bets WHERE channel = %s AND status IN('open', 'started')", [channel])
result = cur.fetchone()[0] or 0
if result > 0:
cur.close()
return False
else:
cur.execute("INSERT INTO bets(channel, status, openedTime) VALUES (%s, 'open', %s)", [channel, current_milli_time()])
cur.close()
return True
def cancelBet(channel):
cur = db.cursor()
affected = cur.execute("UPDATE bets SET status = 'cancelled' WHERE channel = %s AND status IN('open', 'started')",
[channel])
cur.close()
return affected > 0
def getHand(twitchid):
try:
tID = int(twitchid)
except Exception:
logger.error("Got non-integer id for getHand. Aborting.")
return []
with db.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute("SELECT cards.id AS cardid, waifus.name, waifus.id AS waifuid, cards.rarity, waifus.series, COALESCE(cards.customImage, waifus.image) AS image, waifus.base_rarity, cards.tradeableAt, waifus.is_event AS waifu_event, cards.isEvent AS card_event FROM cards JOIN waifus ON cards.waifuid = waifus.id WHERE cards.userid = %s AND cards.boosterid IS NULL ORDER BY COALESCE(cards.sortValue, 32000) ASC, (rarity < %s) DESC, waifus.id ASC, cards.id ASC",
[tID, int(config["numNormalRarities"])])
return cur.fetchall()
def getOpenBooster(twitchid):
try:
tID = int(twitchid)
except Exception:
logger.error("Got non-integer id for getBooster. Aborting.")
return []
with db.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute("SELECT id, boostername, paid FROM boosters_opened WHERE userid = %s AND status = 'open' LIMIT 1", [tID])
booster = cur.fetchone()
if booster is None:
return None
cur.execute("SELECT cards.id AS cardid, waifus.name, waifus.id AS waifuid, cards.rarity, waifus.series, COALESCE(cards.customImage, waifus.image) AS image, waifus.base_rarity FROM cards JOIN waifus ON cards.waifuid = waifus.id WHERE cards.userid = %s AND cards.boosterid = %s ORDER BY waifus.id ASC", [tID, booster['id']])
booster['cards'] = cur.fetchall()
return booster
def getCard(cardID):
with db.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute("SELECT cards.*, waifus.base_rarity, waifus.image FROM cards JOIN waifus ON cards.waifuid=waifus.id WHERE cards.id = %s", [cardID])
return cur.fetchone()
def addCard(userid, waifuid, source, boosterid=None, rarity=None, event=None):
with db.cursor() as cur:
if rarity is None:
cur.execute("SELECT base_rarity FROM waifus WHERE id = %s", [waifuid])
rarity = cur.fetchone()[0]
if event is None:
cur.execute("SELECT is_event FROM waifus WHERE id = %s", [waifuid])
event = cur.fetchone()[0]
waifuInfo = [userid, boosterid, waifuid, rarity, current_milli_time(), userid, boosterid, source, event]
cur.execute("INSERT INTO cards (userid, boosterid, waifuid, rarity, created, originalOwner, originalBooster, source, isEvent) VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)", waifuInfo)
return cur.lastrowid
def updateCard(id, changes):
changes["updated"] = current_milli_time()
with db.cursor() as cur:
cur.execute('UPDATE cards SET {} WHERE id = %s'.format(', '.join('{}=%s'.format(k) for k in changes)), list(changes.values()) + [id])
def search(query, series=None):
cur = db.cursor()
if series is None:
cur.execute("SELECT id, name, series, base_rarity FROM waifus WHERE can_lookup = 1 AND name LIKE %s",
["%" + query + "%"])
else:
cur.execute(
"SELECT id, name, series, base_rarity FROM waifus WHERE can_lookup = 1 AND name LIKE %s AND series LIKE %s",
["%" + query + "%", "%" + series + "%"])
rows = cur.fetchall()
ret = []
for row in rows:
ret.append({'id': row[0], 'name': row[1], 'series': row[2], 'base_rarity': row[3]})
return ret
def handLimit(userid):
with db.cursor() as cur:
cur.execute("SELECT 7 + paidHandUpgrades + freeUpgrades FROM users WHERE id = %s", [userid])
res = cur.fetchone()
limit = int(res[0])
return limit
def paidHandUpgrades(userid):
cur = db.cursor()
cur.execute("SELECT paidHandUpgrades FROM users WHERE id = %s", [userid])
res = cur.fetchone()
limit = int(res[0])
cur.close()
return limit
def currentCards(userid, verbose=False):
cur = db.cursor()
cur.execute(
"SELECT (SELECT COUNT(*) FROM cards WHERE userid = %s AND boosterid IS NULL AND rarity < %s), (SELECT COUNT(*) FROM bounties WHERE userid = %s AND status = 'open')",
[userid, int(config["numNormalRarities"]), userid])
result = cur.fetchone()
cur.close()
if verbose:
return {"hand": result[0], "bounties": result[1], "total": result[0] + result[1]}
else:
return result[0] + result[1]
def upgradeHand(userid, gifted=False):
cur = db.cursor()
cur.execute(
"UPDATE users SET paidHandUpgrades = paidHandUpgrades + %s, freeUpgrades = freeUpgrades + %s WHERE id = %s",
[0 if gifted else 1, 1 if gifted else 0, userid])
cur.close()
def disenchant(bot, cardid):
# return amount of points gained
with db.cursor() as cur:
card = getCard(cardid)
deValue = int(config["rarity" + str(card["rarity"]) + "Value"])
updateCard(cardid, {"userid": None, "boosterid": None})
# bounty to fill?
cur.execute(
"SELECT bounties.id, bounties.userid, users.name, bounties.amount, waifus.name, waifus.base_rarity, waifus.image FROM bounties JOIN users ON bounties.userid = users.id JOIN waifus ON bounties.waifuid = waifus.id WHERE bounties.waifuid = %s AND bounties.status = 'open' ORDER BY bounties.amount DESC LIMIT 1",
[card["waifuid"]])
order = cur.fetchone()
if order is not None:
# fill their order instead of actually disenchanting
filledCardID = addCard(order[1], card['waifuid'], "bounty")
# when we spawn a bounty card, carry over the old original owner id
updateCard(filledCardID, {"originalOwner": card['originalOwner']})
bot.message('#%s' % order[2],
"Your bounty for [%d] %s for %d points has been filled and they have been added to your hand." % (
card['waifuid'], order[4], order[3]), True)
cur.execute("UPDATE bounties SET status = 'filled', oldCard = %s, newCard = %s, updated = %s WHERE id = %s",
[cardid, filledCardID, current_milli_time(), order[0]])
sendPushNotification([order[1]], {'type': 'bountyFilled',
'image': card['customImage'] if card['customImage'] else order[6],
'message': "Your bounty for [%d] %s for %d points has been filled and they have been added to your hand." % (
card['waifuid'], order[4], order[3]),
'openurl': config['siteHost'] + '/hand?user=' + order[2]})
# alert people with lower bounties but above the cap?
base_value = int(config["rarity" + str(order[5]) + "Value"])
min_bounty = int(config["rarity" + str(order[5]) + "MinBounty"])
rarity_cap = int(config["rarity" + str(order[5]) + "MaxBounty"])
cur.execute(
"SELECT users.name, users.id FROM bounties JOIN users ON bounties.userid = users.id WHERE bounties.waifuid = %s AND bounties.status = 'open' AND bounties.amount > %s",
[card['waifuid'], rarity_cap])
otherUsers = []
for userrow in cur.fetchall():
bot.message('#%s' % userrow[0],
"A higher bounty for [%d] %s than yours was filled, so you can now cancel yours and get full points back provided you don't change it." % (
card['waifuid'], order[4]), True)
otherUsers.append(userrow[1])
if otherUsers:
sendPushNotification(otherUsers, {'type': 'bountyHigherFilled',
'image': card['customImage'] if card['customImage'] else order[6],
'message': "A higher bounty for [%d] %s than yours was filled, so you can now cancel yours and get full points back provided you don't change it." % (
card['waifuid'], order[4]),
'openurl': 'https://twitch.tv/nepnepbot'})
# give the disenchanter appropriate profit
# everything up to the min bounty, 1/2 of any amount between the min and max bounties, 1/4 of anything above the max bounty.
deValue += (min_bounty - base_value) + max(min(order[3] - min_bounty, rarity_cap - min_bounty) // 2, 0) + max((order[3] - rarity_cap) // 4, 0)
return deValue
def sendPushNotification(ids, data):
pushHeaders = {'Authorization': 'Basic ' + base64.b64encode(bytes('internal:' + config['adminPass'], 'utf-8')).decode('utf-8')}
r = requests.post(config['siteHost'] + '/sendpush', headers=pushHeaders, json={'ids': ids, 'data': data})
try:
res = r.json()
except:
logger.warning('Error during request decoding')
logger.warning(str(r.status_code))
logger.warning(r.text)
def setFavourite(userid, waifu):
with db.cursor() as cur:
cur.execute("UPDATE users SET favourite=%s WHERE id = %s", [waifu, userid])
def setDescription(userid, newDesc):
with db.cursor() as cur:
cur.execute("UPDATE users SET profileDescription=%s WHERE id = %s", [newDesc, userid])
def checkFavouriteValidity(userid):
with db.cursor() as cur:
cur.execute("SELECT favourite FROM users WHERE id = %s", [userid])
favourite = getWaifuById(cur.fetchone()[0])
valid = True
if favourite["can_favourite"] == 0:
valid = False
elif favourite["base_rarity"] >= int(config["numNormalRarities"]):
# must be owned
cur.execute("SELECT COUNT(*) FROM cards WHERE waifuid = %s AND boosterid IS NULL AND userid = %s", [favourite["id"], userid])
valid = cur.fetchone()[0] > 0
if not valid:
# reset favourite
cur.execute("UPDATE users SET favourite = 1 WHERE id = %s", [userid])
def getBadgeByID(id):
logger.debug("Getting badge for id %s", id)
try:
id = int(id)
if id < 1 or id > maxBadgeID():
logger.debug("ID was smaller than 1 or bigger than max.")
return None
except ValueError:
logger.debug("ValueError, not an int")
return None
cur = db.cursor()
cur.execute("SELECT id, name, description, image FROM badges WHERE id=%s",
[id])
row = cur.fetchone()
ret = {"id": row[0], "name": row[1], "image": row[3], "description": row[2]}
cur.close()
logger.debug("Fetched Badge from id: %s", ret)
return ret
def addBadge(name, description, image):
"""Adds a new Badge to the database"""
with db.cursor() as cur:
cur.execute("INSERT INTO badges(name, description, image) VALUES(%s, %s, %s)", [name, description, image])
return cur.lastrowid
def giveBadge(userid, badge):
"""Gives a user a badge"""
badgeObj = getBadgeByID(badge)
if badgeObj is None:
return False
else:
try:
with db.cursor() as cur:
cur.execute("INSERT INTO has_badges(userID, badgeID) VALUES(%s, %s)", [userid, badge])
except:
logger.debug("Had an error.")
return False
return True
def getHoraro():
r = requests.get(
"https://horaro.org/-/api/v1/schedules/{horaroid}/ticker".format(horaroid=config["horaroID"]))
try:
j = r.json()
# ("got horaro ticker: " + str(j))
return j
except Exception:
logger.error("Horaro Error:")
logger.error(str(r.status_code))
logger.error(r.text)
def getRawRunner(runner):
if '[' not in runner:
return runner
return runner[runner.index('[') + 1 : runner.index(']')]
def getGameID(gameName):
# Try exact matches first, then fall back on search endpoint
r = requests.get("https://api.twitch.tv/helix/games", params={"name":gameName})
try:
j = r.json()
data = j["data"]
return data[0]["id"]
except Exception:
# Not found, checking search endpoint...
r = requests.get("https://api.twitch.tv/helix/search/categories", params={"query": gameName})
try:
j = r.json()
data = j["data"]
return data[0]["id"]
except Exception:
return 0
return 0
def updateBoth(game, title):
if not booleanConfig("marathonBotFunctions"):
return
myheaders = headers.copy()
myheaders["Authorization"] = "Bearer " + config["marathonOAuth"].replace("oauth:", "")
myheaders["Content-Type"] = "application/json"
gameID = getGameID(game)
body = {"title": str(title), "game_id": gameID}
logger.debug(str(body))
r = requests.patch("https://api.twitch.tv/helix/channels?broadcaster_id="+config["marathonChannelID"], headers=myheaders, json=body)
try:
j = r.json()
logger.debug("Response from twitch: "+str(j))
# print("tried to update channel title, response: " + str(j))
except Exception:
logger.error(str(r.status_code))
logger.error(r.text)
def updateTitle(title):
if not booleanConfig("marathonBotFunctions"):
return
myheaders = headers.copy()
myheaders["Authorization"] = "Bearer " + config["marathonOAuth"].replace("oauth:", "")
myheaders["Content-Type"] = "application/json"
body = {"title": str(title)}
r = requests.patch("https://api.twitch.tv/helix/channels?broadcaster_id="+config["marathonChannelID"], headers=myheaders, json=body)
try:
j = r.json()
except Exception:
logger.error(str(r.status_code))
logger.error(r.text)
def updateGame(game):
if not booleanConfig("marathonBotFunctions"):
return
myheaders = headers.copy()
myheaders["Authorization"] = "Bearer " + config["marathonOAuth"].replace("oauth:", "")
myheaders["Content-Type"] = "application/json"
gameID = getGameID(game)
body = {"game_id": gameID}
r = requests.patch("https://api.twitch.tv/helix/channels?broadcaster_id="+config["marathonChannelID"], headers=myheaders, json=body)
try:
j = r.json()
except Exception:
logger.error(str(r.status_code))
logger.error(r.text)
def sendStreamlabsAlert(channel, data):
if '#' in channel:
channel = channel[1:]
with busyLock:
with db.cursor() as cur:
cur.execute("SELECT alertkey FROM channels WHERE name = %s LIMIT 1", [channel])
tokenRow = cur.fetchone()
if tokenRow is not None and tokenRow[0] is not None:
data['access_token'] = tokenRow[0]
with streamlabsLock:
try:
req = requests.post(streamlabsalerturl, headers=alertheaders, json=data)
if req.status_code != 200:
logger.debug("response for streamlabs alert: %s; %s", str(req.status_code), str(req.text))
except Exception:
logger.error("Tried to send a Streamlabs alert to %s, but failed." % channel)
logger.error("Error: %s", str(sys.exc_info()))
def sendDiscordAlert(data):
with discordLock:
for url in discordhooks:
req2 = requests.post(
url,
json=data)
while req2.status_code == 429:
time.sleep((int(req2.headers["Retry-After"]) / 1000) + 1)
req2 = requests.post(
url,
json=data)
def sendAdminDiscordAlert(data):
with discordLock:
req2 = requests.post(config["adminDiscordHook"], json=data)
while req2.status_code == 429:
time.sleep((int(req2.headers["Retry-After"]) / 1000) + 1)
req2 = requests.post(
config["adminDiscordHook"],
json=data)
def sendDrawAlert(channel, waifu, user, discord=True):
logger.info("Alerting for waifu %s", str(waifu))
with busyLock:
cur = db.cursor()
# check for first time drop
first_time = "pulls" in waifu and waifu['pulls'] == 0
message = "*{user}* drew {first_time}[*{rarity}*] {name}!".format(user=str(user),
rarity=str(config["rarity" + str(
waifu["base_rarity"]) + "Name"]),
name=str(waifu["name"]),
first_time=(
"the first ever " if first_time else ""))
chanOwner = str(channel).replace("#", "")
cur.execute("SELECT config, val FROM alertConfig WHERE channelName = %s", [chanOwner])
rows = cur.fetchall()
colorKey = "rarity" + str(waifu["base_rarity"]) + "EmbedColor"
colorInt = int(config[colorKey])
# Convert RGB int to RGB values
blue = colorInt & 255
green = (colorInt >> 8) & 255
red = (colorInt >> 16) & 255
alertconfig = {}
for row in rows:
alertconfig[row[0]] = row[1]
keys = alertconfig.keys()
alertChannel = "donation" if "alertChannel" not in keys else alertconfig["alertChannel"]
defaultSound = config["alertSound"] if "defaultSound" not in keys else alertconfig["defaultSound"]
alertSound = defaultSound if str("rarity" + str(waifu["base_rarity"]) + "Sound") not in keys else alertconfig[
str("rarity" + str(waifu["base_rarity"]) + "Sound")]
defaultLength = config["alertDuration"] if "defaultLength" not in keys else alertconfig["defaultLength"]
alertLength = defaultLength if str("rarity" + str(waifu["base_rarity"]) + "Length") not in keys else \
alertconfig[str("rarity" + str(waifu["base_rarity"]) + "Length")]
alertColor = "default" if "color" not in keys else alertconfig["color"]
if "id" in waifu:
cur.execute("SELECT sound, length FROM waifuAlerts WHERE waifuid=%s", [waifu["id"]])
rows = cur.fetchall()
if len(rows) == 1:
alertLength = int(rows[0][1])
alertSound = str(rows[0][0])
alertbody = {"type": alertChannel, "image_href": waifu["image"],
"sound_href": alertSound, "duration": int(alertLength), "message": message}
if alertColor == "rarity":
alertbody["special_text_color"] = "rgb({r}, {g}, {b})".format(r=str(red), g=str(green), b=str(blue))
cur.close()
threading.Thread(target=sendStreamlabsAlert, args=(channel, alertbody)).start()
if discord:
# check for first time drop
rarityName = str(config["rarity" + str(waifu["base_rarity"]) + "Name"])
discordbody = {"username": "Waifu TCG", "embeds": [
{
"title": "A{n} {rarity} waifu has been dropped{first_time}!".format(
rarity=rarityName,
first_time=(" for the first time" if first_time else ""),
n='n' if rarityName[0] in ('a', 'e', 'i', 'o', 'u') else '')
},
{
"type": "rich",
"title": "{user} dropped [{wid}] {name}!".format(user=str(user), wid=str(waifu["id"]),
name=str(waifu["name"])),
"url": "https://twitch.tv/{name}".format(name=str(channel).replace("#", "").lower()),
"footer": {
"text": "Waifu TCG by Marenthyu"
},
"image": {
"url": str(waifu["image"])
},
"provider": {
"name": "Marenthyu",
"url": "https://marenthyu.de"
}
}
]}
if colorKey in config:
discordbody["embeds"][0]["color"] = int(config[colorKey])
discordbody["embeds"][1]["color"] = int(config[colorKey])
threading.Thread(target=sendDiscordAlert, args=(discordbody,)).start()
def sendDisenchantAlert(channel, waifu, user):
# no streamlabs alert for now
# todo maybe make a b&w copy of the waifu image
discordbody = {"username": "Waifu TCG", "embeds": [
{
"title": "A {rarity} waifu has been disenchanted!".format(
rarity=str(config["rarity" + str(waifu["base_rarity"]) + "Name"]))
},
{
"type": "rich",
"title": "[{wid}] {name} has been disenchanted! Press F to pay respects.".format(name=str(waifu["name"]),
wid=str(waifu["id"])),
"footer": {
"text": "Waifu TCG by Marenthyu"
},
"image": {
"url": str(waifu["image"])
},
"provider": {
"name": "Marenthyu",
"url": "https://marenthyu.de"
}
}
]}
colorKey = "rarity" + str(waifu["base_rarity"]) + "EmbedColor"
if colorKey in config:
discordbody["embeds"][0]["color"] = int(config[colorKey])
discordbody["embeds"][1]["color"] = int(config[colorKey])
threading.Thread(target=sendDiscordAlert, args=(discordbody,)).start()
def sendPromotionAlert(userid, waifuid, new_rarity):
with busyLock:
# check for duplicate alert and don't send it
# UNLESS this is a promotion to MAX rarity
if new_rarity != int(config["numNormalRarities"]) - 1:
with db.cursor() as cur:
cur.execute(
"SELECT COUNT(*) FROM promotion_alerts_sent WHERE userid = %s AND waifuid = %s AND rarity >= %s",
[userid, waifuid, new_rarity])
result = cur.fetchone()[0]
if result > 0:
return
# get data necessary for the alert and note that we sent it
# TODO maybe use display name instead
waifu = getWaifuById(waifuid)
with db.cursor() as cur:
cur.execute("SELECT name FROM users WHERE id = %s", [userid])
username = cur.fetchone()[0]
cur.execute("REPLACE INTO promotion_alerts_sent (userid, waifuid, rarity) VALUES(%s, %s, %s)",
[userid, waifuid, new_rarity])
# compile alert
discordbody = {"username": "Waifu TCG", "embeds": [
{
"title": "A waifu has been promoted!",
"color": int(config["rarity%dEmbedColor" % new_rarity])
},
{
"type": "rich",
"title": "{user} promoted [{wid}] {name} to {rarity} rarity!".format(user=username, name=waifu["name"],
wid=str(waifu["id"]),
rarity=config[
"rarity%dName" % new_rarity]),
"color": int(config["rarity%dEmbedColor" % new_rarity]),
"footer": {
"text": "Waifu TCG by Marenthyu"
},
"image": {
"url": waifu["image"]
},
"provider": {
"name": "Marenthyu",
"url": "https://marenthyu.de"
}
}
]}
threading.Thread(target=sendDiscordAlert, args=(discordbody,)).start()
def naturalJoinNames(names):
if len(names) == 1:
return names[0]
return ", ".join(names[:-1]) + " and " + names[-1]
def getWaifuRepresentationString(waifuid, baserarity=None, cardrarity=None, waifuname=None):
if baserarity == None or cardrarity == None or waifuname == None:
waifuData = getWaifuById(waifuid)
if baserarity == None:
baserarity = waifuData['base_rarity']
if cardrarity == None:
cardrarity = baserarity
if waifuname == None:
waifuname = waifuData['name']
promoteDiff = cardrarity - baserarity
promoteStars = (" (" + ("★" * (promoteDiff)) + ")") if promoteDiff > 0 else ""
retStr = "[%d][%s%s] %s" % (
waifuid, config["rarity" + str(cardrarity) + "Name"], promoteStars, waifuname)
return retStr
def sendSetAlert(channel, user, name, waifus, reward, firstTime, discord=True):
logger.info("Alerting for set claim %s", name)
with busyLock:
with db.cursor() as cur:
chanOwner = str(channel).replace("#", "")
cur.execute("SELECT config, val FROM alertConfig WHERE channelName = %s", [chanOwner])
rows = cur.fetchall()
alertconfig = {row[0]: row[1] for row in rows}
alertChannel = "donation" if "alertChannel" not in alertconfig else alertconfig["alertChannel"]
defaultSound = config["alertSound"] if "defaultSound" not in alertconfig else alertconfig["defaultSound"]
alertSound = defaultSound if "setClaimSound" not in alertconfig else alertconfig["setClaimSound"]
defaultLength = config["alertDuration"] if "defaultLength" not in alertconfig else alertconfig["defaultLength"]
alertLength = defaultLength if "setClaimLength" not in alertconfig else alertconfig["setClaimLength"]
message = "{user} claimed the set {name}!".format(user=user, name=name)
alertbody = {"type": alertChannel, "sound_href": alertSound, "duration": int(alertLength), "message": message}
threading.Thread(target=sendStreamlabsAlert, args=(channel, alertbody)).start()
discordbody = {"username": "Waifu TCG", "embeds": [
{
"title": "A set has been completed%s!" % (" for the first time" if firstTime else ""),
"color": int(config["rarity" + str(int(config["numNormalRarities"]) - 1) + "EmbedColor"])
},
{
"type": "rich",
"title": "{user} completed the set {name}!".format(user=str(user), name=name),
"description": "They gathered {waifus} and received {reward} as their reward.".format(waifus=naturalJoinNames(waifus), reward=reward),
"url": "https://twitch.tv/{name}".format(name=str(channel).replace("#", "").lower()),
"color": int(config["rarity" + str(int(config["numNormalRarities"]) - 1) + "EmbedColor"]),
"footer": {
"text": "Waifu TCG by Marenthyu"
},
"provider": {
"name": "Marenthyu",
"url": "https://marenthyu.de"
}
}
]}
if discord:
threading.Thread(target=sendDiscordAlert, args=(discordbody,)).start()
def followsme(userid):
try:
r = requests.get(
"https://api.twitch.tv/helix/channels/followers?user_id={twitchid}&broadcaster_id={myid}".format(twitchid=str(userid),
myid=str(
config["twitchid"])),
headers={"Authorization": "Bearer %s" % config["oauth"].replace("oauth:", ""),
"Client-ID": config["clientID"]})
j = r.json()
for element in j["data"]:
if element["user_id"] == str(userid):
return True
return False
except Exception:
return False
def getWaifuById(id):
try:
id = int(id)
if id < 1:
return None
except ValueError:
return None
with db.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute("SELECT id, name, image, base_rarity, series, can_lookup, pulls, last_pull, can_favourite, can_purchase, is_event FROM waifus WHERE id=%s", [id])
return cur.fetchone()
def getWaifuOwners(id, rarity):
with db.cursor() as cur:
baseRarityName = config["rarity%dName" % rarity]
godRarity = int(config["numNormalRarities"]) - 1
cur.execute(
"SELECT users.name, c1.rarity, IF(c1.boosterid IS NOT NULL, 1, 0), IF(c1.rarity = %s AND NOT EXISTS(SELECT id FROM cards c2 WHERE c2.userid IS NOT NULL AND c2.rarity = %s AND c2.waifuid = c1.waifuid AND (c2.created < c1.created OR (c2.created=c1.created AND c2.id < c1.id))), 1, 0) AS firstGod FROM cards c1 JOIN users ON c1.userid = users.id WHERE c1.waifuid = %s AND c1.userid IS NOT NULL ORDER BY firstGod DESC, c1.rarity DESC, c1.created ASC, users.name ASC",
[godRarity, godRarity, id])
allOwners = cur.fetchall()
# compile per-owner data grouped into not in booster / in booster
ownerDescriptions = [[], []]
for i in range(2):
ownerData = OrderedDict()
ownedByOwner = {}
for row in allOwners:
if row[2] != i:
continue
if row[0] not in ownerData:
ownerData[row[0]] = OrderedDict()
ownedByOwner[row[0]] = 0
rarityName = ("α" if row[3] else "") + config["rarity%dName" % row[1]]
if rarityName not in ownerData[row[0]]:
ownerData[row[0]][rarityName] = 0
ownerData[row[0]][rarityName] += 1
ownedByOwner[row[0]] += 1
for owner in ownerData:
if len(ownerData[owner]) != 1 or baseRarityName not in ownerData[owner] or ownedByOwner[owner] > 1:
# verbose
ownerDescriptions[i].append(owner + " (" + ", ".join([("%d %s" % (ownerData[owner][k], k) if ownerData[owner][k] > 1 else k) for k in ownerData[owner]]) + ")")
else:
ownerDescriptions[i].append(owner)
return ownerDescriptions
def hasPoints(userid, amount):
cur = db.cursor()
cur.execute("SELECT points FROM users WHERE id = %s", [userid])
ret = int(cur.fetchone()[0]) >= int(amount)
cur.close()
return ret
def addPoints(userid, amount):
cur = db.cursor()
cur.execute("UPDATE users SET points = points + %s WHERE id = %s", [amount, userid])
cur.close()
def getIDFromName(username):