forked from bbedward/graham_discord_bot
-
Notifications
You must be signed in to change notification settings - Fork 5
/
db.py
executable file
·813 lines (726 loc) · 26.2 KB
/
db.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
import re
import datetime
import util
import settings
import random
import secrets
from peewee import *
from playhouse.sqliteq import SqliteQueueDatabase
# (Seconds) how long a user must wait in between messaging the bot
LAST_MSG_TIME = 1
# How many messages consider a user rain eligible
LAST_MSG_RAIN_COUNT = 5
# (Seconds) How spaced out the messages must be
LAST_MSG_RAIN_DELTA = 60
# How many words messages must contain
LAST_MSG_RAIN_WORDS = 3
# (Seconds) how long user must wait between tiprandom
TIP_RANDOM_WAIT=10
# (Seconds) how long user must wait between tipfavorites
TIP_FAVORITES_WAIT=150
db = SqliteQueueDatabase('discord.db')
logger = util.get_logger("db")
### User Stuff
def get_user_by_id(user_id, user_name=None):
try:
user = User.get(user_id=str(user_id))
if user_name is not None and user_name != user.user_name:
User.update(user_name=user_name).where(User.id == user.id).execute()
user.user_name = user_name
return user
except User.DoesNotExist:
# logger.debug('user %s does not exist !', user_id)
return None
def get_user_by_wallet_address(address):
try:
user = User.get(wallet_address=address)
return user
except User.DoesNotExist:
# logger.debug('wallet %s does not exist !', address)
return None
def user_exists(user_id):
return User.select().where(User.user_id == user_id).count() > 0
def get_active_users(since_minutes):
since_ts = datetime.datetime.now() - datetime.timedelta(minutes=since_minutes)
users = User.select().where(User.last_msg > since_ts).order_by(User.user_id)
return_ids = []
for user in users:
if user.last_msg_count >= LAST_MSG_RAIN_COUNT:
if is_banned(user.user_id):
continue
return_ids.append(user.user_id)
return return_ids
def get_address(user_id):
logger.info('getting wallet address for user %d ...', user_id)
user = get_user_by_id(user_id)
if user is None:
return None
else:
return user.wallet_address
def get_top_users(count):
users = User.select().where((User.tipped_amount > 0) & (User.stats_ban == False)).order_by(User.tipped_amount.desc()).limit(count)
return_data = []
for idx, user in enumerate(users):
return_data.append({'index': idx + 1, 'name': user.user_name, 'amount': user.tipped_amount})
return return_data
def get_giveaway_winners(count):
winners = Giveaway.select().where((Giveaway.active == False) & (Giveaway.winner_id.is_null(False))).order_by(Giveaway.end_time.desc()).limit(count)
return_data = []
for idx, winner in enumerate(winners):
user = get_user_by_id(winner.winner_id)
return_data.append({'index': idx + 1, 'name': user.user_name, 'amount': winner.amount + winner.tip_amount})
return return_data
def get_tip_stats(user_id):
user_id = str(user_id)
user = get_user_by_id(user_id)
if user is None:
return None
rank = User.select().where((User.tipped_amount > user.tipped_amount) & (User.stats_ban == False)).count() + 1
if not user.stats_ban:
tipped_amount = user.tipped_amount
tip_count = user.tip_count
top_tip = user.top_tip
else:
tipped_amount = 0
tip_count = 0
top_tip = 0
rank = -1
if tip_count == 0:
average = 0
else:
average = tipped_amount / tip_count
return {'rank':rank, 'total':tipped_amount, 'average':average,'top':float(top_tip)}
# Update tip stats
def update_tip_stats(user, tip, rain=False, giveaway=False):
tip = int(tip)
(User.update(
tipped_amount=(User.tipped_amount + (tip)),
tip_count = User.tip_count + 1
).where(User.id == user.id)
).execute()
# Update all time tip if necessary
if tip > int(float(user.top_tip)):
(User.update(
top_tip = tip,
top_tip_ts = datetime.datetime.now()
).where(User.id == user.id)
).execute()
# Update monthly tip if necessary
if user.top_tip_month_ts.month != datetime.datetime.now().month or tip > int(float(user.top_tip_month)):
(User.update(
top_tip_month = tip,
top_tip_month_ts = datetime.datetime.now()
).where(User.id == user.id)
).execute()
# Update 24H tip if necessary
delta = datetime.datetime.now() - user.top_tip_day_ts
if delta.total_seconds() > 86400 or tip > int(float(user.top_tip_day)):
(User.update(
top_tip_day = tip,
top_tip_day_ts = datetime.datetime.now()
).where(User.id == user.id)
).execute()
# Update rain or giveaway stats
if rain:
(User.update(
rain_amount = User.rain_amount + (tip)
)
.where(User.id == user.id)
).execute()
elif giveaway:
(User.update(
giveaway_amount = User.giveaway_amount + (tip)
)
.where(User.id == user.id)
).execute()
def update_tip_total(user_id, new_total):
user_id = str(user_id)
User.update(tipped_amount = new_total).where(User.user_id == user_id).execute()
return
def update_tip_count(user_id, new_count):
user_id = str(user_id)
User.update(tip_count = new_count).where(User.user_id == user_id).execute()
return
def update_pending(user_id, send=0, receive=0):
user_id=str(user_id)
return (User.update(
pending_send = (User.pending_send + send),
pending_receive = (User.pending_receive + receive)
).where(User.user_id == user_id)
).execute()
def create_user(user_id, user_name, wallet_address):
user_id=str(user_id)
user = User(user_id=user_id,
user_name=user_name,
wallet_address=wallet_address,
)
user.save()
return user
### Transaction Stuff
def create_transaction(src_usr, uuid, to_addr, amt, target_id=None, giveaway_id=0):
# Increment amount of giveaway TX if user has already donated to giveaway
if giveaway_id != 0:
try:
giveawayTx = (Transaction.select()
.where(
(Transaction.source_address == src_usr.wallet_address) &
(Transaction.giveawayid == giveaway_id)
)
).get()
update = (Transaction.update(amount = Transaction.amount.cast('integer') + amt)
.where(Transaction.id == giveawayTx.id)
).execute()
if update > 0:
update_pending(src_usr.user_id, send=amt)
return
except Transaction.DoesNotExist:
pass
tx = Transaction(uid=uuid,
source_address=src_usr.wallet_address,
to_address=to_addr,
amount=amt,
giveawayid=giveaway_id
)
tx.save()
update_pending(src_usr.user_id, send=amt)
if target_id is not None:
update_pending(target_id, receive=amt)
return tx
def update_last_withdraw(user_id):
user_id = str(user_id)
User.update(last_withdraw=datetime.datetime.now()).where(User.user_id == user_id).execute()
def get_last_withdraw_delta(user_id):
user_id = str(user_id)
try:
user = User.select(User.last_withdraw).where(User.user_id == user_id).get()
delta = (datetime.datetime.now() - user.last_withdraw).total_seconds()
return delta
except User.DoesNotExist:
return None
def get_unprocessed_transactions():
# We don't simply return the txs list cuz that causes issues with database locks in the thread
txs = Transaction.select().where((Transaction.processed == False) & (Transaction.giveawayid == 0)).order_by(Transaction.created)
return_data = []
for tx in txs:
return_data.append({'uid':tx.uid,'source_address':tx.source_address,'to_address':tx.to_address,'amount':tx.amount,'attempts':tx.attempts})
return return_data
def process_giveaway_transactions(giveaway_id, winner_user_id):
txs = Transaction.select().where(Transaction.giveawayid == giveaway_id)
winner = get_user_by_id(winner_user_id);
pending_receive = 0
for tx in txs:
pending_receive += int(tx.amount)
update_pending(winner_user_id, receive=pending_receive)
(Transaction.update(
to_address = winner.wallet_address,
giveawayid = 0
).where(
(Transaction.giveawayid == giveaway_id)
)).execute()
# Start Giveaway
def start_giveaway(user_id, user_name, amount, end_time, channel, entry_fee = 0):
user_id=str(user_id)
channel=str(channel)
giveaway = Giveaway(started_by=user_id,
started_by_name=user_name,
active=True,
amount = amount,
tip_amount = 0,
end_time=end_time,
channel_id = channel,
winner_id = None,
entry_fee = entry_fee
)
giveaway.save()
# Delete contestants not meeting fee criteria
deleted = []
if entry_fee > 0:
entries = Contestant.select()
for c in entries:
donated = get_tipgiveaway_contributions(c.user_id)
if entry_fee > donated:
c.delete_instance()
deleted.append(c.user_id)
tip_amt = update_giveaway_transactions(giveaway.id)
giveaway.tip_amount = tip_amt
giveaway.save()
return (giveaway, deleted)
def get_giveaway():
try:
giveaway = Giveaway.get(active=True)
return giveaway
except:
return None
def update_giveaway_transactions(giveawayid):
tip_sum = 0
txs = Transaction.select().where(Transaction.giveawayid == -1)
for tx in txs:
tip_sum += int(tx.amount)
(Transaction.update(
giveawayid = giveawayid
).where(
(Transaction.giveawayid == -1)
)).execute()
return float(tip_sum)
def add_tip_to_giveaway(amount):
giveawayupdt = (Giveaway
.update(
tip_amount = (Giveaway.tip_amount + amount)
).where(Giveaway.active == True)
).execute()
def get_tipgiveaway_sum():
tip_sum = 0
txs = Transaction.select().where(Transaction.giveawayid == -1)
for tx in txs:
tip_sum += int(tx.amount)
return tip_sum
# Get tipgiveaway contributions
def get_tipgiveaway_contributions(user_id, giveawayid=-1):
tip_sum = 0
user = get_user_by_id(user_id)
txs = Transaction.select().where((Transaction.giveawayid == giveawayid) & (Transaction.source_address == user.wallet_address))
for tx in txs:
tip_sum += int(tx.amount)
return tip_sum
def is_banned(user_id):
user_id=str(user_id)
banned = BannedUser.select().where(BannedUser.user_id == user_id).count()
return banned > 0
def ban_user(user_id):
user_id = str(user_id)
already_banned = is_banned(user_id)
if already_banned > 0:
return False
ban = BannedUser(user_id=user_id)
ban.save()
return True
def statsban_user(user_id):
user_id = str(user_id)
banned = User.update(stats_ban = True).where(User.user_id == user_id).execute()
return banned > 0
def unban_user(user_id):
user_id = str(user_id)
deleted = BannedUser.delete().where(BannedUser.user_id == user_id).execute()
return deleted > 0
def statsunban_user(user_id):
user_id = str(user_id)
unbanned = User.update(stats_ban = False).where(User.user_id == user_id).execute()
return unbanned > 0
def get_banned():
banned = BannedUser.select(BannedUser.user_id)
users = User.select(User.user_name).where(User.user_id.in_(banned))
if users.count() == 0:
return "```Nobody Banned```"
ret = "```"
for idx,user in enumerate(users):
ret += "{0}: {1}\n".format(idx+1,user.user_name)
ret += "```"
return ret
def get_statsbanned():
statsbanned = User.select().where(User.stats_ban == True)
if statsbanned.count() == 0:
return "```No stats bans```"
ret = "```"
for idx,user in enumerate(statsbanned):
ret += "{0}: {1}\n".format(idx+1,user.user_name)
ret += "```"
return ret
def is_frozen(user_id):
return FrozenUser.select().where(FrozenUser.user_id == user_id).count() > 0
def freeze(user):
if not is_frozen(user.id):
fu = FrozenUser(user_id=user.id, user_name=user.name)
saved = fu.save()
return saved > 0
return False
def unfreeze(user_id):
if not is_frozen(user_id):
return False
return FrozenUser.delete().where(FrozenUser.user_id==user_id).execute() > 0
def frozen():
frozen = FrozenUser.select()
if frozen.count() == 0:
return "```Nobody Frozen```"
ret = "```"
for idx, fu in enumerate(frozen):
ret += "{0}: {1}\n".format(idx+1, fu.user_name)
ret += "```"
return ret
# Returns winning user
def finish_giveaway():
contestants = Contestant.select(Contestant.user_id).order_by(Contestant.user_id)
contestant_ids = []
for c in contestants:
contestant_ids.append(c.user_id)
sysrand = random.SystemRandom()
sysrand.shuffle(contestant_ids)
offset = secrets.randbelow(len(contestant_ids))
winner = get_user_by_id(contestant_ids[offset])
Contestant.delete().execute()
giveaway = Giveaway.get(active=True)
giveaway.active=False
giveaway.winner_id = winner.user_id
giveaway.save()
process_giveaway_transactions(giveaway.id, winner.user_id)
return giveaway
# Returns True is contestant added, False if contestant already exists
def add_contestant(user_id):
user_id=str(user_id)
exists = Contestant.select().where(Contestant.user_id == user_id).count() > 0
if exists:
return False
contestant = Contestant(user_id=user_id,banned=False)
contestant.save()
return True
def get_ticket_status(user_id):
user_id = str(user_id)
try:
giveaway = Giveaway.select().where(Giveaway.active==True).get()
if contestant_exists(user_id):
return "You are already entered into the giveaway!"
fee = giveaway.entry_fee
contributions = get_tipgiveaway_contributions(user_id, giveawayid=giveaway.id)
cost = fee - contributions
return_str = ("You do not have a ticket to the current giveaway!\n" +
"Giveaway fee: {0}\n" +
"Your donations: {1}\n" +
"Your ticket cost: {2}\n\n" +
"You may enter using `{3}ticket {4}`").format(fee, contributions, cost, settings.command_prefix, cost)
return return_str
except Giveaway.DoesNotExist:
contributions = get_tipgiveaway_contributions(user_id)
return "There is no active giveaway.\nSo far you've contributed {0} BANANO towards the next one!".format(contributions)
def contestant_exists(user_id):
user_id = str(user_id)
c = Contestant.select().where(Contestant.user_id == user_id).count()
return c > 0
def is_active_giveaway():
giveaway = Giveaway.select().where(Giveaway.active==True).count()
if giveaway > 0:
return True
return False
# Gets giveaway stats
def get_giveaway_stats():
try:
giveaway = Giveaway.get(active=True)
entries = Contestant.select().count()
return {"amount":giveaway.amount + giveaway.tip_amount, "started_by":giveaway.started_by_name, "entries":entries, "end":giveaway.end_time,"fee":giveaway.entry_fee}
except Giveaway.DoesNotExist:
return None
def inc_tx_attempts(uid):
tx = Transaction.get(uid = uid)
if tx is not None:
tx.attempts += 1
tx.save()
return
def update_top_tips(user_id, month=0,day=0,alltime=0):
return (User.update(top_tip = User.top_tip + alltime,
top_tip_month = User.top_tip_month + month,
top_tip_day = User.top_tip_day + day
).where(User.user_id == user_id)).execute()
def get_top_tips():
dt = datetime.datetime.now()
past_dt = dt - datetime.timedelta(days=1) # Date 24H ago
month_str = dt.strftime("%B")
month_num = "{0:02d}".format(dt.month) # Sqlite uses 2 digit month (with leading 0)
amount = fn.MAX(User.top_tip).alias('amount')
amount_day = fn.MAX(User.top_tip_day).alias('amount')
amount_month = fn.MAX(User.top_tip_month).alias('amount')
top_24h = User.select(amount_day, User.user_name).where((User.top_tip_day_ts > past_dt) & (User.stats_ban == False)).order_by(User.top_tip_day_ts).limit(1)
top_month = User.select(amount_month, User.user_name).where((fn.strftime("%m", User.top_tip_month_ts) == month_num) & (User.stats_ban == False)).order_by(User.top_tip_month_ts).limit(1)
top_at = User.select(amount, User.user_name).where(User.stats_ban == False).order_by(User.top_tip_ts).limit(1)
# Formatted output
user24h = None
monthuser = None
atuser = None
for top in top_24h:
user24h = top.user_name
amount24h = float(top.amount)
for top in top_month:
monthuser = top.user_name
monthamount = float(top.amount)
for top in top_at:
atuser = top.user_name
atamount = float(top.amount)
if user24h is None and monthuser is None and atuser is None:
return "```No Tips Found```"
result = ""
if user24h is not None:
result += "Biggest tip in the last 24 hours:```{0:.2f} BANANO by {1}```".format(amount24h, user24h)
if monthuser is not None:
result += "Biggest tip in {0}:```{1:.2f} BANANO by {2}```".format(month_str, monthamount, monthuser)
if atuser is not None:
result += "Biggest tip of all time:```{0:.2f} BANANO by {1}```".format(atamount, atuser)
return result
# Marks TX as sent
def mark_transaction_sent(uuid, amt, source_id, target_id=None):
tu = (Transaction.update(
sent = True
).where(
(Transaction.uid == uuid) &
(Transaction.sent == False)
)).execute()
if tu > 0:
update_pending(source_id,send=amt)
if target_id is not None:
update_pending(target_id, receive=amt)
# This adds block to our TX
def mark_transaction_processed(uuid, tranid):
(Transaction.update(
tran_id = tranid,
processed = True
).where(Transaction.uid == uuid)).execute()
# Return false if last message was < LAST_MSG_TIME
# If > LAST_MSG_TIME, return True and update the user
# Also return true, if user does not have a tip bot acct yet
def last_msg_check(user_id, content, is_private, citizen):
user = get_user_by_id(user_id)
if user is None:
return True
# Get difference in seconds between now and last msg
since_last_msg_s = (datetime.datetime.now() - user.last_msg).total_seconds()
if since_last_msg_s < LAST_MSG_TIME:
return False
else:
update_last_msg(user, since_last_msg_s, content, is_private, citizen)
return True
def update_last_msg(user, delta, content, is_private, citizen):
content_adjusted = unicode_strip(content)
words = content_adjusted.split(' ')
adjusted_count = 0
prev_len = 0
for word in words:
word = word.strip()
cur_len = len(word)
if cur_len > 0:
if word.startswith(":") and word.endswith(":"):
continue
if prev_len == 0:
prev_len = cur_len
adjusted_count += 1
else:
res = prev_len % cur_len
prev_len = cur_len
if res != 0:
adjusted_count += 1
if adjusted_count >= LAST_MSG_RAIN_WORDS:
break
if (not citizen and delta >= 1800) or (citizen and delta >= 5400):
user.last_msg_count = 0
if adjusted_count >= LAST_MSG_RAIN_WORDS and not is_private and (datetime.datetime.now() - user.last_msg_rain).total_seconds() > LAST_MSG_RAIN_DELTA:
user.last_msg_count += 1
user.last_msg_rain = datetime.datetime.now()
user.last_msg=datetime.datetime.now()
(User.update(
last_msg_count = user.last_msg_count,
last_msg_rain = user.last_msg_rain,
last_msg = user.last_msg
).where(User.user_id == user.user_id)
).execute()
return
def unicode_strip(content):
pattern = re.compile("["
u"\U0001F600-\U0001F64F"
u"\U0001F300-\U0001F5FF"
u"\U0001F1E0-\U0001F1FF"
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
return pattern.sub(r'',content)
def mark_user_active(user):
if user is None:
return
if LAST_MSG_RAIN_COUNT > user.last_msg_count:
(User.update(
last_msg_count = LAST_MSG_RAIN_COUNT
).where(User.user_id == user.user_id)
).execute()
## Favorites
# Return true if favorite added
def add_favorite(user_id, favorite_id):
user_id=str(user_id)
favorite_id=str(favorite_id)
if not user_exists(favorite_id):
return False
count = UserFavorite.select().where(UserFavorite.user_id == user_id).count()
# Identifier makes it easy for user to remove their favorite via DM
if count == 0:
identifier = 1
else:
identifier = count + 1
exists = UserFavorite.select().where((UserFavorite.user_id == user_id) & (UserFavorite.favorite_id == favorite_id)).count()
if exists == 0:
fav = UserFavorite(user_id=user_id,favorite_id=favorite_id,identifier=identifier)
fav.save()
return True
return False
# Returns true if favorite deleted
def remove_favorite(user_id, favorite_id=None,identifier=None):
if favorite_id is None and identifier is None:
return False
user_id=str(user_id)
if favorite_id is not None:
favorite_id = str(favorite_id)
return UserFavorite.delete().where((UserFavorite.user_id == user_id) & (UserFavorite.favorite_id == favorite_id)).execute() > 0
elif identifier is not None:
return UserFavorite.delete().where((UserFavorite.user_id == user_id) & (UserFavorite.identifier == identifier)).execute() > 0
# Returns list of favorites for user ID
def get_favorites_list(user_id):
user_id = str(user_id)
favorites = UserFavorite.select().where(UserFavorite.user_id==user_id).order_by(UserFavorite.identifier)
idx = 1
# Normalize identifiers
for fav in favorites:
fav.identifier = idx
UserFavorite.update(identifier=idx).where((UserFavorite.user_id==user_id) & (UserFavorite.favorite_id == fav.favorite_id)).execute()
idx += 1
return_data = []
for fav in favorites:
return_data.append({'user_id':fav.favorite_id,'id': fav.identifier})
return return_data
# Returns list of muted for user id
def get_muted(user_id):
user_id = str(user_id)
muted = MutedList.select().where(MutedList.user_id==user_id)
return_data = []
for m in muted:
return_data.append({'name':m.muted_name, 'id': m.muted_id})
return return_data
# Return True if muted
def muted(source_user, target_user):
source_user = str(source_user)
target_user = str(target_user)
return MutedList.select().where((MutedList.user_id==source_user) & (MutedList.muted_id==target_user)).count() > 0
# Return false if already muted, True if muted
def mute(source_user, target_user, target_name):
if muted(source_user, target_user):
return False
source_user = str(source_user)
target_user = str(target_user)
mute = MutedList(user_id=source_user,muted_id=target_user,muted_name=target_name)
mute.save()
return True
# Return a number > 0 if user was unmuted
def unmute(source_user, target_user):
source_user = str(source_user)
target_user = str(target_user)
return MutedList.delete().where((MutedList.user_id==source_user) & (MutedList.muted_id==target_user)).execute()
def silenced(user_id):
user_id = str(user_id)
return SilenceList.select().where(SilenceList.user_id == user_id).count() > 0
def silence(user_id, server_id, expiration=None):
user_id = str(user_id)
if silenced(user_id):
return False
s = SilenceList(user_id=user_id, expiration=expiration, server_id=server_id)
s.save()
return True
def unsilence(user_id):
user_id = str(user_id)
if not silenced(user_id):
return False
return SilenceList.delete().where(SilenceList.user_id == user_id).execute() > 0
def get_silenced():
return SilenceList.select()
# Returns seconds user must wait to tiprandom again
def tiprandom_check(user):
delta = (datetime.datetime.now() - user.last_random).total_seconds()
if TIP_RANDOM_WAIT > delta:
return (TIP_RANDOM_WAIT - delta)
else:
User.update(last_random=datetime.datetime.now()).where(User.user_id == user.user_id).execute()
return 0
# Returns seconds user must wait to tipfavorites again
def tipfavorites_check(user):
delta = (datetime.datetime.now() -user.last_favorites).total_seconds()
if TIP_FAVORITES_WAIT > delta:
return (TIP_FAVORITES_WAIT - delta)
else:
User.update(last_favorites=datetime.datetime.now()).where(User.user_id == user.user_id).execute()
return 0
# Base Model
class BaseModel(Model):
class Meta:
database = db
# User table
class User(BaseModel):
user_id = CharField(unique=True)
user_name = CharField()
wallet_address = CharField(unique=True)
tipped_amount = FloatField(default=0.0, constraints=[SQL('DEFAULT 0.0')])
pending_receive = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
pending_send = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
tip_count = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
created = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
last_msg = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
last_msg_rain = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
last_msg_count = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
top_tip = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
top_tip_ts = DateTimeField(default=datetime.datetime.now(),constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
top_tip_month = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
top_tip_month_ts = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
top_tip_day = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
top_tip_day_ts = DateTimeField(default=datetime.datetime.now(),constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
last_withdraw = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
stats_ban = BooleanField(default=False, constraints=[SQL('DEFAULT 0')])
rain_amount = FloatField(default=0.0, constraints=[SQL('DEFAULT 0.0')])
giveaway_amount = FloatField(default=0.0, constraints=[SQL('DEFAULT 0.0')])
last_random = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
last_favorites = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
# Transaction table, keep trac of sends to process
class Transaction(BaseModel):
uid = CharField(unique=True)
source_address = CharField()
to_address = CharField(null = True)
amount = CharField()
sent = BooleanField(default=False, constraints=[SQL('DEFAULT 0')])
processed = BooleanField(default=False, constraints=[SQL('DEFAULT 0')])
created = DateTimeField(default=datetime.datetime.now(), constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
tran_id = CharField(default='', null=True)
attempts = IntegerField(default=0, constraints=[SQL('DEFAULT 0')])
giveawayid = IntegerField(null = True)
# Giveaway table, keep track of current giveaway
class Giveaway(BaseModel):
started_by = CharField() # User ID
started_by_name = CharField() # User Name
active = BooleanField()
amount = FloatField()
tip_amount = FloatField()
end_time = DateTimeField()
channel_id = CharField() # The channel to post the results
winner_id = CharField(null = True)
entry_fee = IntegerField()
# Giveaway Entrants
class Contestant(BaseModel):
user_id = CharField(unique=True)
banned = BooleanField()
# Banned List
class BannedUser(BaseModel):
user_id = CharField()
# Favorites
class UserFavorite(BaseModel):
user_id = CharField()
favorite_id = CharField()
created = DateTimeField(default=datetime.datetime.now(),constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
identifier = IntegerField()
# Muted management
class MutedList(BaseModel):
user_id = CharField()
muted_id = CharField()
muted_name = CharField()
created = DateTimeField(default=datetime.datetime.now(),constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
# Silence list (this is for server-wide silence role)
class SilenceList(BaseModel):
user_id = CharField()
expiration = DateTimeField(default=None,null=True)
server_id = IntegerField()
# Separate table for frozen so we can freeze even users not registered with bot
class FrozenUser(BaseModel):
user_id = IntegerField(unique=True)
user_name = CharField()
created = DateTimeField(default=datetime.datetime.now())
def create_db():
db.connect()
db.create_tables([User, Transaction, Giveaway, Contestant, BannedUser, UserFavorite, MutedList, SilenceList, FrozenUser], safe=True)
logger.debug("DB Connected")
create_db()