4264acb8 by Barry

Refactored the way messages are processed. Added new raffle.

1 parent 771720d3
1 import operator
1 import sqlite3 2 import sqlite3
3 import datetime
2 4
3 conn = sqlite3.connect('db.sqlite3') 5 conn = sqlite3.connect('db.sqlite3')
4 6
5 def log(message): 7 def log(message):
6 logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message)) 8 try:
9 logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
10 except:
11 pass
7 12
8 ################## 13 ##################
9 ## Database Calls 14 ## Database Calls
......
No preview for this file type
...@@ -4,8 +4,8 @@ import requests ...@@ -4,8 +4,8 @@ import requests
4 import discord 4 import discord
5 import random 5 import random
6 import datetime 6 import datetime
7 import time
7 import re 8 import re
8 import operator
9 import pickle 9 import pickle
10 import logging 10 import logging
11 11
...@@ -39,12 +39,48 @@ client = discord.Client() ...@@ -39,12 +39,48 @@ client = discord.Client()
39 wolf = {} 39 wolf = {}
40 logging.basicConfig(filename='hellsbot.log',level=logging.WARNING) 40 logging.basicConfig(filename='hellsbot.log',level=logging.WARNING)
41 41
42 registered_commands = {'!help': 'do_help', '!commands': 'do_help',
43 '!shutup': 'do_shutup',
44 '!roll': 'do_roll',
45 '!lastseen': 'do_lastseen',
46 '!youtube': 'do_youtube',
47 '!image': 'do_image',
48 '!gif': 'do_gif',
49 '!gameslist': 'do_gameslist', '!gamelist': 'do_gameslist',
50 '!aliases': 'do_alias', '!alias': 'do_alias',
51 '!addalias': 'do_addalias',
52 '!games': 'do_games',
53 '!reloadbot': 'do_reload', '!restartbot': 'do_reload', '!rebootbot': 'do_reload',
54 '!whoplayed': 'do_whoplayed',
55 '!gimmecredits': 'do_gimmecredits', '!gimmecredit': 'do_gimmecredits',
56 '!grantcredits': 'do_grantcredits',
57 '!ticketrank': 'do_ticketrank',
58 '!startraffle': 'do_startraffle',
59 '!raffle': 'do_raffle',
60 '!buyticket': 'do_buyticket',
61 '!balance': 'do_balance',
62 '!slotsrules': 'do_slotsrules',
63 '!slots': 'do_slots',
64 '!hit': 'do_bj_hit', '!draw': 'do_bj_hit',
65 '!stay': 'do_bj_stay', '!stand': 'do_bj_stay',
66 '!bet': 'do_bj_bet',
67 '!msg': 'do_msg',
68 '!addfortune': 'do_addfortune',
69 '!fortune': 'do_fortune',
70 '!question': 'do_question',
71 '!addjoke': 'do_addjoke',
72 '!joke': 'do_joke',
73 }
74
42 ##################### 75 #####################
43 ## Utility Functions 76 ## Utility Functions
44 ##################### 77 #####################
45 78
46 def log(message): 79 def log(message):
47 logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message)) 80 try:
81 logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
82 except:
83 pass
48 84
49 def format_exception(e): 85 def format_exception(e):
50 exception_list = traceback.format_stack() 86 exception_list = traceback.format_stack()
...@@ -145,30 +181,60 @@ def check_msg_queue(): ...@@ -145,30 +181,60 @@ def check_msg_queue():
145 log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],)) 181 log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],))
146 return 182 return
147 183
148 @client.event 184 def do_roll(client, message_parts, message):
149 def on_message(message): 185 request = message_parts[0]
150 #print message.content 186 count = 1
151 #print message.author 187 dice = 100
152 #print client.user 188 if request.strip() != '':
153 global muted_until 189 if 'd' in request:
154 # we do not want the bot to reply to itself 190 dice_parts = request.split('d')
155 if message.author == client.user: 191 if len(dice_parts) == 2:
192 if dice_parts[0].isdigit() and dice_parts[1].isdigit():
193 count = int(dice_parts[0])
194 dice = int(dice_parts[1])
195 if count > 100000000000000000:
196 client.send_message(message.channel, '{} stop fucking around with those stupid numbers...'.format(message.author.mention()))
156 return 197 return
157 198
158 if message.content.lower().startswith(client.user.name.lower()): 199 if count > 100:
159 log('Someone is talking to %s' % (client.user.name.lower(),)) 200 client.send_message(message.channel, '{} 100 is the largest number of dice I will roll.'.format(message.author.mention()))
160 if ' or ' in message.content: 201 return
161 questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ') 202 roll_results = []
162 client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore'))) 203 for i in range(count):
204 roll_results.append(random.randint(1,dice))
205 out_string = '{} your roll {}d{}: {} = {}'.format(message.author.mention(), count, dice, '+'.join(str(r) for r in roll_results), sum(roll_results))
206 client.send_message(message.channel, out_string)
207 return
208
209 def do_lastseen(client, message_parts, message):
210 username = ' '.join(message_parts).replace('@', '').lower()
211 member = data.db_get_member(username=username)
212 #log(member)
213 if member:
214 out_string = ''
215 if member['is_afk'] == 1:
216 out_string = 'Went AFK at: {}\n'.format(member['afk_at'])
217 elif member['status'] == 'offline':
218 out_string = 'Currently Offline\n'
219 else:
220 out_string = 'Currently Online\n'
221 out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(member['status'],
222 member['status_change_at'],
223 human(datetime.datetime.strptime(member['status_change_at'], '%Y/%m/%d %H:%M:%S')),
224 member['prev_status'])
163 225
226 client.send_message(message.channel, 'Last Information on {}:\n{}'.format(byteify(username), out_string))
227 else:
228 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(username), message.author.mention()))
229 return
164 230
165 if message.content.startswith('!help') or message.content.startswith('!commands'): 231 def do_help(client, message_parts, message):
166 client.send_message(message.channel, 232 client.send_message(message.channel,
167 """{} Available Commands: 233 """{} Available Commands:
168 You can ask compound or questions and I will choose. Example: HellsBot Rui is a Faggot or Rui is a faggot? 234 You can ask compound or questions and I will choose. Example: HellsBot Rui is a Faggot or Rui is a faggot?
169 235
170 User Info: 236 User Info:
171 !aliases - Returns a list of all aliases a user has set for themselves. 237 !aliases <username> - Returns a list of all aliases a user has set for themselves.
172 !addalias <alias> - Adds an alias to your list of aliases. 238 !addalias <alias> - Adds an alias to your list of aliases.
173 !lastseen <username> - Returns info on when the user was last seen and their status. 239 !lastseen <username> - Returns info on when the user was last seen and their status.
174 Messages: 240 Messages:
...@@ -203,251 +269,215 @@ Stuff: ...@@ -203,251 +269,215 @@ Stuff:
203 !joke - Returns a random joke. 269 !joke - Returns a random joke.
204 !roll <1d20> - Roll X number of dice of size X. 1d20 returns 1 roll 1-20. 3d6 returns 3 rolls of 1-6 etc... 270 !roll <1d20> - Roll X number of dice of size X. 1d20 returns 1 roll 1-20. 3d6 returns 3 rolls of 1-6 etc...
205 !secret 271 !secret
206 !shutup - disables all image / gif / youtube span for 5 minutes 272 !shutup - disables all image / gif / youtube spam for 5 minutes
207 !bemyirlwaifu""".format(message.author.mention())) 273 !bemyirlwaifu""".format(message.author.mention()))
208 return
209 274
210 if message.content.startswith('!lastseen'): 275 def do_shutup(client, message_parts, message):
211 username = message.content[10:].replace('@', '').lower() 276 muted_until = datetime.datetime.now() + datetime.timedelta(minutes=5)
212 member = data.db_get_member(username=username) 277 client.send_message(message.channel, 'All image / gif / youtube spam disabled for 5 minutes')
213 #log(member) 278 return
214 if member:
215 out_string = ''
216 if member['is_afk'] == 1:
217 out_string = 'Went AFK at: {}\n'.format(member['afk_at'])
218 elif member['status'] == 'offline':
219 out_string = 'Currently Offline\n'
220 else:
221 out_string = 'Currently Online\n'
222 out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(member['status'],
223 member['status_change_at'],
224 human(datetime.datetime.strptime(member['status_change_at'], '%Y/%m/%d %H:%M:%S')),
225 member['prev_status'])
226 279
227 client.send_message(message.channel, 'Last Information on {}:\n{}'.format(username, out_string)) 280 def do_youtube(client, message_parts, message):
228 else: 281 if datetime.datetime.now() < muted_until:
229 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))
230 return 282 return
283 client.send_message(message.channel, search_youtube(' '.join(message_parts)))
284 return
231 285
232 if message.content.startswith('!shutup'): 286 def do_image(client, message_parts, message):
233 muted_until = datetime.datetime.now() + datetime.timedelta(minutes=5) 287 if datetime.datetime.now() < muted_until:
234 client.send_message(message.channel, search_youtube(query))
235 return 288 return
289 client.send_message(message.channel, search_google_images(' '.join(message_parts)))
290 return
236 291
237 if message.content.startswith('!youtube'): 292 def do_gif(client, message_parts, message):
238 if datetime.datetime.now() < muted_until: 293 if datetime.datetime.now() < muted_until:
239 return
240 query = message.content[9:]
241 client.send_message(message.channel, search_youtube(query))
242 return 294 return
295 client.send_message(message.channel, search_google_images(' '.join(message_parts), True))
296 return
243 297
244 if message.content.startswith('!image'): 298 def do_gameslist(client, message_parts, message):
245 if datetime.datetime.now() < muted_until: 299 limit = 20
246 return 300 if len(message_parts) > 0 and message_parts[0].isdigit():
247 query = message.content[7:] 301 limit = int(message_parts[0])
248 client.send_message(message.channel, search_google_images(query)) 302 games_list = data.db_get_games_list(limit)
249 return 303
304 out_string = ''
305 for game in games_list:
306 out_string += ' {} - {}\n'.format(game[1], byteify(game[0]))
307 client.send_message(message.channel, 'The games I have seen people playing are: ')
308 while len(out_string) > 0:
309 client.send_message(message.channel, out_string[:1900])
310 out_string = out_string[1900:]
311 return
250 312
251 if message.content.startswith('!gif'): 313 def do_alias(client, message_parts, message):
252 if datetime.datetime.now() < muted_until: 314 if len(message_parts) > 0:
253 return 315 username = ' '.join(message_parts).replace('@', '').lower()
254 query = message.content[7:] 316 member = data.db_get_member(username=username)
255 client.send_message(message.channel, search_google_images(query, True)) 317 else:
256 return 318 username = message.author.name
319 member = data.db_get_member(message.author.id)
320 if member:
321 aliases = data.db_get_aliases(member['member_id'])
322 if aliases:
323 client.send_message(message.channel, '{} has the following aliases: {}'.format(byteify(username), byteify(', '.join(aliases))))
324 else:
325 client.send_message(message.channel, 'No known alises for {} yet {}'.format(byteify(username), message.author.mention()))
326 else:
327 client.send_message(message.channel, 'I don\'t know who you are speaking of {}!'.format(message.author.mention()))
328 return
257 329
258 if message.content.startswith('!roll'): 330 def do_addalias(client, message_parts, message):
259 request = message.content[6:] 331 alias = ' '.join(message_parts)
260 count = 1 332 username = message.author.name.lower()
261 dice = 100 333 member = data.db_get_member(username=username)
262 if request.strip() != '': 334 if member:
263 if 'd' in request: 335 data.db_add_aliases(member['member_id'], alias)
264 dice_parts = request.split('d') 336 client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias)))
265 if len(dice_parts) == 2: 337 else:
266 if dice_parts[0].isdigit() and dice_parts[1].isdigit(): 338 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...)')
267 count = int(dice_parts[0]) 339 return
268 dice = int(dice_parts[1])
269 if count > 100000000000000000:
270 client.send_message(message.channel, '{} stop fucking around with those stupid numbers...'.format(message.author.mention()))
271 return
272 340
273 if count > 100: 341 def do_games(client, message_parts, message):
274 client.send_message(message.channel, '{} 100 is the largest number of dice I will roll.'.format(message.author.mention())) 342 if len(message_parts) > 0:
275 return 343 username = ' '.join(message_parts).replace('@', '').lower()
276 roll_results = [] 344 else:
277 for i in range(count): 345 username = message.author.name
278 roll_results.append(random.randint(1,dice)) 346 games_list = data.db_get_games(username)
279 out_string = '{} your roll {}d{}: {} = {}'.format(message.author.mention(), count, dice, '+'.join(str(r) for r in roll_results), sum(roll_results)) 347 if games_list:
280 client.send_message(message.channel, out_string) 348 games = ', '.join(games_list)
281 return 349 games = games.replace("FINAL FANTASY XIV", "**FINAL FANTASY XIV**")
350 log(byteify(games))
351 client.send_message(message.channel, 'I have seen {} playing: {}'.format(byteify(username), byteify(games)))
352 else:
353 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(username), message.author.mention()))
282 354
283 if message.content.startswith('!gameslist') or message.content.startswith('!gamelist') : 355 def do_reload(client, message_parts, message):
284 parts = message.content.split(' ') 356 if message.author.id != '78767557628133376':
285 limit = 20 357 client.send_message(message.channel, "You shouldn't be calling this. You are clearly looking to piss Hellsbreath off.")
286 if len(parts) > 1 and parts[1].isdigit(): 358 return
287 limit = int(parts[1]) 359 call(["service", "hellsbot", "restart"])
288 games_list = data.db_get_games_list(limit)
289 360
361 def do_whoplayed(client, message_parts, message):
362 game_name = ' '.join(message_parts)
363 member_list = data.db_get_whoplayed(game_name)
364 if not member_list:
365 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
366 else:
290 out_string = '' 367 out_string = ''
291 for game in games_list: 368 for member in member_list:
292 out_string += ' {} - {}\n'.format(game[1], byteify(game[0])) 369 out_string += ' {} - {}\n'.format(byteify(member[1]), byteify(member[0]))
293 client.send_message(message.channel, 'The games I have seen people playing are: ') 370 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),))
294 while len(out_string) > 0: 371 while len(out_string) > 0:
295 client.send_message(message.channel, out_string[:1900]) 372 client.send_message(message.channel, out_string[:1900])
296 out_string = out_string[1900:] 373 out_string = out_string[1900:]
374 return
297 375
298 return 376 def do_gimmecredits(client, message_parts, message):
299 377 member = data.db_get_member(message.author.id)
300 if message.content.startswith('!aliases'): 378 if not member:
301 username = message.content[9:].replace('@', '').lower() 379 client.send_message(message.author, "There was a problem looking up your information.")
302 member = data.db_get_member(username=username) 380 else:
303 if member: 381 credits = data.db_get_credit(member['member_id'])
304 aliases = data.db_get_aliases(member['member_id']) 382 if credits < 5:
305 if aliases: 383 amount = random.randint(5, 50)
306 client.send_message(message.channel, '{} has the following aliases: {}'.format(username, byteify(', '.join(aliases)))) 384 data.db_update_credit(member['member_id'], amount)
307 else: 385 client.send_message(message.author, "You have been given {} credits.".format(amount,))
308 client.send_message(message.channel, 'No known alises for {} yet {}'.format(username, message.author.mention()))
309 else:
310 client.send_message(message.channel, 'I don\'t know who you are speaking of {}!'.format(message.author.mention()))
311 return
312
313 if message.content.startswith('!addalias'):
314 alias = message.content[10:]
315 username = message.author.name.lower()
316 member = data.db_get_member(username=username)
317 if member:
318 data.db_add_aliases(member['member_id'], alias)
319 client.send_message(message.channel, '{} has been added to your aliases'.format(byteify(alias)))
320 else:
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...)')
322 return
323
324 if message.content.startswith('!games'):
325 username = message.content[7:].replace('@', '').lower()
326 games_list = data.db_get_games(username)
327 if games_list:
328 games = ', '.join(games_list)
329 client.send_message(message.channel, 'I have seen {} playing: {}'.format(username, games))
330 else: 386 else:
331 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention())) 387 client.send_message(message.author, "You already have credits. Stop begging.")
388 return
332 389
333 if message.content.startswith('!whoplayed'): 390 def do_grantcredits(clients, message_parts, message):
334 game_name = message.content[11:] 391 if message.author.id != '78767557628133376':
335 member_list = data.db_get_whoplayed(game_name) 392 client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
336 if not member_list:
337 client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
338 else:
339 out_string = ''
340 for member in member_list:
341 out_string += ' {} - {}\n'.format(byteify(member[1]), byteify(member[0]))
342 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),))
343 while len(out_string) > 0:
344 client.send_message(message.channel, out_string[:1900])
345 out_string = out_string[1900:]
346 return 393 return
347 394 members = data.db_get_all_members()
348 if message.content.startswith('!gimmecredits'): 395 if len(members) < 0:
349 member = data.db_get_member(message.author.id) 396 client.send_message(message.channel, "There was a problem looking up your information.")
350 if not member: 397 else:
351 client.send_message(message.author, "There was a problem looking up your information.") 398 for member in members:
352 else:
353 credits = data.db_get_credit(member['member_id']) 399 credits = data.db_get_credit(member['member_id'])
354 if credits < 5: 400 if credits < 100:
355 amount = random.randint(5, 50) 401 data.db_update_credit(member['member_id'], 100)
356 data.db_update_credit(member['member_id'], amount) 402 client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
357 client.send_message(message.author, "You have been given {} credits.".format(amount,)) 403 return
358 else:
359 client.send_message(message.author, "You already have credits. Stop begging.")
360 return
361 404
362 if message.content.startswith('!grantcredits'): 405 def do_ticketrank(clients, message_parts, message):
363 if message.author.id != '78767557628133376': 406 members = data.db_get_all_members()
364 client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.") 407 if len(members) < 0:
408 client.send_message(message.channel, "There was a problem looking up your information.")
409 else:
410 ticket_count = 0
411 for member in members:
412 if member['discord_id'] != '78767557628133376':
413 #log(member)
414 ticket_count += member['tickets']
415 if ticket_count == 0:
416 client.send_message(message.channel, "No Tickets have been sold for this raffle.")
365 return 417 return
366 members = data.db_get_all_members()
367 if len(members) < 0:
368 client.send_message(message.channel, "There was a problem looking up your information.")
369 else:
370 for member in members:
371 credits = data.db_get_credit(member['member_id'])
372 if credits < 100:
373 data.db_update_credit(member['member_id'], 100)
374 client.send_message(message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
375 return
376 418
377 if message.content.startswith('!ticketrank'): 419 #log("Ticket Count: {}".format(ticket_count))
378 # if message.author.id != '78767557628133376': 420 out_string = ""
379 # client.send_message(message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.") 421 for member in members:
380 # return 422 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
381 members = data.db_get_all_members() 423 percent = (float(member['tickets']) / float(ticket_count)) * 100.0
382 if len(members) < 0: 424 out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
383 client.send_message(message.channel, "There was a problem looking up your information.")
384 else:
385 ticket_count = 0
386 for member in members:
387 if member['discord_id'] != '78767557628133376':
388 #log(member)
389 ticket_count += member['tickets']
390 if ticket_count == 0:
391 client.send_message(message.channel, "No Tickets have been sold for this raffle.")
392 return
393 425
394 #log("Ticket Count: {}".format(ticket_count)) 426 client.send_message(message.channel, out_string)
395 out_string = "" 427 return
396 for member in members:
397 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
398 percent = (float(member['tickets']) / float(ticket_count)) * 100.0
399 out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
400 428
401 client.send_message(message.channel, out_string) 429 def do_startraffle(client, message_parts, message):
430 if message.author.id != '78767557628133376':
431 client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.")
402 return 432 return
403 433 members = data.db_get_all_members()
404 if message.content.startswith('!startraffle'): 434 if len(members) < 0:
405 if message.author.id != '78767557628133376': 435 client.send_message(message.channel, "There was a problem looking up your information.")
406 client.send_message(message.channel, "You are not Hellsbreath. Go die in an especially hot fire.") 436 else:
437 ticket_count = 0
438 for member in members:
439 if member['discord_id'] != '78767557628133376':
440 #log(member)
441 ticket_count += member['tickets']
442 if ticket_count == 0:
443 client.send_message(message.channel, "No Tickets have been sold for this raffle.")
407 return 444 return
408 members = data.db_get_all_members()
409 if len(members) < 0:
410 client.send_message(message.channel, "There was a problem looking up your information.")
411 else:
412 ticket_count = 0
413 for member in members:
414 if member['discord_id'] != '78767557628133376':
415 #log(member)
416 ticket_count += member['tickets']
417 if ticket_count == 0:
418 client.send_message(message.channel, "No Tickets have been sold for this raffle.")
419 return
420 445
421 #log("Ticket Count: {}".format(ticket_count)) 446 #log("Ticket Count: {}".format(ticket_count))
422 out_string = "The final standings are as follows: \n\n" 447 out_string = "The final standings are as follows: \n\n"
423 ticket_reel = [] 448 ticket_reel = []
424 for member in members: 449 for member in members:
425 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376': 450 if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
426 ticket_reel += [member['discord_mention']] * member['tickets'] 451 ticket_reel += [member['discord_mention']] * member['tickets']
427 percent = (float(member['tickets']) / float(ticket_count)) * 100.0 452 percent = (float(member['tickets']) / float(ticket_count)) * 100.0
428 out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent)) 453 out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))
454 if len(ticket_reel) > 0:
429 winner = random.choice(ticket_reel) 455 winner = random.choice(ticket_reel)
430 while winner in ticket_reel: 456 while winner in ticket_reel:
431 ticket_reel.remove(winner) 457 ticket_reel.remove(winner)
458 client.send_message(message.channel, "\n\n\n**The winner is....\n\n{}!**".format(byteify(winner)))
459 if len(ticket_reel) > 0:
432 second = random.choice(ticket_reel) 460 second = random.choice(ticket_reel)
433 while second in ticket_reel: 461 while second in ticket_reel:
434 ticket_reel.remove(second) 462 ticket_reel.remove(second)
463 time.sleep(0.5)
464 client.send_message(message.channel, "\n\n*2nd Place:* {}".format(byteify(winner)))
465 if len(ticket_reel) > 0:
435 third = random.choice(ticket_reel) 466 third = random.choice(ticket_reel)
467 time.sleep(0.5)
468 client.send_message(message.channel, "\n*3rd Place:* {}".format(byteify(winner)))
469 return
436 470
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)) 471 def do_raffle(client, message_parts, message):
438 client.send_message(message.channel, byteify(out_string)) 472 client.send_message(message.channel, """Current Raffle Item:
439 return
440
441 if message.content.startswith('!raffle'):
442 client.send_message(message.channel, """Current Raffle Item:
443 473
444 **1st Place** 474 **1st Place**
445 475
446 Game: **Fairy Fencer F** 476 Game: **Lightning Returns**
447 Description: 477 Description:
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!* 478 *Lightning Returns is the concluding chapter of the Final Fantasy XIII saga and series heroine Lightning's final battle. The grand finale of the trilogy brings a world reborn as well as free character customization and stunning action based battles.*
449 479
450 http://store.steampowered.com/app/347830/ 480 http://store.steampowered.com/app/345350/
451 481
452 **2nd Place** 482 **2nd Place**
453 483
...@@ -457,38 +487,39 @@ http://store.steampowered.com/app/347830/ ...@@ -457,38 +487,39 @@ http://store.steampowered.com/app/347830/
457 487
458 1 Random Steam Key 488 1 Random Steam Key
459 489
460 Raffle Date: **2/2/2016 00:00:00 (ish)** 490 Raffle Date: **2/9/2016 00:00:00 (ish)**
461 491
462 You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits. 492 You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits.
463 You can get extra credits by playing !slots <amount> and !bet <amount> on BlackJack. 493 You can get extra credits by playing !slots <amount> and !bet <amount> on BlackJack.
464 494
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.* 495 **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.*
466 """) 496 """)
467 return 497 return
468 if message.content.startswith('!buyticket'):
469 member = data.db_get_member(message.author.id)
470 if not member:
471 client.send_message(message.author, "There was a problem looking up your information.")
472 else:
473 result, response = data.db_buy_ticket(member['member_id'], 1)
474 if not result:
475 client.send_message(message.author, response)
476 return
477 498
478 credits = data.db_get_credit(member['member_id']) 499 def do_buyticket(client, message_parts, message):
479 client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits)) 500 member = data.db_get_member(message.author.id)
480 return 501 if not member:
502 client.send_message(message.author, "There was a problem looking up your information.")
503 else:
504 result, response = data.db_buy_ticket(member['member_id'], 1)
505 if not result:
506 client.send_message(message.author, response)
507 return
481 508
482 if message.content.startswith('!balance'): 509 credits = data.db_get_credit(member['member_id'])
483 member = data.db_get_member(message.author.id) 510 client.send_message(message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
484 if not member: 511 return
485 client.send_message(message.author, "There was a problem looking up your information.") 512
486 else: 513 def do_balance(client, message_parts, message):
487 client.send_message(message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets'])) 514 member = data.db_get_member(message.author.id)
488 return 515 if not member:
516 client.send_message(message.author, "There was a problem looking up your information.")
517 else:
518 client.send_message(message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets']))
519 return
489 520
490 if message.content.startswith('!slotsrules'): 521 def do_slotsrules(client, message_parts, message):
491 client.send_message(message.channel, """Paying Combinations: 522 client.send_message(message.channel, """Paying Combinations:
492 523
493 :moneybag:\t:moneybag:\t:moneybag:\t\t\t pays\t250 524 :moneybag:\t:moneybag:\t:moneybag:\t\t\t pays\t250
494 :bell:\t:bell:\t:bell:/:moneybag:\tpays\t20 525 :bell:\t:bell:\t:bell:/:moneybag:\tpays\t20
...@@ -505,126 +536,94 @@ All payouts are in credits. Each pull costs 1 credit. ...@@ -505,126 +536,94 @@ All payouts are in credits. Each pull costs 1 credit.
505 Max Bet: 10 credits 536 Max Bet: 10 credits
506 537
507 To Play: !slots <bet>""") 538 To Play: !slots <bet>""")
539 return
540
541 def do_slots(client, message_parts, message):
542 member = data.db_get_member(message.author.id)
543 if not member:
544 client.send_message(message.author, "There was a problem looking up your information.")
508 return 545 return
509 if message.content.startswith('!slots'): 546 elif type(message.channel) is not discord.channel.PrivateChannel:
510 member = data.db_get_member(message.author.id) 547 client.send_message(message.author, "You must make all bets / gaming via private message.")
511 if not member: 548 return
512 client.send_message(message.author, "There was a problem looking up your information.") 549 bet_amount = message.content[7:]
513 return 550 log("Member: {} Slots Bet: {}".format(member['member_name'], bet_amount))
514 elif type(message.channel) is not discord.channel.PrivateChannel:
515 client.send_message(message.author, "You must make all bets / gaming via private message.")
516 return
517 bet_amount = message.content[7:]
518 log("Member: {} Slots Bet: {}".format(member['member_name'], bet_amount))
519 551
520 if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0: 552 if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0:
521 client.send_message(message.author, "Please provide a bet amount up to 10 credits.") 553 client.send_message(message.author, "Please provide a bet amount up to 10 credits.")
522 return 554 return
523 result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount)) 555 result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
556 if not result:
557 client.send_message(message.author, error_message)
558 return
559
560 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:']
561 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:']
562 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:']
563 #:moneybag: :bell: :diamonds: :spades: :hearts:
564 val1 = random.choice(reel1)
565 val2 = random.choice(reel2)
566 val3 = random.choice(reel3)
567 winnings = 0
568 reels = [val1, val2, val3]
569 cherries = reels.count(":cherries:")
570 spades = reels.count(":spades:")
571 diamonds = reels.count(":diamonds:")
572 bells = reels.count(":bell:")
573 moneybags = reels.count(":moneybag:")
574 if moneybags == 3:
575 out_string += "JACKPOT!!"
576 winnings = 250
577 elif bells == 3 or (bells == 2 and moneybags == 1):
578 winnings = 20
579 elif diamonds == 3 or (diamonds == 2 and moneybags == 1):
580 winnings = 14
581 elif spades == 3 or (spades == 2 and moneybags == 1):
582 winnings = 10
583 elif cherries == 3:
584 winnings = 7
585 elif cherries == 2:
586 winnings = 5
587 elif cherries == 1:
588 winnings = 2
589 out_string = """| {} | {} | {} |\n\n""".format(val1, val2, val3)
590 winnings = int(winnings * int(bet_amount))
591 if winnings > 0:
592 out_string += "You Won! Total Winnings: {}".format(winnings,)
593 log("Member: {} Wins: {}".format(member['member_name'], winnings))
594
595 else:
596 out_string += "You lose. Total Winnings: {}".format(winnings,)
597 if winnings > 0:
598 result, error_message = data.db_update_credit(member['member_id'], winnings)
524 if not result: 599 if not result:
525 client.send_message(message.author, error_message) 600 client.send_message(message.author, error_message)
526 return 601 return
527 602
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:'] 603 credits = data.db_get_credit(member['member_id'])
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:'] 604 out_string += "\nCredits: {}".format(credits)
530 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:']
531 #:moneybag: :bell: :diamonds: :spades: :hearts:
532 val1 = random.choice(reel1)
533 val2 = random.choice(reel2)
534 val3 = random.choice(reel3)
535 winnings = 0
536 reels = [val1, val2, val3]
537 cherries = reels.count(":cherries:")
538 spades = reels.count(":spades:")
539 diamonds = reels.count(":diamonds:")
540 bells = reels.count(":bell:")
541 moneybags = reels.count(":moneybag:")
542 if moneybags == 3:
543 out_string += "JACKPOT!!"
544 winnings = 250
545 elif bells == 3 or (bells == 2 and moneybags == 1):
546 winnings = 20
547 elif diamonds == 3 or (diamonds == 2 and moneybags == 1):
548 winnings = 14
549 elif spades == 3 or (spades == 2 and moneybags == 1):
550 winnings = 10
551 elif cherries == 3:
552 winnings = 7
553 elif cherries == 2:
554 winnings = 5
555 elif cherries == 1:
556 winnings = 2
557 out_string = """| {} | {} | {} |\n\n""".format(val1, val2, val3)
558 winnings = int(winnings * int(bet_amount))
559 if winnings > 0:
560 out_string += "You Won! Total Winnings: {}".format(winnings,)
561 log("Member: {} Wins: {}".format(member['member_name'], winnings))
562
563 else:
564 out_string += "You lose. Total Winnings: {}".format(winnings,)
565 if winnings > 0:
566 result, error_message = data.db_update_credit(member['member_id'], winnings)
567 if not result:
568 client.send_message(message.author, error_message)
569 return
570
571 credits = data.db_get_credit(member['member_id'])
572 out_string += "\nCredits: {}".format(credits)
573
574 #log(out_string)
575 client.send_message(message.author, out_string)
576
577 return
578 605
579 if message.content.startswith('!hit') or message.content.startswith('!draw'): 606 client.send_message(message.author, out_string)
580 member = data.db_get_member(message.author.id) 607 return
581 if not member:
582 client.send_message(message.author, "There was a problem looking up your information.")
583 elif type(message.channel) is not discord.channel.PrivateChannel:
584 client.send_message(message.author, "You must make all bets / gaming via private message.")
585 else:
586 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
587 if state:
588 out_string = ""
589 bj = pickle.loads(str(state))
590 bj.draw()
591 out_string += bj.print_hand()
592 actions = bj.get_actions()
593 if len(actions) > 0:
594 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
595 data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
596 else:
597 win, response = bj.is_win()
598 out_string += "\n\n" + bj.print_hand(show_dealer=True)
599 out_string += "\n\n" + response.format(win,)
600 data.db_delete_minigame_state(member['member_id'], 'blackjack')
601 log("{} - {}".format(member['member_name'], response.format(win,)))
602 result, error_message = data.db_update_credit(member['member_id'], int(win))
603 if not result:
604 client.send_message(message.author, error_message)
605 return
606
607 credits = data.db_get_credit(member['member_id'])
608 out_string += "\nCredits: {}".format(credits)
609
610 client.send_message(message.author, out_string)
611 608
609 def do_bj_hit(client, message_parts, message):
610 member = data.db_get_member(message.author.id)
611 if not member:
612 client.send_message(message.author, "There was a problem looking up your information.")
613 elif type(message.channel) is not discord.channel.PrivateChannel:
614 client.send_message(message.author, "You must make all bets / gaming via private message.")
615 else:
616 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
617 if state:
618 out_string = ""
619 bj = pickle.loads(str(state))
620 bj.draw()
621 out_string += bj.print_hand()
622 actions = bj.get_actions()
623 if len(actions) > 0:
624 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
625 data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
612 else: 626 else:
613 client.send_message(message.author, "You must start a game with !bet before you can ask for a new card.")
614 return
615
616 if message.content.startswith('!stay') or message.content.startswith('!stand'):
617 member = data.db_get_member(message.author.id)
618 if not member:
619 client.send_message(message.author, "There was a problem looking up your information.")
620 elif type(message.channel) is not discord.channel.PrivateChannel:
621 client.send_message(message.author, "You must make all bets / gaming via private message.")
622 else:
623 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
624 if state:
625 out_string = ""
626 bj = pickle.loads(str(state))
627
628 win, response = bj.is_win() 627 win, response = bj.is_win()
629 out_string += "\n\n" + bj.print_hand(show_dealer=True) 628 out_string += "\n\n" + bj.print_hand(show_dealer=True)
630 out_string += "\n\n" + response.format(win,) 629 out_string += "\n\n" + response.format(win,)
...@@ -634,65 +633,60 @@ To Play: !slots <bet>""") ...@@ -634,65 +633,60 @@ To Play: !slots <bet>""")
634 if not result: 633 if not result:
635 client.send_message(message.author, error_message) 634 client.send_message(message.author, error_message)
636 return 635 return
636
637 credits = data.db_get_credit(member['member_id']) 637 credits = data.db_get_credit(member['member_id'])
638 out_string += "\nCredits: {}".format(credits) 638 out_string += "\nCredits: {}".format(credits)
639 client.send_message(message.author, out_string)
640 return
641 639
642 if message.content.startswith('!bet'): 640 client.send_message(message.author, out_string)
643 member = data.db_get_member(message.author.id)
644 if not member:
645 client.send_message(message.author, "There was a problem looking up your information.")
646 elif type(message.channel) is not discord.channel.PrivateChannel:
647 client.send_message(message.author, "You must make all bets / gaming via private message.")
648 else:
649 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
650 if state:
651 client.send_message(message.author, "You are already playing a game!")
652
653 out_string = ""
654 bj = pickle.loads(str(state))
655 out_string += bj.print_hand()
656 actions = bj.get_actions()
657 if len(actions) > 0:
658 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
659 data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
660 else:
661 win, response = bj.is_win()
662 out_string += "\n\n" + bj.print_hand(show_dealer=True)
663 out_string += "\n\n" + response.format(win,)
664 data.db_delete_minigame_state(member['member_id'], 'blackjack')
665 log("{} - {}".format(member['member_name'], response.format(win,)))
666 result, error_message = data.db_update_credit(member['member_id'], int(win))
667 if not result:
668 client.send_message(message.author, error_message)
669 return
670 credits = data.db_get_credit(member['member_id'])
671 out_string += "\nCredits: {}".format(credits)
672
673 client.send_message(message.author, out_string)
674 641
675 return 642 else:
643 client.send_message(message.author, "You must start a game with !bet before you can ask for a new card.")
644 return
676 645
646 def do_bj_stay(client, message_parts, message):
647 member = data.db_get_member(message.author.id)
648 if not member:
649 client.send_message(message.author, "There was a problem looking up your information.")
650 elif type(message.channel) is not discord.channel.PrivateChannel:
651 client.send_message(message.author, "You must make all bets / gaming via private message.")
652 else:
653 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
654 if state:
677 out_string = "" 655 out_string = ""
678 bet_amount = message.content[5:] 656 bj = pickle.loads(str(state))
679 log("Member: {} Bet: {}".format(member['member_name'], bet_amount)) 657
680 658 win, response = bj.is_win()
681 if not bet_amount.isdigit(): 659 out_string += "\n\n" + bj.print_hand(show_dealer=True)
682 client.send_message(message.author, "Please provide a bet amount. !bet 10") 660 out_string += "\n\n" + response.format(win,)
683 return 661 data.db_delete_minigame_state(member['member_id'], 'blackjack')
684 662 log("{} - {}".format(member['member_name'], response.format(win,)))
685 result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount)) 663 result, error_message = data.db_update_credit(member['member_id'], int(win))
686 if not result: 664 if not result:
687 client.send_message(message.author, error_message) 665 client.send_message(message.author, error_message)
688 return 666 return
689 out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount) 667 credits = data.db_get_credit(member['member_id'])
690 bj = Blackjack(bet_amount) 668 out_string += "\nCredits: {}".format(credits)
669 client.send_message(message.author, out_string)
670 return
671
672 def do_bj_bet(client, message_parts, message):
673 member = data.db_get_member(message.author.id)
674 if not member:
675 client.send_message(message.author, "There was a problem looking up your information.")
676 elif type(message.channel) is not discord.channel.PrivateChannel:
677 client.send_message(message.author, "You must make all bets / gaming via private message.")
678 else:
679 state = data.db_get_minigame_state(member['member_id'], 'blackjack')
680 if state:
681 client.send_message(message.author, "You are already playing a game!")
682
683 out_string = ""
684 bj = pickle.loads(str(state))
691 out_string += bj.print_hand() 685 out_string += bj.print_hand()
692 actions = bj.get_actions() 686 actions = bj.get_actions()
693 if len(actions) > 0: 687 if len(actions) > 0:
694 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions)) 688 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
695 data.db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj)) 689 data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
696 else: 690 else:
697 win, response = bj.is_win() 691 win, response = bj.is_win()
698 out_string += "\n\n" + bj.print_hand(show_dealer=True) 692 out_string += "\n\n" + bj.print_hand(show_dealer=True)
...@@ -708,180 +702,247 @@ To Play: !slots <bet>""") ...@@ -708,180 +702,247 @@ To Play: !slots <bet>""")
708 702
709 client.send_message(message.author, out_string) 703 client.send_message(message.author, out_string)
710 704
711 return 705 return
712 706
713 # !msg joe in 5 minutes YOU ARE A DICK 707 out_string = ""
714 if message.content.startswith('!msg'): 708 bet_amount = message.content[5:]
715 channel = message.channel 709 log("Member: {} Bet: {}".format(member['member_name'], bet_amount))
716 author = message.author
717 #author = message.author.name
718 username = ''
719 try:
720 message_bits = message.content.split(" ")
721 msg_datetime = datetime.datetime.now()
722 msg_idx = 2
723 if message_bits[2] == 'in' and message_bits[3].isdigit():
724 time = int(message_bits[3])
725 msg_idx = 4
726 if message_bits[4].startswith('sec'):
727 msg_datetime = msg_datetime + datetime.timedelta(seconds=time)
728 msg_idx = 5
729 elif message_bits[4].startswith('hour'):
730 msg_datetime = msg_datetime + datetime.timedelta(hours=time)
731 msg_idx = 5
732 else: # minutes by default
733 msg_datetime = msg_datetime + datetime.timedelta(minutes=time)
734 msg_idx = 5
735 elif message_bits[2] == 'on':
736 try:
737 tmp_date = parse(message_bits[3])
738 msg_datetime = tmp_date
739 msg_idx = 4
740 except ValueError:
741 client.send_message(channel, 'Your shitty message has been rejected {}. Next time learn how to date...MM\\DD\\YYYY'.format(message.author.mention()))
742 return
743
744 username = message_bits[1]
745 user_mention = ''
746 # TODO: have it look in the database. Do this AFTER on startup we add all users.
747 for member in client.get_all_members():
748 log("MEMBER: %s" % member)
749 if username.lower() == member.name.lower():
750 user_mention = member.mention()
751 user_id = member.id
752 if user_mention == '':
753 client.send_message(channel, 'Your shitty message has been rejected {}. That user does not exist.'.format(message.author.name))
754 return
755
756 msg_text = byteify(' '.join(message_bits[msg_idx:]))
757 message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
758 log("Message: %s" % message)
759 data.db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
760 # print("Data: %s" % data)
761 #test_ch = Object(channel.id)
762 #client.send_message(test_ch, 'Test Message {}.'.format(author))
763 except Exception as e:
764 client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, e))
765 return
766 if msg_datetime < datetime.datetime.now():
767 client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
768 else:
769 client.send_message(channel, '{} your message will be delivered to {} {}.'.format(author.name, user_mention, human(msg_datetime)))
770 check_msg_queue()
771 return
772 710
773 if message.content.startswith('!addfortune'): 711 if not bet_amount.isdigit():
774 try: 712 client.send_message(message.author, "Please provide a bet amount. !bet 10")
775 fortune = message.content[9:] 713 return
776 if 'aa737a5846' in fortune: 714
777 client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention())) 715 result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
716 if not result:
717 client.send_message(message.author, error_message)
718 return
719 out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount)
720 bj = Blackjack(bet_amount)
721 out_string += bj.print_hand()
722 actions = bj.get_actions()
723 if len(actions) > 0:
724 out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
725 data.db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
726 else:
727 win, response = bj.is_win()
728 out_string += "\n\n" + bj.print_hand(show_dealer=True)
729 out_string += "\n\n" + response.format(win,)
730 data.db_delete_minigame_state(member['member_id'], 'blackjack')
731 log("{} - {}".format(member['member_name'], response.format(win,)))
732 result, error_message = data.db_update_credit(member['member_id'], int(win))
733 if not result:
734 client.send_message(message.author, error_message)
778 return 735 return
779 date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') 736 credits = data.db_get_credit(member['member_id'])
780 c = conn.cursor() 737 out_string += "\nCredits: {}".format(credits)
781 c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
782 conn.commit()
783 log("Added fortune")
784 except Exception as e:
785 log(e.message)
786 client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
787 return
788 client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
789 return
790 738
791 if message.content.startswith('!fortune'): 739 client.send_message(message.author, out_string)
792 fortune = None 740 return
793 try: 741
794 c = conn.cursor() 742 def do_msg(client, message_parts, message):
795 fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0] 743 channel = message.channel
796 log(fortune) 744 author = message.author
797 except Exception as e: 745 #author = message.author.name
798 log(e) 746 username = ''
799 pass 747 try:
800 if not fortune: 748 # TODO: Switch message_bits with message_parts
801 client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention())) 749 message_bits = message.content.split(" ")
750 msg_datetime = datetime.datetime.now()
751 msg_idx = 2
752 if message_bits[2] == 'in' and message_bits[3].isdigit():
753 time = int(message_bits[3])
754 msg_idx = 4
755 if message_bits[4].startswith('sec'):
756 msg_datetime = msg_datetime + datetime.timedelta(seconds=time)
757 msg_idx = 5
758 elif message_bits[4].startswith('hour'):
759 msg_datetime = msg_datetime + datetime.timedelta(hours=time)
760 msg_idx = 5
761 else: # minutes by default
762 msg_datetime = msg_datetime + datetime.timedelta(minutes=time)
763 msg_idx = 5
764 elif message_bits[2] == 'on':
765 try:
766 tmp_date = parse(message_bits[3])
767 msg_datetime = tmp_date
768 msg_idx = 4
769 except ValueError:
770 client.send_message(channel, 'Your shitty message has been rejected {}. Next time learn how to date...MM\\DD\\YYYY'.format(message.author.mention()))
771 return
772
773 username = message_bits[1]
774 user_mention = ''
775 # TODO: have it look in the database. Do this AFTER on startup we add all users.
776 for member in client.get_all_members():
777 #log("MEMBER: {}".format(byteify(member)))
778 if username.lower() == member.name.lower():
779 user_mention = member.mention()
780 user_id = member.id
781 if user_mention == '':
782 client.send_message(channel, 'Your shitty message has been rejected {}. That user does not exist.'.format(message.author.name))
783 return
784
785 msg_text = byteify(' '.join(message_bits[msg_idx:]))
786 message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
787 log("Message: %s" % byteify(message))
788 data.db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
789 # print("Data: %s" % data)
790 #test_ch = Object(channel.id)
791 #client.send_message(test_ch, 'Test Message {}.'.format(author))
792 except Exception as e:
793 client.send_message(channel, 'Your shitty message has been rejected {}. {}'.format(author.name, format_exception(e)))
794 return
795 if msg_datetime < datetime.datetime.now():
796 client.send_message(channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
797 else:
798 client.send_message(channel, '{} your message will be delivered to {} {}.'.format(author.name, user_mention, human(msg_datetime)))
799 check_msg_queue()
800 return
801
802 def do_addfortune(client, message_parts, message):
803 try:
804 fortune = message.content[9:]
805 if 'aa737a5846' in fortune:
806 client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
807 return
808 date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
809 c = conn.cursor()
810 c.execute("INSERT INTO fortunes (fortune, date_added) VALUES (?, ?)", (fortune, date_added))
811 conn.commit()
812 log("Added fortune")
813 except Exception as e:
814 log(e.message)
815 client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
816 return
817 client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
818 return
819
820 def do_fortune(client, message_parts, message):
821 fortune = None
822 try:
823 c = conn.cursor()
824 # TODO: Move this shit to data
825 fortune = c.execute("SELECT fortune FROM fortunes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
826 log(fortune)
827 except Exception as e:
828 log(e)
829 pass
830 if not fortune:
831 client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
832 else:
833 client.send_message(message.channel, '{} Your fortune is... {}'.format(message.author.mention(), byteify(fortune)))
834 return
835
836 def do_question(client, message_parts, message):
837 question = message.content[10:]
838 if "is it gay" in question:
839 client.send_message(message.channel, 'Yes {}, it is gay.'.format(message.author.mention()))
840 return
841 res = wolf.query(question)
842 try:
843 if len(res.pods):
844 pod_text = []
845 for pod in res.pods:
846 if pod.text:
847 pod_text.append(pod.text)
848 client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify("\n".join(pod_text)[:1990])))
802 else: 849 else:
803 client.send_message(message.channel, '{} Your fortune is... {}'.format(message.author.mention(), byteify(fortune))) 850 tagged_sent = pos_tag(question.replace('?', '').split())
851 proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
852 wiki_search = " ".join(proper_nouns)
853 if wiki_search.strip() != "":
854 log("Looking up {}".format(wiki_search))
855 wiki_out = wikipedia.summary(wiki_search, sentences=3)
856 client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
857 else:
858 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
859 return
860 except Exception as e:
861 log(format_exception(e))
862 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
804 return 863 return
805 864
806 if message.content.startswith('!question'): 865 def do_addjoke(client, message_parts, message):
807 question = message.content[10:] 866 try:
808 if "is it gay" in question: 867 joke = message.content[9:]
809 client.send_message(message.channel, 'Yes {}, it is gay.'.format(message.author.mention())) 868 if 'aa737a5846' in joke:
810 return 869 client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
811 res = wolf.query(question)
812 try:
813 if len(res.pods):
814 pod_text = []
815 for pod in res.pods:
816 if pod.text:
817 pod_text.append(pod.text)
818 client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify("\n".join(pod_text)[:1990])))
819 else:
820 tagged_sent = pos_tag(question.replace('?', '').split())
821 proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
822 wiki_search = " ".join(proper_nouns)
823 if wiki_search.strip() != "":
824 log("Looking up {}".format(wiki_search))
825 wiki_out = wikipedia.summary(wiki_search, sentences=3)
826 client.send_message(message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
827 else:
828 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
829 return
830 except Exception as e:
831 log(format_exception(e))
832 client.send_message(message.channel, 'I don\'t know {}.'.format(message.author.mention()))
833 return 870 return
871 date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
872 c = conn.cursor()
873 c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
874 conn.commit()
875 log("Added joke")
876 except Exception as e:
877 log(e.message)
878 client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
879 return
880 client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
881 return
882
883 def do_joke(client, message_parts, message):
884 joke = None
885 try:
886 c = conn.cursor()
887 joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0]
888 log(joke)
889 except Exception as e:
890 log(e)
891 pass
892 if not joke:
893 client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
894 else:
895 client.send_message(message.channel, '{} {}'.format(message.author.mention(), byteify(joke)))
896 return
834 897
835 if message.content.startswith('!addjoke'): 898 @client.event
836 try: 899 def on_message(message):
837 joke = message.content[9:] 900 #print message.content
838 if 'aa737a5846' in joke: 901 #print message.author
839 client.send_message(message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention())) 902 #print client.user
840 return 903 global muted_until
841 date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S') 904 # we do not want the bot to reply to itself
842 c = conn.cursor() 905 if message.author == client.user:
843 c.execute("INSERT INTO jokes (joke) VALUES (?)", (joke,))
844 conn.commit()
845 log("Added joke")
846 except Exception as e:
847 log(e.message)
848 client.send_message(message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
849 return
850 client.send_message(message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
851 return 906 return
852 907
853 if message.content.startswith('!joke'): 908 message_parts = message.content.split(" ")
854 joke = None 909 for command, method in registered_commands.iteritems():
855 try: 910 if message_parts[0] == command:
856 c = conn.cursor() 911 try:
857 joke = c.execute("SELECT joke FROM jokes ORDER BY RANDOM() LIMIT 1;").fetchone()[0] 912 globals()[method](client, message_parts[1:], message)
858 log(joke) 913 except Exception as e:
859 except Exception as e: 914 log("{} - {}".format(format_exception(e), e.message))
860 log(e) 915 return
861 pass 916
862 if not joke: 917 if message.content.lower().startswith(client.user.name.lower()):
863 client.send_message(message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention())) 918 log('Someone is talking to %s' % (client.user.name.lower(),))
864 else: 919 if ' or ' in message.content:
865 client.send_message(message.channel, '{} {}'.format(message.author.mention(), byteify(joke))) 920 questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
866 return 921 client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore')))
867 922
868 if message.content.startswith('!secret'): 923 if message.content.startswith('!secret'):
869 client.send_message(message.channel, 'git gud {}! My source is here: http://git.savsoul.com/barry/discordbot\nVersion: {}'.format(message.author.mention(), VERSION)) 924 client.send_message(message.channel, 'git gud {}! My source is here: http://git.savsoul.com/barry/discordbot\nVersion: {}'.format(message.author.mention(), VERSION))
925 return
870 926
871 if message.content.startswith('!bemyirlwaifu'): 927 if message.content.startswith('!bemyirlwaifu'):
872 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())) 928 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()))
929 return
873 930
874 if message.content.startswith('HILLARY 2016'): 931 if message.content.startswith('HILLARY 2016'):
875 client.send_message(message.channel, ':bomb: Ohhhhhh, now you done it...:bomb:'.format(message.author.mention())) 932 client.send_message(message.channel, ':bomb: Ohhhhhh, now you done it...:bomb:'.format(message.author.mention()))
933 return
934
935 if message.content.startswith('!squid'):
936 client.send_message(message.channel, 'くコ:彡 くコ:彡 くコ:彡 くコ:彡')
937 return
938
939 if message.content.startswith('!stars'):
940 client.send_message(message.channel, '✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈ ✰═━┈┈ ✰═━┈┈')
941 return
876 942
877 if message.content.startswith('!hello'): 943 if message.content.startswith('!hello'):
878 client.send_message(message.channel, 'Hello {}!'.format(message.author.mention())) 944 client.send_message(message.channel, 'Hello {}!'.format(message.author.mention()))
879 945 return
880 if message.content.startswith('!reloadbot'):
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 946
886 947
887 @client.event 948 @client.event
......
1 import random 1 import random
2 import time 2 import time
3 import pickle
3 4
4 FIND_PERCENTAGE = 80 5 FIND_PERCENTAGE = 100
5 6 SKILL_PERCENT = 80
6 7
7 class HuntResponse: 8 class HuntResponse:
8 ERROR = -1 9 ERROR = -1
...@@ -14,6 +15,7 @@ class HuntResponse: ...@@ -14,6 +15,7 @@ class HuntResponse:
14 self.message = message 15 self.message = message
15 self.monster = monster 16 self.monster = monster
16 17
18 exp_to_level = [500, 1250, 2250, 3500, 5000, 6750, 8750, 10950, 13350, 15950, 18750, 21750, 24950, 28350, 31950, 35750, 39750, 43950, 48350, 52950, 57750, 62750, 67850, 73050, 78350, 83750, 89250, 94850, 100550, 106350, 112250, 118250, 124350, 130550, 136850, 143250, 149750, 156350, 163050, 169850, 176750, 183750, 190850, 198050, 205350, 212750, 220250, 227850, 235550]
17 19
18 class Jobs: 20 class Jobs:
19 WAR = 1 21 WAR = 1
...@@ -39,6 +41,20 @@ class Jobs: ...@@ -39,6 +41,20 @@ class Jobs:
39 GEO = 21 41 GEO = 21
40 RUN = 22 42 RUN = 22
41 43
44 TemperamentPosture = {
45 4: {"name": "Very Agressive", "message": "Show no mercy!", "value": 4},
46 3: {"name": "Somewhat Agressive", "message": "Give em' a little more bite!", "value": 3},
47 2: {"name": "Somewhat Defensive", "message": "Back off a bit!", "value": 2},
48 1: {"name": "Very Defensive", "message": "Guard! Block! Parry! Hold!", "value": 1}
49 }
50
51 TemperamentAttitude = {
52 4: {"name": "Very Wild", "message": "Don't think, kill!", "value": 4},
53 3: {"name": "Somewhat Wild", "message": "Less thinking, more striking!", "value": 3},
54 2: {"name": "Somewhat Tame", "message": "Watch your opponent, then attack!", "value": 2},
55 1: {"name": "Very Tame", "message": "Think, and think again!", "value": 1}
56 }
57
42 PhysicalDamageTypes = { 58 PhysicalDamageTypes = {
43 'blunt': ['Hand-to-Hand', 'Club', 'Staff', 'Harlequin Frame', 'Stormwaker Frame', 'Sharpshot Frame'], 59 'blunt': ['Hand-to-Hand', 'Club', 'Staff', 'Harlequin Frame', 'Stormwaker Frame', 'Sharpshot Frame'],
44 'slashing': ['Axe', 'Great Axe', 'Great Sword', 'Sword', 'Scythe', 'Katana', 'Great Katana', 'Valoredge Frame'], 60 'slashing': ['Axe', 'Great Axe', 'Great Sword', 'Sword', 'Scythe', 'Katana', 'Great Katana', 'Valoredge Frame'],
...@@ -46,7 +62,7 @@ PhysicalDamageTypes = { ...@@ -46,7 +62,7 @@ PhysicalDamageTypes = {
46 } 62 }
47 63
48 FeralSkills = { 64 FeralSkills = {
49 'Airy Shield': {'type': 'Enhancing', 'sub_type': 'arrow shield', 'shadows': 'ignore', 'range': None, 'aoe': False, 'spell': 'arrow shield'}, 65 'Airy Shield': {'fp_cost': 0, 'type': 'Enhancing', 'sub_type': 'arrow shield', 'shadows': 'ignore', 'range': None, 'aoe': False, 'spell': 'arrow shield'},
50 'Binding Wave': {'type': 'Enfeebling', 'shadows': 'ignore', 'range': 15, 'aoe': True, 'spell': 'bind'}, 66 'Binding Wave': {'type': 'Enfeebling', 'shadows': 'ignore', 'range': 15, 'aoe': True, 'spell': 'bind'},
51 'Dire Straight': {'type': 'Physical', 'shadows': 'wipe', 'range': None, 'aoe': False}, 67 'Dire Straight': {'type': 'Physical', 'shadows': 'wipe', 'range': None, 'aoe': False},
52 'Dismemberment': {'type': 'Piercing', 'shadows': 'absorb', 'range': None, 'aoe': False}, # causes the monster to lose a body part 68 'Dismemberment': {'type': 'Piercing', 'shadows': 'absorb', 'range': None, 'aoe': False}, # causes the monster to lose a body part
...@@ -60,37 +76,75 @@ Families = { ...@@ -60,37 +76,75 @@ Families = {
60 'acrolith': { 76 'acrolith': {
61 'base_fp': 50, 77 'base_fp': 50,
62 'fp_per_level': 0.1, 78 'fp_per_level': 0.1,
63 'max_fp': 55, 79 'max_fp': 55,
64 'main_job': Jobs.WAR, 80 'available_main_job': [Jobs.WAR, Jobs.DRG, Jobs.DRK, Jobs.PLD],
65 'support_job': None, 81 'available_support_job': [Jobs.WAR, Jobs.DRG, Jobs.DRK, Jobs.PLD],
66 'innate_feral_skills': ['Sinker Drill', 'Dire Straight', 'Dismemberment', 'Earthshatter'], 82 'innate_feral_skills': ['Sinker Drill', 'Dire Straight', 'Dismemberment', 'Earthshatter'],
67 'type': 'Arcana', 83 'type': 'Arcana',
68 'strong_vs': ['Dark'], 84 'strong_vs': ['Dark'],
69 'charmable': False, 85 'charmable': False,
70 'aspir': False, 86 'aspir': False,
71 'drain': False 87 'drain': False,
88 'temperament_attitude': {
89 'initial_value': 4,
90 'actions': {
91 4: {'use_tp_chance': 100, 'ws': ['Sinker Drill'], 'side_attack_chance': 0, 'range_chance': 0},
92 3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
93 2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
94 1: {'use_tp_chance': 70, 'ws': ['Binding Wave', 'Hypnosis', 'Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 70}
95 }
96 },
97 'temperament_posture': {
98 'initial_value': 4,
99 'actions': {
100 4: {'use_tp_chance': 100, 'ws': ['Eyes On Me'], 'side_attack_chance': 0, 'range_chance': 0},
101 3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
102 2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
103 1: {'use_tp_chance': 70, 'ws': ['Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 100}
104 }
105 }
72 }, 106 },
73 'ahriman': { 107 'ahriman': {
74 'base_fp': 65, 108 'base_fp': 65,
75 'fp_per_level': 0.3, 109 'fp_per_level': 0.3,
76 'max_fp': 80, 110 'max_fp': 80,
77 'main_job': Jobs.WAR, 111 'available_main_job': [Jobs.BLM, Jobs.RDM, Jobs.WAR],
78 'support_job': Jobs.BLM, 112 'available_support_job': [Jobs.BLM, Jobs.RDM, Jobs.WAR],
79 'innate_feral_skills': ['Binding Wave', 'Magic Barrier', 'Hypnosis', 'Eyes On Me', 'Airy Shield'], 113 'innate_feral_skills': ['Binding Wave', 'Magic Barrier', 'Hypnosis', 'Eyes On Me', 'Airy Shield'],
80 'type': 'Demon', 114 'type': 'Demon',
81 'traits': ['magic defence bonus +25%'], 115 'traits': ['magic defence bonus +25%'],
82 'charmable': False, 116 'charmable': False,
83 'aspir': True, 117 'aspir': True,
84 'drain': True 118 'drain': True,
119 'temperament_attitude': {
120 'initial_value': 4,
121 'actions': {
122 4: {'use_tp_chance': 100, 'ws': ['Eyes On Me'], 'side_attack_chance': 0, 'range_chance': 0},
123 3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
124 2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
125 1: {'use_tp_chance': 70, 'ws': ['Binding Wave', 'Hypnosis', 'Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 70}
126 }
127 },
128 'temperament_posture': {
129 'initial_value': 4,
130 'actions': {
131 4: {'use_tp_chance': 100, 'ws': ['Eyes On Me'], 'side_attack_chance': 0, 'range_chance': 0},
132 3: {'use_tp_chance': 75, 'ws': ['Eyes On Me'], 'side_attack_chance': 70, 'range_chance': 10},
133 2: {'use_tp_chance': 50, 'ws': ['Binding Wave', 'Hypnosis'], 'side_attack_chance': 25, 'range_chance': 70},
134 1: {'use_tp_chance': 70, 'ws': ['Magic Barrier', 'Airy Shield'], 'side_attack_chance': 25, 'range_chance': 100}
135 }
136 }
85 } 137 }
86 } 138 }
87 139
88 Monsters = { 140 Monsters = {
89 'Mechanical Menace': { 141 'Mechanical Menace': {
142 'initial_level': 9,
90 'family': 'acrolith', 143 'family': 'acrolith',
91 'zone': 'Abyssea - Uleguerand' 144 'zone': 'Abyssea - Uleguerand'
92 }, 145 },
93 'Floating Eye': { 146 'Floating Eye': {
147 'initial_level': 3,
94 'family': 'ahriman', 148 'family': 'ahriman',
95 'zone': 'Ranguemont Pass' 149 'zone': 'Ranguemont Pass'
96 } 150 }
...@@ -120,8 +174,27 @@ class Pankration: ...@@ -120,8 +174,27 @@ class Pankration:
120 174
121 def hunt_monster(self, zone): 175 def hunt_monster(self, zone):
122 if random.randint(1, 100) < FIND_PERCENTAGE: 176 if random.randint(1, 100) < FIND_PERCENTAGE:
177 monster_data = Monsters[random.choice(self.get_monsters(zone))]
178 print(monster_data)
179 family_name = monster_data['family']
180 level = monster_data['initial_level']
181 family = Families[family_name]
182 main_job = random.choice(family['available_main_job'])
183 support_job = random.choice(family['available_support_job'])
184 feral_skills = []
185 skills = random.sample(family['innate_feral_skills'], 3)
186 if random.randint(1, 100) < SKILL_PERCENT:
187 feral_skills.append(skills[0])
188 if random.randint(1, 100) < SKILL_PERCENT:
189 feral_skills.append(skills[1])
190 if random.randint(1, 100) < SKILL_PERCENT:
191 feral_skills.append(skills[2])
192 dicipline_level = 1
193
194 monster = Monster(family, level, main_job, support_job, feral_skills,
195 [], dicipline_level)
123 return HuntResponse(HuntResponse.SUCCESS, "You captured the monster!", 196 return HuntResponse(HuntResponse.SUCCESS, "You captured the monster!",
124 random.choice(self.get_monsters(zone))) 197 monster)
125 else: 198 else:
126 return HuntResponse(HuntResponse.FAILURE, "You were unable to capture a monster's soul.", 199 return HuntResponse(HuntResponse.FAILURE, "You were unable to capture a monster's soul.",
127 None) 200 None)
...@@ -130,26 +203,77 @@ class Pankration: ...@@ -130,26 +203,77 @@ class Pankration:
130 return "" 203 return ""
131 204
132 class Monster: 205 class Monster:
133 def __init__(self, family, level, main_job, support_job, fp_capacity, innate_feral_skills, 206 def __init__(self, family, level, main_job, support_job, innate_feral_skills,
134 eqipped_feral_skills, dicipline_level, temperament): 207 equipped_feral_skills, dicipline_level):
135 self.family = family 208 self.family = family
136 self.level = level 209 self.level = level
137 self.main_job = main_job 210 self.main_job = main_job
138 self.support_job = support_job 211 self.support_job = support_job
139 self.fp_capacity = fp_capacity
140 self.innate_feral_skills = innate_feral_skills 212 self.innate_feral_skills = innate_feral_skills
141 self.equipped_feral_skills = eqipped_feral_skills 213 self.equipped_feral_skills = equipped_feral_skills
142 self.discipline_level = dicipline_level 214 self.discipline_level = dicipline_level
143 self.temperament = temperament 215 self.temperament_posture = family['temperament_posture']['initial_value']
144 216 self.temperament_attitude = family['temperament_attitude']['initial_value']
145 def calculate_fp_gain(self): 217 self.pre_fight_command = {"temperament_posture": None, "temperament_attitude": None}
218 self.exp = exp_to_level[level] + 1
219
220 def __str__(self):
221 return "Family: {}\nLevel: {}\nMain Job: {}\nSupport Job: {}\nInnate Feral Skills: {}\nEquipped Feral Skills: {}\nDicipline Level: {}\nTemperament...".format(self.family, self.level, self.main_job, self.support_job, self.innate_feral_skills, self.equipped_feral_skills, self.discipline_level)
222
223 def get_fp(self):
224 return int(self.level / self.family['fp_per_level'])
225
226 def add_xp(self, exp_to_add):
227 self.exp += exp_to_add
228 for i in range(self.level, 50):
229 if self.exp > exp_to_level[i]:
230 if i > self.level:
231 # We leveled up!
232 print("Start level: {} New Level: {}".format(self.level, i))
233 else:
234 print("Just another brick in the wall...")
235 else:
236 break
237 # calc level based on xp
238 # stop at 50
146 pass 239 pass
147 240
148 def set_strategy(self, strategy_type): 241 def get_current_posture(self):
149 if strategy_type not in self.monster_data['strategies']: 242 return TemperamentPosture(self.temperament_posture)
150 return False 243
244 def get_current_attitude(self):
245 return TemperamentAttitude(self.temperament_attitude)
246
247 def get_dicipline_level(self):
248 if self.dicipline_level < 2:
249 return "Defiant"
250 elif self.dicipline_level < 5:
251 return "Disrespectful"
252 elif self.dicipline_level < 7:
253 return "Disobedient"
254 else:
255 return "Obedient"
256
257 # This should ONLY be executed at the start of battle.
258 def set_strategy(self, temperament_posture, temperament_attitude):
259 distance_from_nature = abs(self.temperament_posture - temperament_posture)
260 distance_from_nature += abs(self.temperament_attitude - temperament_attitude)
261
262 if distance_from_nature == 0:
263 chance_of_listening = self.discipline_level
264 else:
265 chance_of_listening = float(float(self.discipline_level) / (float(distance_from_nature)/10))
266
267 chance_of_listening = abs(float((float(chance_of_listening)-1)/(20-1)))
268
269 if random.randint(1, 100) > chance_of_listening * 100:
270 print("DO ACTION:")
271 # adjust dicipline_level
272 # move temperament
151 else: 273 else:
152 self.strategy = strategy_type 274 #continue action
275 #if severe request then reduce dicipline_level
276 pass
153 277
154 class Battle: 278 class Battle:
155 pass 279 pass
...@@ -169,8 +293,12 @@ print(str(hunt_response.result)) ...@@ -169,8 +293,12 @@ print(str(hunt_response.result))
169 time.sleep(0.5) 293 time.sleep(0.5)
170 if hunt_response.result == HuntResponse.SUCCESS: 294 if hunt_response.result == HuntResponse.SUCCESS:
171 print(hunt_response.message) 295 print(hunt_response.message)
172 monster = Monsters[hunt_response.monster] 296 monster = hunt_response.monster
173 print("The Soul Plate Shows: \n\n{}\n{}{}".format(hunt_response.monster)) 297 print("The Soul Plate Shows: \n\n{}".format(monster))
298 print(monster.set_strategy(4, 3))
299 print(monster.set_strategy(1, 1))
300 print(monster.set_strategy(1, 2))
301 monster.add_xp(2900)
174 else: 302 else:
175 print(hunt_response.message) 303 print(hunt_response.message)
176 304
......