771720d3 by Barry

Moved the data access layer to it's own file. Added a way to restart the bot fro…

…m chat. Updates to pankration.
1 parent 775d749e
1 import sqlite3
2
3 conn = sqlite3.connect('db.sqlite3')
4
5 def log(message):
6 logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
7
8 ##################
9 ## Database Calls
10 ##################
11
12 # Converts a row into a dictionary
13 def dict_factory(cursor, row):
14 if row == None:
15 return None
16 d = {}
17 for idx, col in enumerate(cursor.description):
18 d[col[0]] = row[idx]
19 return d
20
21 def db_get_credit(member_id):
22 c = conn.cursor()
23 credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
24 if credits:
25 return credits[0]
26
27 def db_buy_ticket(member_id, amount):
28 c = conn.cursor()
29 credits = c.execute("SELECT credits, tickets FROM members WHERE member_id = ?;", (member_id,)).fetchone()
30 if not credits:
31 return False, "Unable to find your account"
32
33 if int(credits[0]) - int(100*amount) < 0:
34 return False, "You do not have enough credits to purchase a ticket. Credits: {} Tickets: {}".format(credits[0], credits[1])
35 c = conn.cursor()
36 cost = int(100 * amount)
37 c.execute("""UPDATE members SET credits = credits - ?, tickets = tickets + ?
38 WHERE member_id = ?;""", (cost, amount, member_id))
39 conn.commit()
40 return True, int(credits[1]) + int(amount)
41
42 def db_update_credit(member_id, amount):
43 c = conn.cursor()
44 credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
45 if not credits:
46 return False, "Unable to find your account"
47
48 if int(credits[0]) + int(amount) < 0:
49 return False, "You do not have enough credits to cover amount requested. Credit: {} Amount Requested: {}".format(credits[0], amount)
50 if int(credits[0]) < 0:
51 c.execute("""UPDATE members SET credits = 0
52 WHERE member_id = ?;""", (amount, member_id))
53 conn.commit()
54
55 c.execute("""UPDATE members SET credits = credits + ?
56 WHERE member_id = ?;""", (amount, member_id))
57 conn.commit()
58 return True, ""
59
60 def db_add_minigame(member_id, minigame_name, state):
61 c = conn.cursor()
62 db_state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
63 if not db_state:
64 c.execute("""INSERT INTO minigames(member_id, minigame_name, state)
65 VALUES(?, ?, ?);""", (member_id, minigame_name, state))
66 conn.commit()
67 else:
68 c.execute("""UPDATE minigames SET state = ?
69 WHERE member_id = ? AND minigame_name = ?;""", (state, member_id, minigame_name))
70 conn.commit()
71
72 def db_get_minigame_state(member_id, minigame_name):
73 c = conn.cursor()
74 state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
75 if state:
76 return state[0]
77
78 def db_delete_minigame_state(member_id, minigame_name):
79 c = conn.cursor()
80 c.execute("DELETE FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name))
81 conn.commit()
82
83 def db_add_message(message, delivery_time, channel, message_from, message_to, user_id):
84 c = conn.cursor()
85 c.execute("""INSERT INTO messages(message, delivery_time, channel, message_from, message_to, user_id)
86 VALUES(?, ?, ?, ?, ?, ?);""", (message, delivery_time, channel, message_from, message_to, user_id))
87 conn.commit()
88
89 def db_delete_sent_message(message_id):
90 c = conn.cursor()
91 c.execute("DELETE FROM messages WHERE message_id = ?;", (message_id,))
92 conn.commit()
93
94 def db_get_aliases(member_id):
95 c = conn.cursor()
96 aliases = c.execute("SELECT alias_name FROM aliases WHERE member_id = ?;", (member_id,)).fetchall()
97 if aliases:
98 alias_list = []
99 for alias in aliases:
100 alias_list.append(alias[0])
101 return alias_list
102 else:
103 return None
104
105 def db_add_aliases(member_id, alias_name):
106 c = conn.cursor()
107 c.execute("INSERT INTO aliases(alias_name, member_id) VALUES (?, ?);", (alias_name, member_id,))
108 conn.commit()
109
110 def db_get_messages():
111 msg_conn = sqlite3.connect('db.sqlite3')
112
113 c = msg_conn.cursor()
114 messages = c.execute("SELECT * FROM messages WHERE datetime('now') >= datetime( replace(delivery_time, '/', '-'));").fetchall()
115 if messages:
116 db_messages = []
117 for message in messages:
118 db_messages.append(dict_factory(c, message))
119 else:
120 db_messages = None
121 msg_conn.close()
122 return db_messages
123
124 def db_get_whoplayed(game_name):
125 c = conn.cursor()
126 members = c.execute("""SELECT m.member_name, xmg.launch_count
127 FROM members m
128 INNER JOIN xmember_games xmg ON
129 m.member_id = xmg.member_id
130 INNER JOIN games g ON
131 g.game_id = xmg.game_id
132 WHERE g.game_name COLLATE nocase = ?
133 Order By xmg.launch_count, m.member_name DESC;""", (game_name,)).fetchall()
134 member_list = {}
135 for member in members:
136 member_list[member[0]] = member[1]
137 #log(member_list)
138 return sorted(member_list.items(), reverse=True, key=operator.itemgetter(1))
139 #return sorted(member_list, reverse=True, key=lambda tup: tup[1])
140
141 def db_get_games(username):
142 c = conn.cursor()
143 games = c.execute("""SELECT g.game_name, xmg.launch_count FROM games g
144 INNER JOIN xmember_games xmg ON
145 g.game_id = xmg.game_id
146 INNER JOIN members m ON
147 m.member_id = xmg.member_id
148 WHERE m.member_name COLLATE nocase = ?;""", (username,)).fetchall()
149 games_list = {}
150 for game in games:
151 games_list[game[0]] = game[1]
152 return games_list
153
154 def db_get_games_list(limit):
155 c = conn.cursor()
156 games_list = c.execute("""SELECT g.game_name, count(DISTINCT xmg.member_id)
157 FROM games g
158 INNER JOIN xmember_games xmg ON
159 g.game_id = xmg.game_id
160 Group By xmg.game_id
161 Order By COUNT(DISTINCT xmg.member_id) DESC
162 LIMIT ?""", (limit,)).fetchall()
163 return games_list
164
165 def db_add_game(member_id, game_name):
166 # 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
167 c = conn.cursor()
168 games = c.execute("SELECT game_id FROM games WHERE game_name = ?;", (game_name,)).fetchone()
169 db_game_id = 0
170 if not games:
171 log("Adding Game: {}".format(game_name,))
172 c.execute("INSERT INTO games(game_name) VALUES(?);", (game_name,))
173 conn.commit()
174 db_game_id = c.execute("select last_insert_rowid();").fetchone()[0]
175 else:
176 db_game_id = games[0]
177 #log("DB Game ID: {}".format(db_game_id,))
178 member_games = c.execute("SELECT launch_count FROM xmember_games WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id)).fetchone()
179 if not member_games:
180 #log("Inserting Member Games: {}, {}".format(db_game_id, member_id))
181 c.execute("INSERT INTO xmember_games(game_id, member_id, launch_count) VALUES(?, ?, 1);", (db_game_id, member_id))
182 conn.commit()
183 else:
184 #log("Updating Member Games: {}, {}".format(db_game_id, member_id))
185 c.execute("UPDATE xmember_games SET launch_count = launch_count + 1 WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id))
186 conn.commit()
187
188 def db_get_all_members():
189 # 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
190 member_conn = sqlite3.connect('db.sqlite3')
191
192 c = member_conn.cursor()
193 results = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members;").fetchall()
194 member_conn.close()
195 members_list = []
196 for member in results:
197 members_list.append(dict_factory(c, member))
198 return members_list
199
200 def db_get_member(discord_id=None, username=None):
201 # 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
202 member_conn = sqlite3.connect('db.sqlite3')
203
204 c = member_conn.cursor()
205 result = None
206 if discord_id:
207 result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE discord_id = ?;", (discord_id,)).fetchone()
208 if username:
209 result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE member_name = ?;", (username,)).fetchone()
210 member_conn.close()
211 return dict_factory(c, result)
212
213 def db_create_member(member):
214 # 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
215 c = conn.cursor()
216 c.execute("""INSERT INTO members (member_name, discord_id, discord_mention,
217 is_afk, afk_at, status, prev_status,
218 status_change_at, current_game)
219 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);""", (member.name.lower(),
220 member.id, member.mention(),
221 0, datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
222 'online', 'offline',
223 datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
224 member.game_id))
225 conn.commit()
226 if member.game_id != None:
227 db_add_game(db_get_member(member.id)['member_id'], member.game_id)
228
229 def db_update_member(member, db_member):
230 # 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
231 db_member_id = db_member['member_id']
232 db_membername = db_member['member_name']
233 status = db_member['status']
234 prev_status = db_member['prev_status']
235
236 c = conn.cursor()
237 if member.name.lower() != db_membername:
238 log("Member Name changed! {} to {}".format(byteify(db_membername), byteify(member.name.lower())))
239 c.execute("UPDATE members SET member_name = ? WHERE discord_id = ?;", (member.name.lower(), member.id,))
240 conn.commit()
241
242 aliases = c.execute("SELECT * FROM aliases WHERE alias_name = ? AND member_id = ?;", (db_membername, db_member_id)).fetchone()
243 log("Alias list for user: {}".format(aliases))
244 if aliases == None:
245 log("creating new alias: {}, {}".format(byteify(db_membername), db_member_id))
246 c.execute("INSERT INTO aliases (alias_name, member_id) VALUES (?, ?);", (db_membername, db_member_id))
247 conn.commit()
248
249 if member.status == 'idle':
250 afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
251 is_afk = True
252 else:
253 is_afk = False
254 status_change_at = None
255 if status != member.status:
256 prev_status = status
257 status = member.status
258 status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
259 if is_afk:
260 #log("is afk")
261 c.execute("""UPDATE members
262 SET is_afk = ?, afk_at = ?, status = ?,
263 prev_status = ?, status_change_at = ?
264 WHERE discord_id = ?;""", (1, afk_at, status, prev_status, status_change_at, member.id))
265 conn.commit()
266 else:
267 #log("is not afk")
268 c.execute("""UPDATE members
269 SET is_afk = ?, status = ?,
270 prev_status = ?, status_change_at = ?
271 WHERE discord_id = ?;""", (0, status, prev_status, status_change_at, member.id))
272 conn.commit()
273 c.execute("UPDATE members SET current_game = ? WHERE discord_id = ?;", (member.game_id, member.id))
274 conn.commit()
275
276 #log("Member: {} \nMember GameID: {} db Game id: {}".format(member, member.game_id, db_member['current_game']))
277 if member.game_id != None and member.game_id != db_member['current_game']:
278 db_add_game(db_member['member_id'], member.game_id)
...\ No newline at end of file ...\ No newline at end of file
No preview for this file type
1 #!/usr/bin/env python
1 # -*- coding: utf-8 -*- 2 # -*- coding: utf-8 -*-
2 import requests 3 import requests
3 import discord 4 import discord
...@@ -11,6 +12,7 @@ import logging ...@@ -11,6 +12,7 @@ import logging
11 import traceback 12 import traceback
12 import sys 13 import sys
13 import wikipedia 14 import wikipedia
15 from subprocess import call
14 16
15 from dateutil.parser import parse 17 from dateutil.parser import parse
16 18
...@@ -23,16 +25,12 @@ from nltk.tag import pos_tag ...@@ -23,16 +25,12 @@ from nltk.tag import pos_tag
23 import wolframalpha 25 import wolframalpha
24 import sqlite3 26 import sqlite3
25 from blackjack import Blackjack 27 from blackjack import Blackjack
28 import data
26 29
27 VERSION = 1.6 30 VERSION = 2.0
28 31
29 conn = sqlite3.connect('db.sqlite3') 32 conn = sqlite3.connect('db.sqlite3')
30 33
31 member_status = 'members.json'
32 deliveries_file = 'deliveries.json'
33 # fortune_file = 'fortunes.json'
34 # joke_file = 'jokes.json'
35 games_file = 'games.json'
36 credentials = 'creds.json' 34 credentials = 'creds.json'
37 35
38 muted_until = datetime.datetime.now() 36 muted_until = datetime.datetime.now()
...@@ -81,7 +79,7 @@ def search_youtube(query): ...@@ -81,7 +79,7 @@ def search_youtube(query):
81 query_string = {"search_query" : query} 79 query_string = {"search_query" : query}
82 r = requests.get("http://www.youtube.com/results", params=query_string) 80 r = requests.get("http://www.youtube.com/results", params=query_string)
83 search_results = re.findall(r'href=\"\/watch\?v=(.{11})', r.content) 81 search_results = re.findall(r'href=\"\/watch\?v=(.{11})', r.content)
84 print("http://www.youtube.com/watch?v=" + search_results[0]) 82 log("http://www.youtube.com/watch?v=" + search_results[0])
85 return "http://www.youtube.com/watch?v=" + search_results[0] 83 return "http://www.youtube.com/watch?v=" + search_results[0]
86 84
87 def search_google_images(query, animated=False): 85 def search_google_images(query, animated=False):
...@@ -99,281 +97,10 @@ def search_google_images(query, animated=False): ...@@ -99,281 +97,10 @@ def search_google_images(query, animated=False):
99 search_result = search_result[:search_result.find('/revision/')] 97 search_result = search_result[:search_result.find('/revision/')]
100 if '%' in search_result: 98 if '%' in search_result:
101 search_result = search_result[:search_result.find('%')] 99 search_result = search_result[:search_result.find('%')]
102 print(search_result) 100 log(search_result)
103 return search_result 101 return search_result
104 return "boo you fail.." 102 return "boo you fail.."
105 103
106 ##################
107 ## Database Calls
108 ##################
109
110 # Converts a row into a dictionary
111 def dict_factory(cursor, row):
112 if row == None:
113 return None
114 d = {}
115 for idx, col in enumerate(cursor.description):
116 d[col[0]] = row[idx]
117 return d
118
119 def db_get_credit(member_id):
120 c = conn.cursor()
121 credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
122 if credits:
123 return credits[0]
124
125 def db_buy_ticket(member_id, amount):
126 c = conn.cursor()
127 credits = c.execute("SELECT credits, tickets FROM members WHERE member_id = ?;", (member_id,)).fetchone()
128 if not credits:
129 return False, "Unable to find your account"
130
131 if int(credits[0]) - int(100*amount) < 0:
132 return False, "You do not have enough credits to purchase a ticket. Credits: {} Tickets: {}".format(credits[0], credits[1])
133 c = conn.cursor()
134 cost = int(100 * amount)
135 c.execute("""UPDATE members SET credits = credits - ?, tickets = tickets + ?
136 WHERE member_id = ?;""", (cost, amount, member_id))
137 conn.commit()
138 return True, int(credits[1]) + int(amount)
139
140 def db_update_credit(member_id, amount):
141 c = conn.cursor()
142 credits = c.execute("SELECT credits FROM members WHERE member_id = ?;", (member_id,)).fetchone()
143 if not credits:
144 return False, "Unable to find your account"
145
146 if int(credits[0]) + int(amount) < 0:
147 return False, "You do not have enough credits to cover amount requested. Credit: {} Amount Requested: {}".format(credits[0], amount)
148 if int(credits[0]) < 0:
149 c.execute("""UPDATE members SET credits = 0
150 WHERE member_id = ?;""", (amount, member_id))
151 conn.commit()
152
153 c.execute("""UPDATE members SET credits = credits + ?
154 WHERE member_id = ?;""", (amount, member_id))
155 conn.commit()
156 return True, ""
157
158 def db_add_minigame(member_id, minigame_name, state):
159 c = conn.cursor()
160 db_state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
161 if not db_state:
162 c.execute("""INSERT INTO minigames(member_id, minigame_name, state)
163 VALUES(?, ?, ?);""", (member_id, minigame_name, state))
164 conn.commit()
165 else:
166 c.execute("""UPDATE minigames SET state = ?
167 WHERE member_id = ? AND minigame_name = ?;""", (state, member_id, minigame_name))
168 conn.commit()
169
170 def db_get_minigame_state(member_id, minigame_name):
171 c = conn.cursor()
172 state = c.execute("SELECT state FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name)).fetchone()
173 if state:
174 return state[0]
175
176 def db_delete_minigame_state(member_id, minigame_name):
177 c = conn.cursor()
178 c.execute("DELETE FROM minigames WHERE member_id = ? AND minigame_name = ?;", (member_id, minigame_name))
179 conn.commit()
180
181 def db_add_message(message, delivery_time, channel, message_from, message_to, user_id):
182 c = conn.cursor()
183 c.execute("""INSERT INTO messages(message, delivery_time, channel, message_from, message_to, user_id)
184 VALUES(?, ?, ?, ?, ?, ?);""", (message, delivery_time, channel, message_from, message_to, user_id))
185 conn.commit()
186
187 def db_delete_sent_message(message_id):
188 c = conn.cursor()
189 c.execute("DELETE FROM messages WHERE message_id = ?;", (message_id,))
190 conn.commit()
191
192 def db_get_aliases(member_id):
193 c = conn.cursor()
194 aliases = c.execute("SELECT alias_name FROM aliases WHERE member_id = ?;", (member_id,)).fetchall()
195 if aliases:
196 alias_list = []
197 for alias in aliases:
198 alias_list.append(alias[0])
199 return alias_list
200 else:
201 return None
202
203 def db_add_aliases(member_id, alias_name):
204 c = conn.cursor()
205 c.execute("INSERT INTO aliases(alias_name, member_id) VALUES (?, ?);", (alias_name, member_id,))
206 conn.commit()
207
208 def db_get_messages():
209 msg_conn = sqlite3.connect('db.sqlite3')
210
211 c = msg_conn.cursor()
212 messages = c.execute("SELECT * FROM messages WHERE datetime('now') >= datetime( replace(delivery_time, '/', '-'));").fetchall()
213 if messages:
214 db_messages = []
215 for message in messages:
216 db_messages.append(dict_factory(c, message))
217 else:
218 db_messages = None
219 msg_conn.close()
220 return db_messages
221
222 def db_get_whoplayed(game_name):
223 c = conn.cursor()
224 members = c.execute("""SELECT m.member_name, xmg.launch_count
225 FROM members m
226 INNER JOIN xmember_games xmg ON
227 m.member_id = xmg.member_id
228 INNER JOIN games g ON
229 g.game_id = xmg.game_id
230 WHERE g.game_name COLLATE nocase = ?
231 Order By xmg.launch_count, m.member_name DESC;""", (game_name,)).fetchall()
232 member_list = {}
233 for member in members:
234 member_list[member[0]] = member[1]
235 #log(member_list)
236 return sorted(member_list.items(), reverse=True, key=operator.itemgetter(1))
237 #return sorted(member_list, reverse=True, key=lambda tup: tup[1])
238
239 def db_get_games(username):
240 c = conn.cursor()
241 games = c.execute("""SELECT g.game_name, xmg.launch_count FROM games g
242 INNER JOIN xmember_games xmg ON
243 g.game_id = xmg.game_id
244 INNER JOIN members m ON
245 m.member_id = xmg.member_id
246 WHERE m.member_name COLLATE nocase = ?;""", (username,)).fetchall()
247 games_list = {}
248 for game in games:
249 games_list[game[0]] = game[1]
250 return games_list
251
252 def db_get_games_list(limit):
253 c = conn.cursor()
254 games_list = c.execute("""SELECT g.game_name, count(DISTINCT xmg.member_id)
255 FROM games g
256 INNER JOIN xmember_games xmg ON
257 g.game_id = xmg.game_id
258 Group By xmg.game_id
259 Order By COUNT(DISTINCT xmg.member_id) DESC
260 LIMIT ?""", (limit,)).fetchall()
261 return games_list
262
263 def db_add_game(member_id, game_name):
264 # 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
265 c = conn.cursor()
266 games = c.execute("SELECT game_id FROM games WHERE game_name = ?;", (game_name,)).fetchone()
267 db_game_id = 0
268 if not games:
269 log("Adding Game: {}".format(game_name,))
270 c.execute("INSERT INTO games(game_name) VALUES(?);", (game_name,))
271 conn.commit()
272 db_game_id = c.execute("select last_insert_rowid();").fetchone()[0]
273 else:
274 db_game_id = games[0]
275 #log("DB Game ID: {}".format(db_game_id,))
276 member_games = c.execute("SELECT launch_count FROM xmember_games WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id)).fetchone()
277 if not member_games:
278 #log("Inserting Member Games: {}, {}".format(db_game_id, member_id))
279 c.execute("INSERT INTO xmember_games(game_id, member_id, launch_count) VALUES(?, ?, 1);", (db_game_id, member_id))
280 conn.commit()
281 else:
282 #log("Updating Member Games: {}, {}".format(db_game_id, member_id))
283 c.execute("UPDATE xmember_games SET launch_count = launch_count + 1 WHERE game_id = ? AND member_id = ?;", (db_game_id, member_id))
284 conn.commit()
285
286 def db_get_all_members():
287 # 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
288 member_conn = sqlite3.connect('db.sqlite3')
289
290 c = member_conn.cursor()
291 results = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members;").fetchall()
292 member_conn.close()
293 members_list = []
294 for member in results:
295 members_list.append(dict_factory(c, member))
296 return members_list
297
298 def db_get_member(discord_id=None, username=None):
299 # 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
300 member_conn = sqlite3.connect('db.sqlite3')
301
302 c = member_conn.cursor()
303 result = None
304 if discord_id:
305 result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE discord_id = ?;", (discord_id,)).fetchone()
306 if username:
307 result = c.execute("SELECT member_id, member_name, discord_id, discord_mention, is_afk, afk_at, status, prev_status, status_change_at, current_game, credits, tickets FROM members WHERE member_name = ?;", (username,)).fetchone()
308 member_conn.close()
309 return dict_factory(c, result)
310
311 def db_create_member(member):
312 # 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
313 c = conn.cursor()
314 c.execute("""INSERT INTO members (member_name, discord_id, discord_mention,
315 is_afk, afk_at, status, prev_status,
316 status_change_at, current_game)
317 VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?);""", (member.name.lower(),
318 member.id, member.mention(),
319 0, datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
320 'online', 'offline',
321 datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'),
322 member.game_id))
323 conn.commit()
324 if member.game_id != None:
325 db_add_game(db_get_member(member.id)['member_id'], member.game_id)
326
327 def db_update_member(member, db_member):
328 # 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
329 db_member_id = db_member['member_id']
330 db_membername = db_member['member_name']
331 status = db_member['status']
332 prev_status = db_member['prev_status']
333
334 c = conn.cursor()
335 if member.name.lower() != db_membername:
336 log("Member Name changed! {} to {}".format(byteify(db_membername), byteify(member.name.lower())))
337 c.execute("UPDATE members SET member_name = ? WHERE discord_id = ?;", (member.name.lower(), member.id,))
338 conn.commit()
339
340 aliases = c.execute("SELECT * FROM aliases WHERE alias_name = ? AND member_id = ?;", (db_membername, db_member_id)).fetchone()
341 log("Alias list for user: {}".format(aliases))
342 if aliases == None:
343 log("creating new alias: {}, {}".format(byteify(db_membername), db_member_id))
344 c.execute("INSERT INTO aliases (alias_name, member_id) VALUES (?, ?);", (db_membername, db_member_id))
345 conn.commit()
346
347 if member.status == 'idle':
348 afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
349 is_afk = True
350 else:
351 is_afk = False
352 status_change_at = None
353 if status != member.status:
354 prev_status = status
355 status = member.status
356 status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
357 if is_afk:
358 #log("is afk")
359 c.execute("""UPDATE members
360 SET is_afk = ?, afk_at = ?, status = ?,
361 prev_status = ?, status_change_at = ?
362 WHERE discord_id = ?;""", (1, afk_at, status, prev_status, status_change_at, member.id))
363 conn.commit()
364 else:
365 #log("is not afk")
366 c.execute("""UPDATE members
367 SET is_afk = ?, status = ?,
368 prev_status = ?, status_change_at = ?
369 WHERE discord_id = ?;""", (0, status, prev_status, status_change_at, member.id))
370 conn.commit()
371 c.execute("UPDATE members SET current_game = ? WHERE discord_id = ?;", (member.game_id, member.id))
372 conn.commit()
373
374 #log("Member: {} \nMember GameID: {} db Game id: {}".format(member, member.game_id, db_member['current_game']))
375 if member.game_id != None and member.game_id != db_member['current_game']:
376 db_add_game(db_member['member_id'], member.game_id)
377 104
378 ################# 105 #################
379 ## Client Events 106 ## Client Events
...@@ -387,62 +114,33 @@ def on_socket_raw_send(payload, binary=False): ...@@ -387,62 +114,33 @@ def on_socket_raw_send(payload, binary=False):
387 def on_status(member): 114 def on_status(member):
388 for member in client.get_all_members(): 115 for member in client.get_all_members():
389 try: 116 try:
390 db_member = db_get_member(member.id) 117 db_member = data.db_get_member(member.id)
391 #log(db_member) 118 #log(db_member)
392 if not db_member: 119 if not db_member:
393 log("Creating new member: {}".format(member) ) 120 log("Creating new member: {}".format(member) )
394 db_create_member(member) 121 data.db_create_member(member)
395 else: 122 else:
396 #log("Updating member: {}".format(member) ) 123 #log("Updating member: {}".format(member) )
397 db_update_member(member, db_member) 124 data.db_update_member(member, db_member)
398 125
399 check_msg_queue() 126 check_msg_queue()
400 except Exception as e: 127 except Exception as e:
401 log("Exception: {}".format(format_exception(e))) 128 log("Exception: {}".format(format_exception(e)))
402 pass 129 pass
403 130
404 def get_game_names(game_id_list):
405 json_data=open(games_file).read()
406 data = json.loads(json_data)
407 result = []
408 for game_id in game_id_list:
409 if isinstance(game_id, str) and not game_id.isdigit():
410 result.append(game_id)
411 continue
412 name_set = False
413 for game in data:
414 if game['id'] == game_id:
415 result.append(game['name'])
416 name_set = True
417 return result
418
419 def get_mention_status(mention):
420 try:
421 json_data=open(member_status).read()
422 data = json.loads(json_data)
423 except ValueError:
424 data = {}
425 if not data:
426 data = {}
427 for user in data:
428 if 'mention' in data[user]:
429 if data[user]['mention'] == mention:
430 return data[user]
431 return None
432
433 def check_msg_queue(): 131 def check_msg_queue():
434 #print("checking messages") 132 #log("checking messages")
435 messages = db_get_messages() 133 messages = data.db_get_messages()
436 if messages: 134 if messages:
437 for message in messages: 135 for message in messages:
438 try: 136 try:
439 member = db_get_member(filter(unicode.isalnum, message['message_to'])) 137 member = data.db_get_member(filter(unicode.isalnum, message['message_to']))
440 if member: 138 if member:
441 if message['message_to'] == member['discord_mention']: 139 if message['message_to'] == member['discord_mention']:
442 print("Found Message: {} - {} - Status: {} Channel: {}".format(message['message_to'], member['discord_mention'], member['status'], message['channel'])) 140 log("Found Message: {} - {} - Status: {} Channel: {}".format(message['message_to'], member['discord_mention'], member['status'], message['channel']))
443 if member['status'] == 'online': 141 if member['status'] == 'online':
444 client.send_message(Object(message['channel']), '{}, {} asked me to tell you "{}"'.format(message['message_to'], message['message_from'], message['message'])) 142 client.send_message(Object(message['channel']), '{}, {} asked me to tell you "{}"'.format(message['message_to'], message['message_from'], message['message']))
445 db_delete_sent_message(message['message_id']) 143 data.db_delete_sent_message(message['message_id'])
446 except Exception as e: 144 except Exception as e:
447 log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],)) 145 log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],))
448 return 146 return
...@@ -458,7 +156,7 @@ def on_message(message): ...@@ -458,7 +156,7 @@ def on_message(message):
458 return 156 return
459 157
460 if message.content.lower().startswith(client.user.name.lower()): 158 if message.content.lower().startswith(client.user.name.lower()):
461 print('Someone is talking to %s' % (client.user.name.lower(),)) 159 log('Someone is talking to %s' % (client.user.name.lower(),))
462 if ' or ' in message.content: 160 if ' or ' in message.content:
463 questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ') 161 questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
464 client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore'))) 162 client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore')))
...@@ -511,8 +209,8 @@ Stuff: ...@@ -511,8 +209,8 @@ Stuff:
511 209
512 if message.content.startswith('!lastseen'): 210 if message.content.startswith('!lastseen'):
513 username = message.content[10:].replace('@', '').lower() 211 username = message.content[10:].replace('@', '').lower()
514 member = db_get_member(username=username) 212 member = data.db_get_member(username=username)
515 log(member) 213 #log(member)
516 if member: 214 if member:
517 out_string = '' 215 out_string = ''
518 if member['is_afk'] == 1: 216 if member['is_afk'] == 1:
...@@ -587,7 +285,7 @@ Stuff: ...@@ -587,7 +285,7 @@ Stuff:
587 limit = 20 285 limit = 20
588 if len(parts) > 1 and parts[1].isdigit(): 286 if len(parts) > 1 and parts[1].isdigit():
589 limit = int(parts[1]) 287 limit = int(parts[1])
590 games_list = db_get_games_list(limit) 288 games_list = data.db_get_games_list(limit)
591 289
592 out_string = '' 290 out_string = ''
593 for game in games_list: 291 for game in games_list:
...@@ -601,9 +299,9 @@ Stuff: ...@@ -601,9 +299,9 @@ Stuff:
601 299
602 if message.content.startswith('!aliases'): 300 if message.content.startswith('!aliases'):
603 username = message.content[9:].replace('@', '').lower() 301 username = message.content[9:].replace('@', '').lower()
604 member = db_get_member(username=username) 302 member = data.db_get_member(username=username)
605 if member: 303 if member:
606 aliases = db_get_aliases(member['member_id']) 304 aliases = data.db_get_aliases(member['member_id'])
607 if aliases: 305 if aliases:
608 client.send_message(message.channel, '{} has the following aliases: {}'.format(username, byteify(', '.join(aliases)))) 306 client.send_message(message.channel, '{} has the following aliases: {}'.format(username, byteify(', '.join(aliases))))
609 else: 307 else:
...@@ -615,9 +313,9 @@ Stuff: ...@@ -615,9 +313,9 @@ Stuff:
615 if message.content.startswith('!addalias'): 313 if message.content.startswith('!addalias'):
616 alias = message.content[10:] 314 alias = message.content[10:]
617 username = message.author.name.lower() 315 username = message.author.name.lower()
618 member = db_get_member(username=username) 316 member = data.db_get_member(username=username)
619 if member: 317 if member:
620 db_add_aliases(member['member_id'], alias) 318 data.db_add_aliases(member['member_id'], alias)
621 client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias))) 319 client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias)))
622 else: 320 else:
623 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...)') 321 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...)')
...@@ -625,7 +323,7 @@ Stuff: ...@@ -625,7 +323,7 @@ Stuff:
625 323
626 if message.content.startswith('!games'): 324 if message.content.startswith('!games'):
627 username = message.content[7:].replace('@', '').lower() 325 username = message.content[7:].replace('@', '').lower()
628 games_list = db_get_games(username) 326 games_list = data.db_get_games(username)
629 if games_list: 327 if games_list:
630 games = ', '.join(games_list) 328 games = ', '.join(games_list)
631 client.send_message(message.channel, 'I have seen {} playing: {}'.format(username, games)) 329 client.send_message(message.channel, 'I have seen {} playing: {}'.format(username, games))
...@@ -634,7 +332,7 @@ Stuff: ...@@ -634,7 +332,7 @@ Stuff:
634 332
635 if message.content.startswith('!whoplayed'): 333 if message.content.startswith('!whoplayed'):
636 game_name = message.content[11:] 334 game_name = message.content[11:]
637 member_list = db_get_whoplayed(game_name) 335 member_list = data.db_get_whoplayed(game_name)
638 if not member_list: 336 if not member_list:
639 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention())) 337 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
640 else: 338 else:
...@@ -648,14 +346,14 @@ Stuff: ...@@ -648,14 +346,14 @@ Stuff:
648 return 346 return
649 347
650 if message.content.startswith('!gimmecredits'): 348 if message.content.startswith('!gimmecredits'):
651 member = db_get_member(message.author.id) 349 member = data.db_get_member(message.author.id)
652 if not member: 350 if not member:
653 client.send_message(message.author, "There was a problem looking up your information.") 351 client.send_message(message.author, "There was a problem looking up your information.")
654 else: 352 else:
655 credits = db_get_credit(member['member_id']) 353 credits = data.db_get_credit(member['member_id'])
656 if credits < 5: 354 if credits < 5:
657 amount = random.randint(5, 50) 355 amount = random.randint(5, 50)
658 db_update_credit(member['member_id'], amount) 356 data.db_update_credit(member['member_id'], amount)
659 client.send_message(message.author, "You have been given {} credits.".format(amount,)) 357 client.send_message(message.author, "You have been given {} credits.".format(amount,))
660 else: 358 else:
661 client.send_message(message.author, "You already have credits. Stop begging.") 359 client.send_message(message.author, "You already have credits. Stop begging.")
...@@ -665,14 +363,14 @@ Stuff: ...@@ -665,14 +363,14 @@ Stuff:
665 if message.author.id != '78767557628133376': 363 if message.author.id != '78767557628133376':
666 client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.") 364 client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
667 return 365 return
668 members = db_get_all_members() 366 members = data.db_get_all_members()
669 if len(members) < 0: 367 if len(members) < 0:
670 client.send_message(message.channel, "There was a problem looking up your information.") 368 client.send_message(message.channel, "There was a problem looking up your information.")
671 else: 369 else:
672 for member in members: 370 for member in members:
673 credits = db_get_credit(member['member_id']) 371 credits = data.db_get_credit(member['member_id'])
674 if credits < 100: 372 if credits < 100:
675 db_update_credit(member['member_id'], 100) 373 data.db_update_credit(member['member_id'], 100)
676 client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100)) 374 client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
677 return 375 return
678 376
...@@ -680,21 +378,26 @@ Stuff: ...@@ -680,21 +378,26 @@ Stuff:
680 # if message.author.id != '78767557628133376': 378 # if message.author.id != '78767557628133376':
681 # client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.") 379 # client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
682 # return 380 # return
683 members = db_get_all_members() 381 members = data.db_get_all_members()
684 if len(members) < 0: 382 if len(members) < 0:
685 client.send_message(message.channel, "There was a problem looking up your information.") 383 client.send_message(message.channel, "There was a problem looking up your information.")
686 else: 384 else:
687 ticket_count = 0 385 ticket_count = 0
688 for member in members: 386 for member in members:
689 if member['discord_id'] != '78767557628133376': 387 if member['discord_id'] != '78767557628133376':
690 log(member) 388 #log(member)
691 ticket_count += member['tickets'] 389 ticket_count += member['tickets']
692 log("Ticket Count: {}".format(ticket_count)) 390 if ticket_count == 0:
391 client.send_message(message.channel, "No Tickets have been sold for this raffle.")
392 return
393
394 #log("Ticket Count: {}".format(ticket_count))
693 out_string = "" 395 out_string = ""
694 for member in members: 396 for member in members:
695 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376': 397 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
696 percent = (float(member['tickets']) / float(ticket_count)) * 100.0 398 percent = (float(member['tickets']) / float(ticket_count)) * 100.0
697 out_string += "{} - {}%\n".format(member['member_name'], int(percent)) 399 out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
400
698 client.send_message(message.channel, out_string) 401 client.send_message(message.channel, out_string)
699 return 402 return
700 403
...@@ -702,27 +405,37 @@ Stuff: ...@@ -702,27 +405,37 @@ Stuff:
702 if message.author.id != '78767557628133376': 405 if message.author.id != '78767557628133376':
703 client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.") 406 client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.")
704 return 407 return
705 members = db_get_all_members() 408 members = data.db_get_all_members()
706 if len(members) < 0: 409 if len(members) < 0:
707 client.send_message(message.channel, "There was a problem looking up your information.") 410 client.send_message(message.channel, "There was a problem looking up your information.")
708 else: 411 else:
709 ticket_count = 0 412 ticket_count = 0
710 for member in members: 413 for member in members:
711 if member['discord_id'] != '78767557628133376': 414 if member['discord_id'] != '78767557628133376':
712 log(member) 415 #log(member)
713 ticket_count += member['tickets'] 416 ticket_count += member['tickets']
714 log("Ticket Count: {}".format(ticket_count)) 417 if ticket_count == 0:
418 client.send_message(message.channel, "No Tickets have been sold for this raffle.")
419 return
420
421 #log("Ticket Count: {}".format(ticket_count))
715 out_string = "The final standings are as follows: \n\n" 422 out_string = "The final standings are as follows: \n\n"
716 ticket_reel = [] 423 ticket_reel = []
717 for member in members: 424 for member in members:
718 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376': 425 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
719 ticket_reel += [member['member_name']] * member['tickets'] 426 ticket_reel += [member['discord_mention']] * member['tickets']
720 percent = (float(member['tickets']) / float(ticket_count)) * 100.0 427 percent = (float(member['tickets']) / float(ticket_count)) * 100.0
721 out_string += "{} - {}%\n".format(member['member_name'], int(percent)) 428 out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
722
723 winner = random.choice(ticket_reel) 429 winner = random.choice(ticket_reel)
724 out_string += "\n\n\nThe winner is....\n\n{}!".format(winner,) 430 while winner in ticket_reel:
725 client.send_message(message.channel, out_string) 431 ticket_reel.remove(winner)
432 second = random.choice(ticket_reel)
433 while second in ticket_reel:
434 ticket_reel.remove(second)
435 third = random.choice(ticket_reel)
436
437 out_string += "\n\n\n**The winner is....\n\n{}!**\n\n*2nd Place:* {}\n*3rd Place:* {}".format(byteify(winner), byteify(second), byteify(third))
438 client.send_message(message.channel, byteify(out_string))
726 return 439 return
727 440
728 if message.content.startswith('!raffle'): 441 if message.content.startswith('!raffle'):
...@@ -730,9 +443,11 @@ Stuff: ...@@ -730,9 +443,11 @@ Stuff:
730 443
731 **1st Place** 444 **1st Place**
732 445
733 Game: **The Witness** 446 Game: **Fairy Fencer F**
734 Description: 447 Description:
735 *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.* 448 *Long ago, the Vile God and the Goddess waged war with each other. Equally matched, they were sealed away in another world… Now a lazy young man named Fang somehow finds himself a key part of this war he’d really rather not deal with, but fate beckons in this uncommon RPG!*
449
450 http://store.steampowered.com/app/347830/
736 451
737 **2nd Place** 452 **2nd Place**
738 453
...@@ -742,28 +457,30 @@ Description: ...@@ -742,28 +457,30 @@ Description:
742 457
743 1 Random Steam Key 458 1 Random Steam Key
744 459
745 Raffle Date: **1/29/2016** 460 Raffle Date: **2/2/2016 00:00:00 (ish)**
746 461
747 You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits. 462 You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits.
748 You can get extra credits by playing !slots <amount> and !bet <amount> on BlackJack. 463 You can get extra credits by playing !slots <amount> and !bet <amount> on BlackJack.
464
465 **Disclaimer:** *If anything should go wrong you get no refund and there is no guarantee or warrantee on anything. 1 prize per person no matter how many tickets you have.*
749 """) 466 """)
750 return 467 return
751 if message.content.startswith('!buyticket'): 468 if message.content.startswith('!buyticket'):
752 member = db_get_member(message.author.id) 469 member = data.db_get_member(message.author.id)
753 if not member: 470 if not member:
754 client.send_message(message.author, "There was a problem looking up your information.") 471 client.send_message(message.author, "There was a problem looking up your information.")
755 else: 472 else:
756 result, response = db_buy_ticket(member['member_id'], 1) 473 result, response = data.db_buy_ticket(member['member_id'], 1)
757 if not result: 474 if not result:
758 client.send_message(message.author, response) 475 client.send_message(message.author, response)
759 return 476 return
760 477
761 credits = db_get_credit(member['member_id']) 478 credits = data.db_get_credit(member['member_id'])
762 client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits)) 479 client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
763 return 480 return
764 481
765 if message.content.startswith('!balance'): 482 if message.content.startswith('!balance'):
766 member = db_get_member(message.author.id) 483 member = data.db_get_member(message.author.id)
767 if not member: 484 if not member:
768 client.send_message(message.author, "There was a problem looking up your information.") 485 client.send_message(message.author, "There was a problem looking up your information.")
769 else: 486 else:
...@@ -790,7 +507,7 @@ Max Bet: 10 credits ...@@ -790,7 +507,7 @@ Max Bet: 10 credits
790 To Play: !slots <bet>""") 507 To Play: !slots <bet>""")
791 return 508 return
792 if message.content.startswith('!slots'): 509 if message.content.startswith('!slots'):
793 member = db_get_member(message.author.id) 510 member = data.db_get_member(message.author.id)
794 if not member: 511 if not member:
795 client.send_message(message.author, "There was a problem looking up your information.") 512 client.send_message(message.author, "There was a problem looking up your information.")
796 return 513 return
...@@ -803,7 +520,10 @@ To Play: !slots <bet>""") ...@@ -803,7 +520,10 @@ To Play: !slots <bet>""")
803 if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0: 520 if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0:
804 client.send_message(message.author, "Please provide a bet amount up to 10 credits.") 521 client.send_message(message.author, "Please provide a bet amount up to 10 credits.")
805 return 522 return
806 result, error_message = db_update_credit(member['member_id'], -int(bet_amount)) 523 result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
524 if not result:
525 client.send_message(message.author, error_message)
526 return
807 527
808 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:'] 528 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:']
809 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:'] 529 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:']
...@@ -838,30 +558,32 @@ To Play: !slots <bet>""") ...@@ -838,30 +558,32 @@ To Play: !slots <bet>""")
838 winnings = int(winnings * int(bet_amount)) 558 winnings = int(winnings * int(bet_amount))
839 if winnings > 0: 559 if winnings > 0:
840 out_string += "You Won! Total Winnings: {}".format(winnings,) 560 out_string += "You Won! Total Winnings: {}".format(winnings,)
561 log("Member: {} Wins: {}".format(member['member_name'], winnings))
562
841 else: 563 else:
842 out_string += "You lose. Total Winnings: {}".format(winnings,) 564 out_string += "You lose. Total Winnings: {}".format(winnings,)
843 if winnings > 0: 565 if winnings > 0:
844 result, error_message = db_update_credit(member['member_id'], winnings) 566 result, error_message = data.db_update_credit(member['member_id'], winnings)
845 if not result: 567 if not result:
846 client.send_message(message.author, error_message) 568 client.send_message(message.author, error_message)
847 return 569 return
848 570
849 credits = db_get_credit(member['member_id']) 571 credits = data.db_get_credit(member['member_id'])
850 out_string += "\nCredits: {}".format(credits) 572 out_string += "\nCredits: {}".format(credits)
851 573
852 log(out_string) 574 #log(out_string)
853 client.send_message(message.author, out_string) 575 client.send_message(message.author, out_string)
854 576
855 return 577 return
856 578
857 if message.content.startswith('!hit') or message.content.startswith('!draw'): 579 if message.content.startswith('!hit') or message.content.startswith('!draw'):
858 member = db_get_member(message.author.id) 580 member = data.db_get_member(message.author.id)
859 if not member: 581 if not member:
860 client.send_message(message.author, "There was a problem looking up your information.") 582 client.send_message(message.author, "There was a problem looking up your information.")
861 elif type(message.channel) is not discord.channel.PrivateChannel: 583 elif type(message.channel) is not discord.channel.PrivateChannel:
862 client.send_message(message.author, "You must make all bets / gaming via private message.") 584 client.send_message(message.author, "You must make all bets / gaming via private message.")
863 else: 585 else:
864 state = db_get_minigame_state(member['member_id'], 'blackjack') 586 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
865 if state: 587 if state:
866 out_string = "" 588 out_string = ""
867 bj = pickle.loads(str(state)) 589 bj = pickle.loads(str(state))
...@@ -870,18 +592,19 @@ To Play: !slots <bet>""") ...@@ -870,18 +592,19 @@ To Play: !slots <bet>""")
870 actions = bj.get_actions() 592 actions = bj.get_actions()
871 if len(actions) > 0: 593 if len(actions) > 0:
872 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions)) 594 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
873 db_add_minigame(member['member_id'], 'blackjack', bj.serialize()) 595 data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
874 else: 596 else:
875 win, response = bj.is_win() 597 win, response = bj.is_win()
876 out_string += "\n\n" + bj.print_hand(show_dealer=True) 598 out_string += "\n\n" + bj.print_hand(show_dealer=True)
877 out_string += "\n\n" + response.format(win,) 599 out_string += "\n\n" + response.format(win,)
878 db_delete_minigame_state(member['member_id'], 'blackjack') 600 data.db_delete_minigame_state(member['member_id'], 'blackjack')
879 result, error_message = db_update_credit(member['member_id'], int(win)) 601 log("{} - {}".format(member['member_name'], response.format(win,)))
602 result, error_message = data.db_update_credit(member['member_id'], int(win))
880 if not result: 603 if not result:
881 client.send_message(message.author, error_message) 604 client.send_message(message.author, error_message)
882 return 605 return
883 606
884 credits = db_get_credit(member['member_id']) 607 credits = data.db_get_credit(member['member_id'])
885 out_string += "\nCredits: {}".format(credits) 608 out_string += "\nCredits: {}".format(credits)
886 609
887 client.send_message(message.author, out_string) 610 client.send_message(message.author, out_string)
...@@ -891,13 +614,13 @@ To Play: !slots <bet>""") ...@@ -891,13 +614,13 @@ To Play: !slots <bet>""")
891 return 614 return
892 615
893 if message.content.startswith('!stay') or message.content.startswith('!stand'): 616 if message.content.startswith('!stay') or message.content.startswith('!stand'):
894 member = db_get_member(message.author.id) 617 member = data.db_get_member(message.author.id)
895 if not member: 618 if not member:
896 client.send_message(message.author, "There was a problem looking up your information.") 619 client.send_message(message.author, "There was a problem looking up your information.")
897 elif type(message.channel) is not discord.channel.PrivateChannel: 620 elif type(message.channel) is not discord.channel.PrivateChannel:
898 client.send_message(message.author, "You must make all bets / gaming via private message.") 621 client.send_message(message.author, "You must make all bets / gaming via private message.")
899 else: 622 else:
900 state = db_get_minigame_state(member['member_id'], 'blackjack') 623 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
901 if state: 624 if state:
902 out_string = "" 625 out_string = ""
903 bj = pickle.loads(str(state)) 626 bj = pickle.loads(str(state))
...@@ -905,24 +628,25 @@ To Play: !slots <bet>""") ...@@ -905,24 +628,25 @@ To Play: !slots <bet>""")
905 win, response = bj.is_win() 628 win, response = bj.is_win()
906 out_string += "\n\n" + bj.print_hand(show_dealer=True) 629 out_string += "\n\n" + bj.print_hand(show_dealer=True)
907 out_string += "\n\n" + response.format(win,) 630 out_string += "\n\n" + response.format(win,)
908 db_delete_minigame_state(member['member_id'], 'blackjack') 631 data.db_delete_minigame_state(member['member_id'], 'blackjack')
909 result, error_message = db_update_credit(member['member_id'], int(win)) 632 log("{} - {}".format(member['member_name'], response.format(win,)))
633 result, error_message = data.db_update_credit(member['member_id'], int(win))
910 if not result: 634 if not result:
911 client.send_message(message.author, error_message) 635 client.send_message(message.author, error_message)
912 return 636 return
913 credits = db_get_credit(member['member_id']) 637 credits = data.db_get_credit(member['member_id'])
914 out_string += "\nCredits: {}".format(credits) 638 out_string += "\nCredits: {}".format(credits)
915 client.send_message(message.author, out_string) 639 client.send_message(message.author, out_string)
916 return 640 return
917 641
918 if message.content.startswith('!bet'): 642 if message.content.startswith('!bet'):
919 member = db_get_member(message.author.id) 643 member = data.db_get_member(message.author.id)
920 if not member: 644 if not member:
921 client.send_message(message.author, "There was a problem looking up your information.") 645 client.send_message(message.author, "There was a problem looking up your information.")
922 elif type(message.channel) is not discord.channel.PrivateChannel: 646 elif type(message.channel) is not discord.channel.PrivateChannel:
923 client.send_message(message.author, "You must make all bets / gaming via private message.") 647 client.send_message(message.author, "You must make all bets / gaming via private message.")
924 else: 648 else:
925 state = db_get_minigame_state(member['member_id'], 'blackjack') 649 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
926 if state: 650 if state:
927 client.send_message(message.author, "You are already playing a game!") 651 client.send_message(message.author, "You are already playing a game!")
928 652
...@@ -932,17 +656,18 @@ To Play: !slots <bet>""") ...@@ -932,17 +656,18 @@ To Play: !slots <bet>""")
932 actions = bj.get_actions() 656 actions = bj.get_actions()
933 if len(actions) > 0: 657 if len(actions) > 0:
934 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions)) 658 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
935 db_add_minigame(member['member_id'], 'blackjack', bj.serialize()) 659 data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
936 else: 660 else:
937 win, response = bj.is_win() 661 win, response = bj.is_win()
938 out_string += "\n\n" + bj.print_hand(show_dealer=True) 662 out_string += "\n\n" + bj.print_hand(show_dealer=True)
939 out_string += "\n\n" + response.format(win,) 663 out_string += "\n\n" + response.format(win,)
940 db_delete_minigame_state(member['member_id'], 'blackjack') 664 data.db_delete_minigame_state(member['member_id'], 'blackjack')
941 result, error_message = db_update_credit(member['member_id'], int(win)) 665 log("{} - {}".format(member['member_name'], response.format(win,)))
666 result, error_message = data.db_update_credit(member['member_id'], int(win))
942 if not result: 667 if not result:
943 client.send_message(message.author, error_message) 668 client.send_message(message.author, error_message)
944 return 669 return
945 credits = db_get_credit(member['member_id']) 670 credits = data.db_get_credit(member['member_id'])
946 out_string += "\nCredits: {}".format(credits) 671 out_string += "\nCredits: {}".format(credits)
947 672
948 client.send_message(message.author, out_string) 673 client.send_message(message.author, out_string)
...@@ -957,7 +682,7 @@ To Play: !slots <bet>""") ...@@ -957,7 +682,7 @@ To Play: !slots <bet>""")
957 client.send_message(message.author, "Please provide a bet amount. !bet 10") 682 client.send_message(message.author, "Please provide a bet amount. !bet 10")
958 return 683 return
959 684
960 result, error_message = db_update_credit(member['member_id'], -int(bet_amount)) 685 result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
961 if not result: 686 if not result:
962 client.send_message(message.author, error_message) 687 client.send_message(message.author, error_message)
963 return 688 return
...@@ -967,17 +692,18 @@ To Play: !slots <bet>""") ...@@ -967,17 +692,18 @@ To Play: !slots <bet>""")
967 actions = bj.get_actions() 692 actions = bj.get_actions()
968 if len(actions) > 0: 693 if len(actions) > 0:
969 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions)) 694 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
970 db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj)) 695 data.db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
971 else: 696 else:
972 win, response = bj.is_win() 697 win, response = bj.is_win()
973 out_string += "\n\n" + bj.print_hand(show_dealer=True) 698 out_string += "\n\n" + bj.print_hand(show_dealer=True)
974 out_string += "\n\n" + response.format(win,) 699 out_string += "\n\n" + response.format(win,)
975 db_delete_minigame_state(member['member_id'], 'blackjack') 700 data.db_delete_minigame_state(member['member_id'], 'blackjack')
976 result, error_message = db_update_credit(member['member_id'], int(win)) 701 log("{} - {}".format(member['member_name'], response.format(win,)))
702 result, error_message = data.db_update_credit(member['member_id'], int(win))
977 if not result: 703 if not result:
978 client.send_message(message.author, error_message) 704 client.send_message(message.author, error_message)
979 return 705 return
980 credits = db_get_credit(member['member_id']) 706 credits = data.db_get_credit(member['member_id'])
981 out_string += "\nCredits: {}".format(credits) 707 out_string += "\nCredits: {}".format(credits)
982 708
983 client.send_message(message.author, out_string) 709 client.send_message(message.author, out_string)
...@@ -986,13 +712,6 @@ To Play: !slots <bet>""") ...@@ -986,13 +712,6 @@ To Play: !slots <bet>""")
986 712
987 # !msg joe in 5 minutes YOU ARE A DICK 713 # !msg joe in 5 minutes YOU ARE A DICK
988 if message.content.startswith('!msg'): 714 if message.content.startswith('!msg'):
989 try:
990 json_data=open(deliveries_file).read()
991 data = json.loads(json_data)
992 except ValueError:
993 data = {}
994 if not data:
995 data = {}
996 channel = message.channel 715 channel = message.channel
997 author = message.author 716 author = message.author
998 #author = message.author.name 717 #author = message.author.name
...@@ -1026,7 +745,7 @@ To Play: !slots <bet>""") ...@@ -1026,7 +745,7 @@ To Play: !slots <bet>""")
1026 user_mention = '' 745 user_mention = ''
1027 # TODO: have it look in the database. Do this AFTER on startup we add all users. 746 # TODO: have it look in the database. Do this AFTER on startup we add all users.
1028 for member in client.get_all_members(): 747 for member in client.get_all_members():
1029 print("MEMBER: %s" % member) 748 log("MEMBER: %s" % member)
1030 if username.lower() == member.name.lower(): 749 if username.lower() == member.name.lower():
1031 user_mention = member.mention() 750 user_mention = member.mention()
1032 user_id = member.id 751 user_id = member.id
...@@ -1036,18 +755,14 @@ To Play: !slots <bet>""") ...@@ -1036,18 +755,14 @@ To Play: !slots <bet>""")
1036 755
1037 msg_text = byteify(' '.join(message_bits[msg_idx:])) 756 msg_text = byteify(' '.join(message_bits[msg_idx:]))
1038 message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text} 757 message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
1039 print("Message: %s" % message) 758 log("Message: %s" % message)
1040 db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id) 759 data.db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
1041 # data[user_mention] = {}
1042 # data[user_mention][author.mention()] = message
1043 # jdata = json.dumps(data, ensure_ascii=False)
1044 # print("Data: %s" % data) 760 # print("Data: %s" % data)
1045 #test_ch = Object(channel.id) 761 #test_ch = Object(channel.id)
1046 #client.send_message(test_ch, 'Test Message {}.'.format(author)) 762 #client.send_message(test_ch, 'Test Message {}.'.format(author))
1047 except Exception as e: 763 except Exception as e:
1048 client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, e)) 764 client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, e))
1049 return 765 return
1050 # open(deliveries_file, 'wb+').write(jdata.encode('utf8'))
1051 if msg_datetime < datetime.datetime.now(): 766 if msg_datetime < datetime.datetime.now():
1052 client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention)) 767 client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
1053 else: 768 else:
...@@ -1065,9 +780,9 @@ To Play: !slots <bet>""") ...@@ -1065,9 +780,9 @@ To Play: !slots <bet>""")
1065 c = conn.cursor() 780 c = conn.cursor()
1066 c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added)) 781 c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
1067 conn.commit() 782 conn.commit()
1068 print("Added fortune") 783 log("Added fortune")
1069 except Exception as e: 784 except Exception as e:
1070 print e.message 785 log(e.message)
1071 client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention())) 786 client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
1072 return 787 return
1073 client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention())) 788 client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
...@@ -1078,9 +793,9 @@ To Play: !slots <bet>""") ...@@ -1078,9 +793,9 @@ To Play: !slots <bet>""")
1078 try: 793 try:
1079 c = conn.cursor() 794 c = conn.cursor()
1080 fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0] 795 fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
1081 print(fortune) 796 log(fortune)
1082 except Exception as e: 797 except Exception as e:
1083 print(e) 798 log(e)
1084 pass 799 pass
1085 if not fortune: 800 if not fortune:
1086 client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention())) 801 client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
...@@ -1106,14 +821,14 @@ To Play: !slots <bet>""") ...@@ -1106,14 +821,14 @@ To Play: !slots <bet>""")
1106 proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP'] 821 proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
1107 wiki_search = " ".join(proper_nouns) 822 wiki_search = " ".join(proper_nouns)
1108 if wiki_search.strip() != "": 823 if wiki_search.strip() != "":
1109 print "Looking up {}".format(wiki_search) 824 log("Looking up {}".format(wiki_search))
1110 wiki_out = wikipedia.summary(wiki_search, sentences=3) 825 wiki_out = wikipedia.summary(wiki_search, sentences=3)
1111 client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out))) 826 client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
1112 else: 827 else:
1113 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention())) 828 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
1114 return 829 return
1115 except Exception as e: 830 except Exception as e:
1116 print(format_exception(e)) 831 log(format_exception(e))
1117 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention())) 832 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
1118 return 833 return
1119 834
...@@ -1127,9 +842,9 @@ To Play: !slots <bet>""") ...@@ -1127,9 +842,9 @@ To Play: !slots <bet>""")
1127 c = conn.cursor() 842 c = conn.cursor()
1128 c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,)) 843 c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
1129 conn.commit() 844 conn.commit()
1130 print("Added joke") 845 log("Added joke")
1131 except Exception as e: 846 except Exception as e:
1132 print e.message 847 log(e.message)
1133 client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention())) 848 client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
1134 return 849 return
1135 client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention())) 850 client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
...@@ -1140,9 +855,9 @@ To Play: !slots <bet>""") ...@@ -1140,9 +855,9 @@ To Play: !slots <bet>""")
1140 try: 855 try:
1141 c = conn.cursor() 856 c = conn.cursor()
1142 joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0] 857 joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
1143 print(joke) 858 log(joke)
1144 except Exception as e: 859 except Exception as e:
1145 print(e) 860 log(e)
1146 pass 861 pass
1147 if not joke: 862 if not joke:
1148 client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention())) 863 client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
...@@ -1162,16 +877,22 @@ To Play: !slots <bet>""") ...@@ -1162,16 +877,22 @@ To Play: !slots <bet>""")
1162 if message.content.startswith('!hello'): 877 if message.content.startswith('!hello'):
1163 client.send_message(message.channel, 'Hello {}!'.format(message.author.mention())) 878 client.send_message(message.channel, 'Hello {}!'.format(message.author.mention()))
1164 879
1165 if message.content.startswith('!deal'): 880 if message.content.startswith('!reloadbot'):
1166 client.send_message(message.channel, 'You get {}!'.format(message.author.mention())) 881 if message.author.id != '78767557628133376':
882 client.send_message(message.channel, "You shouldn't be calling this. You are clearly looking to piss Hellsbreath off.")
883 return
884 call(["service", "hellsbot", "restart"])
885
1167 886
1168 @client.event 887 @client.event
1169 def on_ready(): 888 def on_ready():
1170 print('Logged in as') 889 log('Logged in as')
1171 print(client.user.name) 890 log(client.user.name)
1172 print(client.user.id) 891 log(client.user.id)
1173 print('------') 892 log('------')
1174 893 for member in client.get_all_members():
894 if member.id == '78767557628133376':
895 client.send_message(member, "Bot Started")
1175 check_msg_queue() 896 check_msg_queue()
1176 897
1177 retries = 0 898 retries = 0
...@@ -1185,6 +906,7 @@ while retries < 1000: ...@@ -1185,6 +906,7 @@ while retries < 1000:
1185 except KeyboardInterrupt: 906 except KeyboardInterrupt:
1186 conn.close 907 conn.close
1187 quit() 908 quit()
1188 except: 909 except Exception as e:
1189 retries += 1 910 retries += 1
1190 print("Shit I crashed: Retry %s" % (retries,)) 911 log("Shit I crashed: {}\nRetry {}".format(e, retries))
912 #time.sleep(1)
......
...@@ -119,7 +119,7 @@ class Pankration: ...@@ -119,7 +119,7 @@ class Pankration:
119 return monster_list 119 return monster_list
120 120
121 def hunt_monster(self, zone): 121 def hunt_monster(self, zone):
122 if random.randint(1, 100) > FIND_PERCENTAGE: 122 if random.randint(1, 100) < FIND_PERCENTAGE:
123 return HuntResponse(HuntResponse.SUCCESS, "You captured the monster!", 123 return HuntResponse(HuntResponse.SUCCESS, "You captured the monster!",
124 random.choice(self.get_monsters(zone))) 124 random.choice(self.get_monsters(zone)))
125 else: 125 else:
......