hellsbot.py
49.7 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
# -*- coding: utf-8 -*-
import requests
import discord
import random
import datetime
import re
import operator
import pickle
import logging
import traceback
import sys
import wikipedia
from dateutil.parser import parse
from discord.object import Object
from discord.channel import PrivateChannel
from ago import human
import simplejson as json
from collections import defaultdict
from nltk.tag import pos_tag
import wolframalpha
import sqlite3
from blackjack import Blackjack
VERSION = 1.6
conn = sqlite3.connect('db.sqlite3')
member_status = 'members.json'
deliveries_file = 'deliveries.json'
# fortune_file = 'fortunes.json'
# joke_file = 'jokes.json'
games_file = 'games.json'
credentials = 'creds.json'
muted_until = datetime.datetime.now()
client = discord.Client()
wolf = {}
logging.basicConfig(filename='hellsbot.log',level=logging.WARNING)
#####################
## Utility Functions
#####################
def log(message):
logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
def format_exception(e):
exception_list = traceback.format_stack()
exception_list = exception_list[:-2]
exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))
exception_str = "Traceback (most recent call last):\n"
exception_str += "".join(exception_list)
# Removing the last \n
exception_str = exception_str[:-1]
return exception_str
def leaders(xs, top=20):
counts = defaultdict(int)
for x in xs:
counts[x] += 1
return sorted(counts.items(), reverse=True, key=lambda tup: tup[1])[:top]
def byteify(input):
if isinstance(input, dict):
return {byteify(key): byteify(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [byteify(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
def search_youtube(query):
query_string = {"search_query" : query}
r = requests.get("http://www.youtube.com/results", params=query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', r.content)
print("http://www.youtube.com/watch?v=" + search_results[0])
return "http://www.youtube.com/watch?v=" + search_results[0]
def search_google_images(query, animated=False):
headers = {'User-Agent': "Mozilla/5.0 (X11; FreeBSD amd64; rv:12.0) Gecko/20100101 Firefox/12.0"}
query_string = {"safe": "off", "tbm": "isch", "q" : query}
if animated:
query_string = {"safe": "off", "tbm": "isch", "q" : query, 'tbs': 'itp:animated'}
r = requests.get("http://www.google.com/search", params=query_string, headers=headers)
start_idx = r.content.find('imgurl=') + 7
if start_idx > 0:
search_result = r.content[start_idx:r.content.find('&', start_idx)]
if '/revision/' in search_result:
search_result = search_result[:search_result.find('/revision/')]
if '%' in search_result:
search_result = search_result[:search_result.find('%')]
print(search_result)
return search_result
return "boo you fail.."
##################
## Database Calls
##################
# Converts a row into a dictionary
def dict_factory(cursor, row):
if row == None:
return None
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def db_get_credit(member_id):
c = conn.cursor()
credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if credits:
return credits[0]
def db_buy_ticket(member_id, amount):
c = conn.cursor()
credits = c.execute("SELECT credits, tickets FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if not credits:
return False, "Unable to find your account"
if int(credits[0]) - int(100*amount) < 0:
return False, "You do not have enough credits to purchase a ticket. Credits: {} Tickets: {}".format(credits[0], credits[1])
c = conn.cursor()
cost = int(100 * amount)
c.execute("""UPDATE members SET credits = credits - ?, tickets = tickets + ?
WHERE member_id = ?;""", (cost, amount, member_id))
conn.commit()
return True, int(credits[1]) + int(amount)
def db_update_credit(member_id, amount):
c = conn.cursor()
credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
if not credits:
return False, "Unable to find your account"
if int(credits[0]) + int(amount) < 0:
return False, "You do not have enough credits to cover amount requested. Credit: {} Amount Requested: {}".format(credits[0], amount)
if int(credits[0]) < 0:
c.execute("""UPDATE members SET credits = 0
WHERE member_id = ?;""", (amount, member_id))
conn.commit()
c.execute("""UPDATE members SET credits = credits + ?
WHERE member_id = ?;""", (amount, member_id))
conn.commit()
return True, ""
def db_add_minigame(member_id, minigame_name, state):
c = conn.cursor()
db_state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if not db_state:
c.execute("""INSERT INTO minigames(member_id, minigame_name, state)
VALUES(?, ?, ?);""", (member_id, minigame_name, state))
conn.commit()
else:
c.execute("""UPDATE minigames SET state = ?
WHERE member_id = ? AND minigame_name = ?;""", (state, member_id, minigame_name))
conn.commit()
def db_get_minigame_state(member_id, minigame_name):
c = conn.cursor()
state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
if state:
return state[0]
def db_delete_minigame_state(member_id, minigame_name):
c = conn.cursor()
c.execute("DELETE FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name))
conn.commit()
def db_add_message(message, delivery_time, channel, message_from, message_to, user_id):
c = conn.cursor()
c.execute("""INSERT INTO messages(message, delivery_time, channel, message_from, message_to, user_id)
VALUES(?, ?, ?, ?, ?, ?);""", (message, delivery_time, channel, message_from, message_to, user_id))
conn.commit()
def db_delete_sent_message(message_id):
c = conn.cursor()
c.execute("DELETE FROM messages WHERE message_id = ?;", (message_id,))
conn.commit()
def db_get_aliases(member_id):
c = conn.cursor()
aliases = c.execute("SELECT alias_name FROM aliases WHERE member_id = ?;", (member_id,)).fetchall()
if aliases:
alias_list = []
for alias in aliases:
alias_list.append(alias[0])
return alias_list
else:
return None
def db_add_aliases(member_id, alias_name):
c = conn.cursor()
c.execute("INSERT INTO aliases(alias_name, member_id) VALUES (?, ?);", (alias_name, member_id,))
conn.commit()
def db_get_messages():
msg_conn = sqlite3.connect('db.sqlite3')
c = msg_conn.cursor()
messages = c.execute("SELECT * FROM messages WHERE datetime('now') >= datetime( replace(delivery_time, '/', '-'));").fetchall()
if messages:
db_messages = []
for message in messages:
db_messages.append(dict_factory(c, message))
else:
db_messages = None
msg_conn.close()
return db_messages
def db_get_whoplayed(game_name):
c = conn.cursor()
members = c.execute("""SELECT m.member_name, xmg.launch_count
FROM members m
INNER JOIN xmember_games xmg ON
m.member_id = xmg.member_id
INNER JOIN games g ON
g.game_id = xmg.game_id
WHERE g.game_name COLLATE nocase = ?
Order By xmg.launch_count, m.member_name DESC;""", (game_name,)).fetchall()
member_list = {}
for member in members:
member_list[member[0]] = member[1]
#log(member_list)
return sorted(member_list.items(), reverse=True, key=operator.itemgetter(1))
#return sorted(member_list, reverse=True, key=lambda tup: tup[1])
def db_get_games(username):
c = conn.cursor()
games = c.execute("""SELECT g.game_name, xmg.launch_count FROM games g
INNER JOIN xmember_games xmg ON
g.game_id = xmg.game_id
INNER JOIN members m ON
m.member_id = xmg.member_id
WHERE m.member_name COLLATE nocase = ?;""", (username,)).fetchall()
games_list = {}
for game in games:
games_list[game[0]] = game[1]
return games_list
def db_get_games_list(limit):
c = conn.cursor()
games_list = c.execute("""SELECT g.game_name, count(DISTINCT xmg.member_id)
FROM games g
INNER JOIN xmember_games xmg ON
g.game_id = xmg.game_id
Group By xmg.game_id
Order By COUNT(DISTINCT xmg.member_id) DESC
LIMIT ?""", (limit,)).fetchall()
return games_list
def db_add_game(member_id, game_name):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
c = conn.cursor()
games = c.execute("SELECT game_id FROM games WHERE game_name = ?;", (game_name,)).fetchone()
db_game_id = 0
if not games:
log("Adding Game: {}".format(game_name,))
c.execute("INSERT INTO games(game_name) VALUES(?);", (game_name,))
conn.commit()
db_game_id = c.execute("select last_insert_rowid();").fetchone()[0]
else:
db_game_id = games[0]
#log("DB Game ID: {}".format(db_game_id,))
member_games = c.execute("SELECT launch_count FROM xmember_games WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id)).fetchone()
if not member_games:
#log("Inserting Member Games: {}, {}".format(db_game_id, member_id))
c.execute("INSERT INTO xmember_games(game_id, member_id, launch_count) VALUES(?, ?, 1);", (db_game_id, member_id))
conn.commit()
else:
#log("Updating Member Games: {}, {}".format(db_game_id, member_id))
c.execute("UPDATE xmember_games SET launch_count = launch_count + 1 WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id))
conn.commit()
def db_get_all_members():
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
member_conn = sqlite3.connect('db.sqlite3')
c = member_conn.cursor()
results = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game FROM members;").fetchall()
member_conn.close()
members_list = []
for member in results:
members_list.append(dict_factory(c, member))
return members_list
def db_get_member(discord_id=None, username=None):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
member_conn = sqlite3.connect('db.sqlite3')
c = member_conn.cursor()
result = None
if discord_id:
result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game FROM members WHERE discord_id = ?;", (discord_id,)).fetchone()
if username:
result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game FROM members WHERE member_name = ?;", (username,)).fetchone()
member_conn.close()
return dict_factory(c, result)
def db_create_member(member):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
c = conn.cursor()
c.execute("""INSERT INTO members (member_name, discord_id, discord_mention,
is_afk, afk_at, status, prev_status,
status_change_at, current_game)
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);""", (member.name.lower(),
member.id, member.mention(),
0, datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
'online', 'offline',
datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
member.game_id))
conn.commit()
if member.game_id != None:
db_add_game(db_get_member(member.id)['member_id'], member.game_id)
def db_update_member(member, db_member):
# Do a lookup by ID, if it's found but the name doesn't match then add a row to aliases with the previous name and change the member name
db_member_id = db_member['member_id']
db_membername = db_member['member_name']
status = db_member['status']
prev_status = db_member['prev_status']
c = conn.cursor()
if member.name.lower() != db_membername:
log("Member Name changed! {} to {}".format(db_membername, member.name.lower()))
c.execute("UPDATE members SET member_name = ? WHERE discord_id = ?;", (member.name.lower(), member.id,))
conn.commit()
aliases = c.execute("SELECT * FROM aliases WHERE alias_name = ? AND member_id = ?;", (db_membername, db_member_id)).fetchone()
log("Alias list for user: {}".format(aliases))
if aliases == None:
log("creating new alias: {}, {}".format(db_membername, db_member_id))
c.execute("INSERT INTO aliases (alias_name, member_id) VALUES (?, ?);", (db_membername, db_member_id))
conn.commit()
if member.status == 'idle':
afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
is_afk = True
else:
is_afk = False
status_change_at = None
if status != member.status:
prev_status = status
status = member.status
status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
if is_afk:
#log("is afk")
c.execute("""UPDATE members
SET is_afk = ?, afk_at = ?, status = ?,
prev_status = ?, status_change_at = ?
WHERE discord_id = ?;""", (1, afk_at, status, prev_status, status_change_at, member.id))
conn.commit()
else:
#log("is not afk")
c.execute("""UPDATE members
SET is_afk = ?, status = ?,
prev_status = ?, status_change_at = ?
WHERE discord_id = ?;""", (0, status, prev_status, status_change_at, member.id))
conn.commit()
c.execute("UPDATE members SET current_game = ? WHERE discord_id = ?;", (member.game_id, member.id))
conn.commit()
#log("Member: {} \nMember GameID: {} db Game id: {}".format(member, member.game_id, db_member['current_game']))
if member.game_id != None and member.game_id != db_member['current_game']:
db_add_game(db_member['member_id'], member.game_id)
#################
## Client Events
#################
@client.event
def on_socket_raw_send(payload, binary=False):
check_msg_queue()
@client.event
def on_status(member):
try:
db_member = db_get_member(member.id)
#log(db_member)
if not db_member:
log("Creating new member: {}".format(member) )
db_create_member(member)
else:
#log("Updating member: {}".format(member) )
db_update_member(member, db_member)
check_msg_queue()
except Exception as e:
log("Exception: {}".format(format_exception(e)))
pass
def get_game_names(game_id_list):
json_data=open(games_file).read()
data = json.loads(json_data)
result = []
for game_id in game_id_list:
if isinstance(game_id, str) and not game_id.isdigit():
result.append(game_id)
continue
name_set = False
for game in data:
if game['id'] == game_id:
result.append(game['name'])
name_set = True
return result
def get_mention_status(mention):
try:
json_data=open(member_status).read()
data = json.loads(json_data)
except ValueError:
data = {}
if not data:
data = {}
for user in data:
if 'mention' in data[user]:
if data[user]['mention'] == mention:
return data[user]
return None
def check_msg_queue():
#print("checking messages")
messages = db_get_messages()
if messages:
for message in messages:
try:
member = db_get_member(filter(unicode.isalnum, message['message_to']))
if member:
if message['message_to'] == member['discord_mention']:
print("Found Message: {} - {} - Status: {} Channel: {}".format(message['message_to'], member['discord_mention'], member['status'], message['channel']))
if member['status'] == 'online':
client.send_message(Object(message['channel']), '{}, {} asked me to tell you "{}"'.format(message['message_to'], message['message_from'], message['message']))
db_delete_sent_message(message['message_id'])
except Exception as e:
log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],))
return
@client.event
def on_message(message):
#print message.content
#print message.author
#print client.user
global muted_until
# we do not want the bot to reply to itself
if message.author == client.user:
return
if message.content.lower().startswith(client.user.name.lower()):
print('Someone is talking to %s' % (client.user.name.lower(),))
if ' or ' in message.content:
questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore')))
if message.content.startswith('!help') or message.content.startswith('!commands'):
client.send_message(message.channel,
"""{} Available Commands:
You can ask compound or questions and I will choose. Example: HellsBot Rui is a Faggot or Rui is a faggot?
User Info:
!aliases - Returns a list of all aliases a user has set for themselves.
!addalias <alias> - Adds an alias to your list of aliases.
!lastseen <username> - Returns info on when the user was last seen and their status.
Messages:
!msg <username> in 5 minutes Tea is ready
!msg <username> in 45 seconds Your finished masterbating
!msg <username> in 2 hours The movie is over
!msg <username> on 12/22/2015 Happy Birthday!
Games:
!games <username> - Returns a list of games played for a username.
!gameslist <count> - Returns a list of the top 20 games and the number of people who have played that game. if you pass a limit it will show that many games instead.
!whoplayed <gamename> - Returns a list of players who have played the game.
Minigames:
!gimmecredits - Gives you some extra credits in case you run out.
!credits - Lists your current credits.
!bet <amount> - Start a game of BlackJack.
!hit - Draw a card
!stand - Show the cards
!buyticket - Purchases a raffle ticket for 100 credits
!raffle - Shows information about the current raffle
Spam:
!youtube <search term> - Returns the first video from the search results for the search term.
!gif <search term> - Returns the first gif from the search results.
!image <search term> - Returns the first image from the search results.
Stuff:
!addfortune <fortune> - Adds a new fortune.
!fortune - Returns your fortune.
!addjoke <joke> - Adds a new joke (it can be multiline but must all be in a single message).
!joke - Returns a random joke.
!roll <1d20> - Roll X number of dice of size X. 1d20 returns 1 roll 1-20. 3d6 returns 3 rolls of 1-6 etc...
!secret
!shutup - disables all image / gif / youtube span for 5 minutes
!bemyirlwaifu""".format(message.author.mention()))
return
if message.content.startswith('!lastseen'):
username = message.content[10:].replace('@', '').lower()
member = db_get_member(username=username)
log(member)
if member:
out_string = ''
if member['is_afk'] == 1:
out_string = 'Went AFK at: {}\n'.format(member['afk_at'])
elif member['status'] == 'offline':
out_string = 'Currently Offline\n'
else:
out_string = 'Currently Online\n'
out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(member['status'],
member['status_change_at'],
human(datetime.datetime.strptime(member['status_change_at'], '%Y/%m/%d %H:%M:%S')),
member['prev_status'])
client.send_message(message.channel, 'Last Information on {}:\n{}'.format(username, out_string))
else:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))
return
if message.content.startswith('!shutup'):
muted_until = datetime.datetime.now() + datetime.timedelta(minutes=5)
client.send_message(message.channel, search_youtube(query))
return
if message.content.startswith('!youtube'):
if datetime.datetime.now() < muted_until:
return
query = message.content[9:]
client.send_message(message.channel, search_youtube(query))
return
if message.content.startswith('!image'):
if datetime.datetime.now() < muted_until:
return
query = message.content[7:]
client.send_message(message.channel, search_google_images(query))
return
if message.content.startswith('!gif'):
if datetime.datetime.now() < muted_until:
return
query = message.content[7:]
client.send_message(message.channel, search_google_images(query, True))
return
if message.content.startswith('!roll'):
request = message.content[6:]
count = 1
dice = 100
if request.strip() != '':
if 'd' in request:
dice_parts = request.split('d')
if len(dice_parts) == 2:
if dice_parts[0].isdigit() and dice_parts[1].isdigit():
count = int(dice_parts[0])
dice = int(dice_parts[1])
if count > 100000000000000000:
client.send_message(message.channel, '{} stop fucking around with those stupid numbers...'.format(message.author.mention()))
return
if count > 100:
client.send_message(message.channel, '{} 100 is the largest number of dice I will roll.'.format(message.author.mention()))
return
roll_results = []
for i in range(count):
roll_results.append(random.randint(1,dice))
out_string = '{} your roll {}d{}: {} = {}'.format(message.author.mention(), count, dice, '+'.join(str(r) for r in roll_results), sum(roll_results))
client.send_message(message.channel, out_string)
return
if message.content.startswith('!gameslist') or message.content.startswith('!gamelist') :
parts = message.content.split(' ')
limit = 20
if len(parts) > 1 and parts[1].isdigit():
limit = int(parts[1])
games_list = db_get_games_list(limit)
out_string = ''
for game in games_list:
out_string += ' {} - {}\n'.format(game[1], byteify(game[0]))
client.send_message(message.channel, 'The games I have seen people playing are: ')
while len(out_string) > 0:
client.send_message(message.channel, out_string[:1900])
out_string = out_string[1900:]
return
if message.content.startswith('!aliases'):
username = message.content[9:].replace('@', '').lower()
member = db_get_member(username=username)
if member:
aliases = db_get_aliases(member['member_id'])
if aliases:
client.send_message(message.channel, '{} has the following aliases: {}'.format(username, byteify(', '.join(aliases))))
else:
client.send_message(message.channel, 'No known alises for {} yet {}'.format(username, message.author.mention()))
else:
client.send_message(message.channel, 'I don\'t know who you are speaking of {}!'.format(message.author.mention()))
return
if message.content.startswith('!addalias'):
alias = message.content[10:]
username = message.author.name.lower()
member = db_get_member(username=username)
if member:
db_add_aliases(member['member_id'], alias)
client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias)))
else:
client.send_message(message.channel, 'Something horrible happened and it is all your fault, try logging out / on again or play a game. (or fuck off i dunno i\'m just an error message. Who am I to tell you how to run your life...)')
return
if message.content.startswith('!games'):
username = message.content[7:].replace('@', '').lower()
games_list = db_get_games(username)
if games_list:
games = ', '.join(games_list)
client.send_message(message.channel, 'I have seen {} playing: {}'.format(username, games))
else:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))
if message.content.startswith('!whoplayed'):
game_name = message.content[11:]
member_list = db_get_whoplayed(game_name)
if not member_list:
client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
else:
out_string = ''
for member in member_list:
out_string += ' {} - {}\n'.format(byteify(member[1]), byteify(member[0]))
client.send_message(message.channel, 'Below is a list of people who have played {} and the number of times they have launched the game:'.format(byteify(game_name),))
while len(out_string) > 0:
client.send_message(message.channel, out_string[:1900])
out_string = out_string[1900:]
return
if message.content.startswith('!gimmecredits'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
credits = db_get_credit(member['member_id'])
if credits < 5:
amount = random.randint(5, 50)
db_update_credit(member['member_id'], amount)
client.send_message(message.author, "You have been given {} credits.".format(amount,))
else:
client.send_message(message.author, "You already have credits. Stop begging.")
return
if message.content.startswith('!grantcredits'):
if message.author.id != '78767557628133376':
client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
return
members = db_get_all_members()
if len(members) < 0:
client.send_message(message.channel, "There was a problem looking up your information.")
else:
for member in members:
credits = db_get_credit(member['member_id'])
if credits < 100:
db_update_credit(member['member_id'], 100)
client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
return
if message.content.startswith('!raffle'):
client.send_message(message.channel, """Current Raffle Item:
Game: **The Witness**
Description:
*Inspired by Myst, The Witness has the player explore an open world island filled with a number of natural and man-made structures. The player progresses by solving puzzles which are based on interactions with mazes presented on panels around the island.*
Raffle Date: **1/29/2016**
You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits.
You can get extra credits by playing !slots and !bet <amount> on BlackJack.
""")
return
if message.content.startswith('!buyticket'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
result, response = db_buy_ticket(member['member_id'], 1)
if not result:
client.send_message(message.author, response)
return
credits = db_get_credit(member['member_id'])
client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
return
if message.content.startswith('!credits'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
else:
credits = db_get_credit(member['member_id'])
client.send_message(message.author, "Credits: {}".format(credits))
return
if message.content.startswith('!slotsrules'):
client.send_message(message.channel, """Paying Combinations:
:moneybag:\t:moneybag:\t:moneybag:\t\t\t pays\t250
:bell:\t:bell:\t:bell:/:moneybag:\tpays\t20
:diamonds:\t:diamonds:\t:diamonds:/:moneybag:\tpays\t14
:spades:\t:spades:\t:spades:/:moneybag:\tpays\t10
:cherries:\t:cherries:\t:cherries:\t\t\t pays\t7
:cherries:\t:cherries:\t -\t\t\t\t pays\t5
:cherries:\t -\t\t -\t\t\t\t pays\t2
:black_square_button:\tblank space
All payouts are in credits. Each pull costs 1 credit. To Play: !slots""")
return
if message.content.startswith('!slots'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
return
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
return
result, error_message = db_update_credit(member['member_id'], -1)
if not result:
client.send_message(message.author, error_message)
return
reel1 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
reel2 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
reel3 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
#:moneybag: :bell: :diamonds: :spades: :hearts:
val1 = random.choice(reel1)
val2 = random.choice(reel2)
val3 = random.choice(reel3)
winnings = 0
reels = [val1, val2, val3]
cherries = reels.count(":cherries:")
spades = reels.count(":spades:")
diamonds = reels.count(":diamonds:")
bells = reels.count(":bells:")
moneybags = reels.count(":moneybag:")
if moneybags == 3:
winnings = 250
elif bells == 3 or (bells == 2 and moneybags == 1):
winnings = 20
elif diamonds == 3 or (diamonds == 2 and moneybags == 1):
winnings = 14
elif spades == 3 or (spades == 2 and moneybags == 1):
winnings = 10
elif cherries == 3:
winnings = 7
elif cherries == 2:
winnings = 5
elif cherries == 1:
winnings = 2
out_string = """| {} | {} | {} |\n\n""".format(val1, val2, val3)
if winnings == 250:
out_string += "You Won the JACKPOT! Total Winnings: {}".format(winnings,)
elif winnings > 0:
out_string += "You Won! Total Winnings: {}".format(winnings,)
else:
out_string += "You lose. Total Winnings: {}".format(winnings,)
if winnings > 0:
result, error_message = db_update_credit(member['member_id'], winnings)
if not result:
client.send_message(message.author, error_message)
return
credits = db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
log(out_string)
client.send_message(message.author, out_string)
return
if message.content.startswith('!hit') or message.content.startswith('!draw'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
bj.draw()
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
credits = db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
else:
client.send_message(message.author, "You must start a game with !bet before you can ask for a new card.")
return
if message.content.startswith('!stay') or message.content.startswith('!stand'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = db_get_minigame_state(member['member_id'], 'blackjack')
if state:
out_string = ""
bj = pickle.loads(str(state))
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
credits = db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
return
if message.content.startswith('!bet'):
member = db_get_member(message.author.id)
if not member:
client.send_message(message.author, "There was a problem looking up your information.")
elif type(message.channel) is not discord.channel.PrivateChannel:
client.send_message(message.author, "You must make all bets / gaming via private message.")
else:
state = db_get_minigame_state(member['member_id'], 'blackjack')
if state:
client.send_message(message.author, "You are already playing a game!")
out_string = ""
bj = pickle.loads(str(state))
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
credits = db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
return
out_string = ""
bet_amount = message.content[5:]
log("Member: {} Bet: {}".format(member['member_name'], bet_amount))
if not bet_amount.isdigit():
client.send_message(message.author, "Please provide a bet amount. !bet 10")
return
result, error_message = db_update_credit(member['member_id'], -int(bet_amount))
if not result:
client.send_message(message.author, error_message)
return
out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount)
bj = Blackjack(bet_amount)
out_string += bj.print_hand()
actions = bj.get_actions()
if len(actions) > 0:
out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
else:
win, response = bj.is_win()
out_string += "\n\n" + bj.print_hand(show_dealer=True)
out_string += "\n\n" + response.format(win,)
db_delete_minigame_state(member['member_id'], 'blackjack')
result, error_message = db_update_credit(member['member_id'], int(win))
if not result:
client.send_message(message.author, error_message)
return
credits = db_get_credit(member['member_id'])
out_string += "\nCredits: {}".format(credits)
client.send_message(message.author, out_string)
return
# !msg joe in 5 minutes YOU ARE A DICK
if message.content.startswith('!msg'):
try:
json_data=open(deliveries_file).read()
data = json.loads(json_data)
except ValueError:
data = {}
if not data:
data = {}
channel = message.channel
author = message.author
#author = message.author.name
username = ''
try:
message_bits = message.content.split(" ")
msg_datetime = datetime.datetime.now()
msg_idx = 2
if message_bits[2] == 'in' and message_bits[3].isdigit():
time = int(message_bits[3])
msg_idx = 4
if message_bits[4].startswith('sec'):
msg_datetime = msg_datetime + datetime.timedelta(seconds=time)
msg_idx = 5
elif message_bits[4].startswith('hour'):
msg_datetime = msg_datetime + datetime.timedelta(hours=time)
msg_idx = 5
else: # minutes by default
msg_datetime = msg_datetime + datetime.timedelta(minutes=time)
msg_idx = 5
elif message_bits[2] == 'on':
try:
tmp_date = parse(message_bits[3])
msg_datetime = tmp_date
msg_idx = 4
except ValueError:
client.send_message(channel, 'Your shitty message has been rejected {}. Next time learn how to date...MM\\DD\\YYYY'.format(message.author.mention()))
return
username = message_bits[1]
user_mention = ''
# TODO: have it look in the database. Do this AFTER on startup we add all users.
for member in client.get_all_members():
print("MEMBER: %s" % member)
if username.lower() == member.name.lower():
user_mention = member.mention()
user_id = member.id
if user_mention == '':
client.send_message(channel, 'Your shitty message has been rejected {}. That user does not exist.'.format(message.author.name))
return
msg_text = byteify(' '.join(message_bits[msg_idx:]))
message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
print("Message: %s" % message)
db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
# data[user_mention] = {}
# data[user_mention][author.mention()] = message
# jdata = json.dumps(data, ensure_ascii=False)
# print("Data: %s" % data)
#test_ch = Object(channel.id)
#client.send_message(test_ch, 'Test Message {}.'.format(author))
except Exception as e:
client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, e))
return
# open(deliveries_file, 'wb+').write(jdata.encode('utf8'))
if msg_datetime < datetime.datetime.now():
client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
else:
client.send_message(channel, '{} your message will be delivered to {} {}.'.format(author.name, user_mention, human(msg_datetime)))
check_msg_queue()
return
if message.content.startswith('!addfortune'):
try:
fortune = message.content[9:]
if 'aa737a5846' in fortune:
client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
conn.commit()
print("Added fortune")
except Exception as e:
print e.message
client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
return
client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
return
if message.content.startswith('!fortune'):
fortune = None
try:
c = conn.cursor()
fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
print(fortune)
except Exception as e:
print(e)
pass
if not fortune:
client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
else:
client.send_message(message.channel, '{} Your fortune is... {}'.format(message.author.mention(), byteify(fortune)))
return
if message.content.startswith('!question'):
question = message.content[10:]
if "is it gay" in question:
client.send_message(message.channel, 'Yes {}, it is gay.'.format(message.author.mention()))
return
res = wolf.query(question)
try:
if len(res.pods):
pod_text = []
for pod in res.pods:
if pod.text:
pod_text.append(pod.text)
client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify("\n".join(pod_text)[:1990])))
else:
tagged_sent = pos_tag(question.replace('?', '').split())
proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
wiki_search = " ".join(proper_nouns)
if wiki_search.strip() != "":
print "Looking up {}".format(wiki_search)
wiki_out = wikipedia.summary(wiki_search, sentences=3)
client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
else:
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
return
except Exception as e:
print(format_exception(e))
client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
return
if message.content.startswith('!addjoke'):
try:
joke = message.content[9:]
if 'aa737a5846' in joke:
client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
return
date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
c = conn.cursor()
c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
conn.commit()
print("Added joke")
except Exception as e:
print e.message
client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
return
client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
return
if message.content.startswith('!joke'):
joke = None
try:
c = conn.cursor()
joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
print(joke)
except Exception as e:
print(e)
pass
if not joke:
client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
else:
client.send_message(message.channel, '{} {}'.format(message.author.mention(), byteify(joke)))
return
if message.content.startswith('!secret'):
client.send_message(message.channel, 'git gud {}! My source is here: http://git.savsoul.com/barry/discordbot\nVersion: {}'.format(message.author.mention(), VERSION))
if message.content.startswith('!bemyirlwaifu'):
client.send_message(message.channel, 'http://orig13.deviantart.net/b25e/f/2014/175/3/d/no_waifu_no_laifu_by_imtheonenexttome-d7nsx3b.gif {}!'.format(message.author.mention()))
if message.content.startswith('HILLARY 2016'):
client.send_message(message.channel, ':bomb: Ohhhhhh, now you done it...:bomb:'.format(message.author.mention()))
if message.content.startswith('!hello'):
client.send_message(message.channel, 'Hello {}!'.format(message.author.mention()))
if message.content.startswith('!deal'):
client.send_message(message.channel, 'You get {}!'.format(message.author.mention()))
@client.event
def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
check_msg_queue()
retries = 0
while retries < 1000:
try:
json_data=open(credentials).read()
creds = json.loads(json_data)
wolf = wolframalpha.Client(creds['wolframkey'])
client.login(creds['username'], creds['password'])
client.run()
except KeyboardInterrupt:
conn.close
quit()
except:
retries += 1
print("Shit I crashed: Retry %s" % (retries,))