hellsbot.py 68.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import discord
import random
import datetime
import time
import re
import pickle
import logging
import thread

import traceback
import sys
import wikipedia
from subprocess import call

from dateutil.parser import parse

from discord.object import Object
from discord.channel import PrivateChannel
from ago import human
import simplejson as json
from collections import defaultdict
from nltk.tag import pos_tag
import wolframalpha
import sqlite3
from blackjack import Blackjack
import data
import pyping
from pankration import Pankration, HuntResponse, Jobs, Action, MagicResistAction, MissAction, AttackAction, DefeatAction, TemperamentPosture, TemperamentAttitude

import subprocess


VERSION = 2.3

quitting = False

grant_hour = 11

battle_in_progress = False

conn = sqlite3.connect('db.sqlite3')

credentials = 'creds.json'

muted_until = datetime.datetime.now()

client = discord.Client()
wolf = {}
logging.basicConfig(filename='hellsbot.log', level=logging.WARNING)

registered_commands = {'!help': 'do_help', '!commands': 'do_help',
                       '!shutup': 'do_shutup',
                       '!roll': 'do_roll',
                       '!lastseen': 'do_lastseen',
                       '!youtube': 'do_youtube',
                       '!image': 'do_image',
                       '!gif': 'do_gif',
                       '!gameslist': 'do_gameslist', '!gamelist': 'do_gameslist',
                       '!aliases': 'do_alias', '!alias': 'do_alias',
                       '!addalias': 'do_addalias',
                       '!games': 'do_games',
                       '!reloadbot': 'do_reload', '!restartbot': 'do_reload', '!rebootbot': 'do_reload',
                       '!whoplayed': 'do_whoplayed',
                       '!gimmecredits': 'do_gimmecredits', '!gimmecredit': 'do_gimmecredits',
                       '!grantcredits': 'do_grantcredits',
                       '!resetalltickets': 'do_resetalltickets',
                       '!ticketrank': 'do_ticketrank',
                       '!startraffle': 'do_startraffle',
                       '!raffle': 'do_raffle',
                       '!pastraffles': 'do_pastraffle', '!pastraffle': 'do_pastraffle',
                       '!buyticket': 'do_buyticket',
                       '!balance': 'do_balance',
                       '!slotsrules': 'do_slotsrules',
                       '!slots': 'do_slots',
                       '!hit': 'do_bj_hit', '!draw': 'do_bj_hit',
                       '!stay': 'do_bj_stay', '!stand': 'do_bj_stay',
                       '!bet': 'do_bj_bet',
                       '!msg': 'do_msg',
                       '!addfortune': 'do_addfortune',
                       '!fortune': 'do_fortune',
                       '!question': 'do_question',
                       '!addjoke': 'do_addjoke',
                       '!joke': 'do_joke',
                       '!secret': 'do_secret',
                       '!bemyirlwaifu': 'do_waifu',
                       'HILLARY 2016': 'do_hillary',
                       '!squid': 'do_squid',
                       '!stars': 'do_stars',
                       '!rigged': 'do_rigged',
                       '!listzones': 'do_list_zones',
                       '!huntmonster': 'do_hunt_monster', '!hunt': 'do_hunt_monster',
                       '!skills': 'do_list_feral_skills', '!feralskills': 'do_list_feral_skills', '!feralskill': 'do_list_feral_skills',
                       '!reflectors': 'do_list_reflectors', '!reflector': 'do_list_reflectors',
                       '!plates': 'do_list_soul_plates', '!soulplates': 'do_list_soul_plates', '!soulplate': 'do_list_soul_plates',
                       '!convert': 'do_convert_plate', '!convertplate': 'do_convert_plate', '!convertsoulplate': 'do_convert_plate',
                       '!registerbattle': 'do_register_battle', '!battle': 'do_register_battle',
                       '!setreflectorname': 'do_set_reflector_name',
                       '!equip': 'do_equip_feral_skills', '!equipskill': 'do_equip_feral_skills', '!equipferalskill': 'do_equip_feral_skills',
                       '!pankration': 'do_pankration',
                       }


#####################
# Utility Functions
#####################
def log(message):
    try:
        logging.warning("{} - {}".format(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), message))
    except:
        pass


def send_message(client, target, message):
    if type(target) is not discord.channel.PrivateChannel:
        if target.id == '121468616414724100':
            return
        elif datetime.datetime.now() < muted_until:
            return
    client.send_message(target, message)


def format_exception(e):
    exception_list = traceback.format_stack()
    exception_list = exception_list[:-2]
    exception_list.extend(traceback.format_tb(sys.exc_info()[2]))
    exception_list.extend(traceback.format_exception_only(sys.exc_info()[0], sys.exc_info()[1]))

    exception_str = "Traceback (most recent call last):\n"
    exception_str += "".join(exception_list)
    # Removing the last \n
    exception_str = exception_str[:-1]

    return exception_str


def leaders(xs, top=20):
    counts = defaultdict(int)
    for x in xs:
        counts[x] += 1
    return sorted(counts.items(), reverse=True, key=lambda tup: tup[1])[:top]


def byteify(input):
    if isinstance(input, dict):
        return {byteify(key): byteify(value) for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input


def search_youtube(query):
    query_string = {"search_query": query}
    r = requests.get("http://www.youtube.com/results", params=query_string)
    search_results = re.findall(r'href=\"\/watch\?v=(.{11})', r.content)
    log("http://www.youtube.com/watch?v=" + search_results[0])
    return "http://www.youtube.com/watch?v=" + search_results[0]


def search_google_images(query, animated=False):
    headers = {'User-Agent': "Mozilla/5.0 (X11; FreeBSD amd64; rv:12.0) Gecko/20100101 Firefox/12.0"}
    query_string = {"safe": "off", "tbm": "isch", "q": query}
    if animated:
        query_string = {"safe": "off", "tbm": "isch", "q": query, 'tbs': 'itp:animated'}

    r = requests.get("http://www.google.com/search", params=query_string, headers=headers)

    start_idx = r.content.find('imgurl=') + 7
    if start_idx > 0:
        search_result = r.content[start_idx:r.content.find('&', start_idx)]
        if '/revision/' in search_result:
            search_result = search_result[:search_result.find('/revision/')]
        if '%' in search_result:
            search_result = search_result[:search_result.find('%')]
        log(search_result)
        return search_result
    return "boo you fail.."


def ping(hostname, timeout):
    ping_response = subprocess.Popen(["/bin/ping", "-c1", "-w100", hostname], stdout=subprocess.PIPE).stdout.read()
    #log(ping_response)
    matches = re.match('.*time=([0-9\.]+) ms.*', ping_response, re.DOTALL)
    if matches:
        return matches.group(1)
    else:
        return False


def check_pings():
    for ping_row in data.db_get_pings():
        new_ping = ping(ping_row.get('ip_address'), 1000)
        if new_ping:
            log("{} - New Ping: {}".format(ping_row.get('ip_address'), new_ping))
            data.db_update_ping(ping_row.get('ping_id'), new_ping)
            for channel in client.get_all_channels():
                if channel.id == '193028170184785920': # Reflex channel
                    send_message(client, channel, "{} - {}ms    Average: {}ms".format(ping_row.get('ip_address'), new_ping, ping_row.get('average_ping')))
                    break
        else:
            # for member in client.get_all_members():
            #     if member.id == '122079633796497409':
            #         send_message(client, member, "Outage! {} - {}ms    Average: {}ms".format(ping_row.get('ip_address'), new_ping, ping_row.get('average_ping')))
            #         break

            data.db_update_ping(ping_row.get('ping_id'), False)


def check_msg_queue(client):
    messages = data.db_get_messages()
    if messages:
        for message in messages:
            try:
                member = data.db_get_member(filter(unicode.isalnum, message['message_to']))
                if member:
                    if message['message_to'] == member['discord_mention']:
                        log("Found Message: {} - {} - Status: {} Channel: {}".format(message['message_to'], member['discord_mention'], member['status'], message['channel']))
                        if member['status'] == 'online':
                            client.send_message(Object(message['channel']), '{}, {} asked me to tell you "{}"'.format(message['message_to'], message['message_from'], message['message']))
                            data.db_delete_sent_message(message['message_id'])
            except Exception as e:
                log("{}\nFailed to send message: {}".format(format_exception(e), message['message_id'],))
    return


def do_roll(client, message_parts, message):
    request = message_parts[0]
    count = 1
    dice = 100
    if request.strip() != '':
        if 'd' in request:
            dice_parts = request.split('d')
            if len(dice_parts) == 2:
                if dice_parts[0].isdigit() and dice_parts[1].isdigit():
                    count = int(dice_parts[0])
                    dice = int(dice_parts[1])
    if count > 100000000000000000:
        send_message(client, message.channel, '{} stop fucking around with those stupid numbers...'.format(message.author.mention()))
        return

    if count > 100:
        send_message(client, message.channel, '{} 100 is the largest number of dice I will roll.'.format(message.author.mention()))
        return
    roll_results = []
    for i in range(count):
        roll_results.append(random.randint(1, dice))
    out_string = '{} your roll {}d{}: {} = {}'.format(message.author.mention(), count, dice, '+'.join(str(r) for r in roll_results), sum(roll_results))
    send_message(client, message.channel, out_string)
    return


def do_lastseen(client, message_parts, message):
    username = ' '.join(message_parts).replace('@', '').lower()
    member = data.db_get_member(username=username)
    if member:
        out_string = ''
        if member['is_afk'] == 1:
            out_string = 'Went AFK at: {}\n'.format(member['afk_at'])
        elif member['status'] == 'offline':
            out_string = 'Currently Offline\n'
        else:
            out_string = 'Currently Online\n'
        out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(member['status'], 
            member['status_change_at'],
            human(datetime.datetime.strptime(member['status_change_at'], '%Y/%m/%d %H:%M:%S')),
            member['prev_status'])

        send_message(client, message.channel, 'Last Information on {}:\n{}'.format(byteify(username), out_string))
    else:
        send_message(client, message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(username), message.author.mention()))
    return


def do_help(client, message_parts, message):
        send_message(client, message.channel, """{} Available Commands:
You can ask compound or questions and I will choose. Example: HellsBot Rui is a Faggot or Rui is a faggot?

User Info:
    !aliases <username> - Returns a list of all aliases a user has set for themselves.
    !addalias <alias> - Adds an alias to your list of aliases.
    !lastseen <username> - Returns info on when the user was last seen and their status.
Messages:
    !msg <username> in 5 minutes Tea is ready
    !msg <username> in 45 seconds Your finished masterbating
    !msg <username> in 2 hours The movie is over
    !msg <username> on 12/22/2015 Happy Birthday!
Games:
    !games <username> - Returns a list of games played for a username.
    !gameslist <count> - Returns a list of the top 20 games and the number of people who have played that game. if you pass a limit it will show that many games instead.
    !whoplayed <gamename> - Returns a list of players who have played the game.
Minigames:
    !gimmecredits - Gives you some extra credits in case you run out.
    !bet <amount> - Start a game of BlackJack.
    !slots <amount> - Spin the slot machine (max 10 credit bet).
    !hit - Draw a card
    !stand - Show the cards
""".format(message.author.mention()))
        send_message(client, message.channel, """
    !balance - Lists your current credits and tickets
    !buyticket - Purchases a raffle ticket for 100 credits
    !raffle - Shows information about the current raffle
    !ticketrank - Shows the percentage of the tickets on the system
Spam:
    !youtube <search term> - Returns the first video from the search results for the search term.
    !gif <search term> - Returns the first gif from the search results.
    !image <search term> - Returns the first image from the search results.
Stuff:
    !addfortune <fortune> - Adds a new fortune.
    !fortune - Returns your fortune.
    !addjoke <joke> - Adds a new joke (it can be multiline but must all be in a single message).
    !joke - Returns a random joke.
    !roll <1d20> - Roll X number of dice of size X. 1d20 returns 1 roll 1-20. 3d6 returns 3 rolls of 1-6 etc...
    !secret
    !shutup - disables all image / gif / youtube spam for 5 minutes
    !rigged - Cause Study is no good at betting.
    !bemyirlwaifu""".format(message.author.mention()))


def do_shutup(client, message_parts, message):
    global muted_until
    muted_until = datetime.datetime.now() + datetime.timedelta(minutes=5)
    send_message(client, message.channel, 'All image / gif / youtube spam disabled for 5 minutes')
    return


def do_youtube(client, message_parts, message):
    if datetime.datetime.now() < muted_until:
        return
    send_message(client, message.channel, search_youtube(' '.join(message_parts)))
    return


def do_image(client, message_parts, message):
    if datetime.datetime.now() < muted_until:
        return
    send_message(client, message.channel, search_google_images(' '.join(message_parts)))
    return


def do_gif(client, message_parts, message):
    if datetime.datetime.now() < muted_until:
        return
    send_message(client, message.channel, search_google_images(' '.join(message_parts), True))
    return


def do_gameslist(client, message_parts, message):
    limit = 20
    log("parts: {} {}".format(message_parts, message))
    if len(message_parts) > 0 and message_parts[0].isdigit():
        limit = int(message_parts[0])
    games_list = data.db_get_games_list(limit)

    out_string = ''
    for game in games_list:
        out_string += '    {} - {}\n'.format(game[1], byteify(game[0]))
    send_message(client, message.channel, 'The games I have seen people playing are: ')
    while len(out_string) > 0:
        send_message(client, message.channel, out_string[:1900])
        out_string = out_string[1900:]
    return


def do_alias(client, message_parts, message):
    if len(message_parts) > 0:
        username = ' '.join(message_parts).replace('@', '').lower()
        member = data.db_get_member(username=username)
    else:
        username = message.author.name
        member = data.db_get_member(message.author.id)
    if member:
        aliases = data.db_get_aliases(member['member_id'])
        if aliases:
            send_message(client, message.channel, '{} has the following aliases: {}'.format(byteify(username), byteify(', '.join(aliases))))
        else:
            send_message(client, message.channel, 'No known alises for {} yet {}'.format(byteify(username), message.author.mention()))
    else:
        send_message(client, message.channel, 'I don\'t know who you are speaking of {}!'.format(message.author.mention()))
    return


def do_addalias(client, message_parts, message):
    alias = ' '.join(message_parts)
    username = message.author.name.lower()
    member = data.db_get_member(username=username)
    if member:
        data.db_add_aliases(member['member_id'], alias)
        send_message(client, message.channel, '{} has been added to your aliases'.format(byteify(alias)))
    else:
        send_message(client, message.channel, 'Something horrible happened and it is all your fault, try logging out / on again or play a game. (or fuck off i dunno i\'m just an error message. Who am I to tell you how to run your life...)')
    return


def do_games(client, message_parts, message):
    if len(message_parts) > 0:
        username = ' '.join(message_parts).replace('@', '').lower()
    else:
        username = message.author.name
    games_list = data.db_get_games(username)
    if games_list:
        games = ', '.join(games_list)
        games = games.replace("FINAL FANTASY XIV", "**FINAL FANTASY XIV**")
        log(byteify(games))
        out_string = byteify(games)
        while len(out_string) > 0:
            send_message(client, message.channel, out_string[:1900])
            out_string = out_string[1900:]
        #send_message(client, message.channel, 'I have seen {} playing: {}'.format(byteify(username), byteify(games)))
    else:
        send_message(client, message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(username), message.author.mention()))


def do_reload(client, message_parts, message):
    if message.author.id != '78767557628133376':
        send_message(client, message.channel, "You shouldn't be calling this. You are clearly looking to piss Hellsbreath off.")
        return
    call(["service", "hellsbot", "restart"])


def do_whoplayed(client, message_parts, message):
    game_name = ' '.join(message_parts)
    member_list = data.db_get_whoplayed(game_name)
    if not member_list:
        send_message(client, message.channel, 'I don\'t have any data on {} yet {}'.format(byteify(game_name), message.author.mention()))
    else:
        out_string = ''
        for member in member_list:
            out_string += '    {} - {}\n'.format(byteify(member[1]), byteify(member[0]))
        send_message(client, message.channel, 'Below is a list of people who have played {} and the number of times they have launched the game:'.format(byteify(game_name),))
        while len(out_string) > 0:
            send_message(client, message.channel, out_string[:1900])
            out_string = out_string[1900:]
    return


def do_gimmecredits(client, message_parts, message):
    member = data.db_get_member(message.author.id)
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
    else:
        credits = data.db_get_credit(member['member_id'])
        if credits < 5:
            amount = random.randint(5, 50)
            data.db_update_credit(member['member_id'], amount)
            send_message(client, message.author, "You have been given {} credits.".format(amount,))
        else:
            send_message(client, message.author, "You already have credits. Stop begging.")
    return

def do_resetalltickets(client, message_parts, message, channel=None):
    if not channel and message.author.id != '78767557628133376':
        send_message(client, message.channel, "You are not Hellsbreath. Go away.")
        return
    members = data.db_get_all_members()
    if len(members) < 0:
        send_message(client, message.channel, "There was a problem looking up your information.")
    else:
        for member in members:
            if member['tickets'] > 0:
                data.db_reset_all_tickets(member['member_id'])
                send_message(client, message.channel, "{} had {} tickets and was reset to 0.".format(member['member_name'], member['tickets']))
    return

def do_grantcredits(client, message_parts, message, channel=None):
    if not channel and message.author.id != '78767557628133376':
        send_message(client, message.channel, "You are not Hellsbreath. Use !gimmecredits to get a few extra if you run out.")
        return
    members = data.db_get_all_members()
    if len(members) < 0:
        send_message(client, message.channel, "There was a problem looking up your information.")
    else:
        for member in members:
            credits = data.db_get_credit(member['member_id'])
            if credits < 100:
                data.db_update_credit(member['member_id'], 100)
                if channel:
                    send_message(client, channel, "{} has been given {} credits.".format(member['member_name'], 100))
                else:
                    send_message(client, message.channel, "{} has been given {} credits.".format(member['member_name'], 100))
    return


def do_ticketrank(client, message_parts, message):
    members = data.db_get_all_members()
    if len(members) < 0:
        send_message(client, message.channel, "There was a problem looking up your information.")
    else:
        ticket_count = 0
        for member in members:
            if member['discord_id'] != '78767557628133376':
                ticket_count += member['tickets']
        if ticket_count == 0:
            send_message(client, message.channel, "No Tickets have been sold for this raffle.")
            return

        out_string = ""
        for member in members:
            if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
                percent = (float(member['tickets']) / float(ticket_count)) * 100.0
                out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))

        send_message(client, message.channel, out_string)
    return


def do_startraffle(client, message_parts, message):
    if message.author.id != '78767557628133376':
        send_message(client, message.channel, "You are not Hellsbreath. Go die in an especially hot fire.")
        return
    members = data.db_get_all_members()
    if len(members) < 0:
        send_message(client, message.channel, "There was a problem looking up your information.")
    else:
        ticket_count = 0
        for member in members:
            if member['discord_id'] != '78767557628133376':
                ticket_count += member['tickets']
        if ticket_count == 0:
            send_message(client, message.channel, "No Tickets have been sold for this raffle.")
            return

        out_string = "The final standings are as follows: \n\n"
        ticket_reel = []
        for member in members:
            if member['tickets'] > 0 and member['discord_id'] != '78767557628133376':
                ticket_reel += [member['discord_mention']] * member['tickets']
                percent = (float(member['tickets']) / float(ticket_count)) * 100.0
                out_string += "{} - {}%\n".format(byteify(member['member_name']), int(percent))

        creds = json.loads(json_data)

        raffles = creds['raffles']
        title = ""
        key = ""
        dlc = ""
        random_keys = creds['randomkeys']
        for key, value in raffles.iteritems():
            if value['current'] == 1:
                title = value['title']
                game_key = value['key']
                if 'dlc' in value:
                    dlc = value['dlc']

        if len(ticket_reel) > 0:
            winner = random.choice(ticket_reel)
            while winner in ticket_reel:
                ticket_reel.remove(winner)
            send_message(client, message.channel, "\n\n\n**The winner is....\n\n{}!**".format(byteify(winner)))
        if len(ticket_reel) > 0:
            second = random.choice(ticket_reel)
            while second in ticket_reel:
                ticket_reel.remove(second)
            time.sleep(0.5)
            send_message(client, message.channel, "\n\n*2nd Place:* {}".format(byteify(second)))
        if len(ticket_reel) > 0:
            third = random.choice(ticket_reel)
            time.sleep(0.5)
            send_message(client, message.channel, "\n*3rd Place:* {}".format(byteify(third)))

        for member in client.get_all_members():
            log(member.id)
            if member.id == '78767557628133376':
                priv_message = "1st: {} key: {}\n2nd: {} keys: {}\n3rd: {} keys: {}".format(byteify(winner), game_key, byteify(second), '  '.join(random_keys[0:2]), byteify(third), random_keys[2])
                log(priv_message)
                send_message(client, member, priv_message)
                break

    return


def do_pastraffle(client, message_parts, message):
    creds = json.loads(json_data)

    raffles = creds['raffles']
    out_str = ""
    for key, value in raffles.iteritems():
        if value['current'] == 0:
            out_str += "{} - {}\n".format(key, value['title'])
    send_message(client, message.channel, "Past Raffles:\n\n{}".format(out_str))
    return


def do_raffle(client, message_parts, message):
    creds = json.loads(json_data)

    raffles = creds['raffles']
    title = ""
    description = ""
    link = ""
    date = ""
    for key, value in raffles.iteritems():
        if value['current'] == 1:
            date = key
            title = value['title']
            description = value['description']
            link = value['link']
    send_message(client, message.channel, """Current Raffle Item:

**1st Place**

Game: **{}**
Description:
*{}*

{}

**2nd Place**

2 Random Steam Keys

**3rd Place**

1 Random Steam Key

Raffle Date: **{}(ish)**

You will be contacted if you win. To win you must purchase tickets with the !buyticket command for 100 credits.
You can get extra credits by playing !slots <amount> and !bet <amount> on BlackJack.

**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.*
""".format(title, byteify(description), link, date))
    return


def do_buyticket(client, message_parts, message):
    log("Buying Ticket")
    member = data.db_get_member(message.author.id)
    log("Member: {}".format(member,))
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
    else:
        log("Buying Ticket for: {}".format(byteify(member['member_name'])))
        result, response = data.db_buy_ticket(member['member_id'], 1)
        log("Buy Result: {} - {}".format(result, response))
        if not result:
            send_message(client, message.author, response)
            return

        credits = data.db_get_credit(member['member_id'])
        send_message(client, message.author, "Raffle ticket purchased. Tickets: {} Credits: {}".format(response, credits))
    return


def do_balance(client, message_parts, message):
    member = data.db_get_member(message.author.id)
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
    else:
        pankration_data = data.db_get_pankration_record(member['member_id'])
        if pankration_data and 'wins' in pankration_data:
            send_message(client, message.author, "Credits: {}\nTickets: {}\nPankration Wins: {}\nPankration Losses: {}".format(member['credits'], member['tickets'], pankration_data['wins'], pankration_data['losses']))
        else:
            send_message(client, message.author, "Credits: {}\nTickets: {}".format(member['credits'], member['tickets']))
    return


def do_slotsrules(client, message_parts, message):
    send_message(client, message.channel, """Paying Combinations:

:moneybag:\t:moneybag:\t:moneybag:\t\t\t  pays\t250
:bell:\t:bell:\t:bell:/:moneybag:\tpays\t20
:diamonds:\t:diamonds:\t:diamonds:/:moneybag:\tpays\t14
:spades:\t:spades:\t:spades:/:moneybag:\tpays\t10
:cherries:\t:cherries:\t:cherries:\t\t\t  pays\t7
:cherries:\t:cherries:\t  -\t\t\t\t pays\t5
:cherries:\t  -\t\t  -\t\t\t\t pays\t2

:black_square_button:\tblank space

All payouts are in credits. Each pull costs 1 credit.

Max Bet: 10 credits

To Play: !slots <bet>""")
    return


def do_slots(client, message_parts, message):
    member = data.db_get_member(message.author.id)
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
        return
    elif type(message.channel) is not discord.channel.PrivateChannel:
        send_message(client, message.author, "You must make all bets / gaming via private message.")
        return
    bet_amount = message.content[7:]
    log("Member: {} Slots Bet: {}".format(member['member_name'], bet_amount))

    if not bet_amount.isdigit() or int(bet_amount) > 10 or int(bet_amount) < 0:
        send_message(client, message.author, "Please provide a bet amount up to 10 credits.")
        return
    result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
    if not result:
        send_message(client, message.author, error_message)
        return

    reel1 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
    reel2 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
    reel3 = [':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':black_square_button:', ':cherries:', ':cherries:', ':cherries:', ':spades:', ':spades:', ':spades:', ':hearts:', ':hearts:', ':diamonds:', ':bell:', ':moneybag:']
    #:moneybag: :bell: :diamonds: :spades:  :hearts: 
    val1 = random.choice(reel1)
    val2 = random.choice(reel2)
    val3 = random.choice(reel3)
    winnings = 0
    reels = [val1, val2, val3]
    cherries = reels.count(":cherries:")
    spades = reels.count(":spades:")
    diamonds = reels.count(":diamonds:")
    bells = reels.count(":bell:")
    moneybags = reels.count(":moneybag:")
    out_string = ""
    if moneybags == 3:
        out_string += "JACKPOT!!"
        winnings = 250
    elif bells == 3 or (bells == 2 and moneybags == 1):
        winnings = 20
    elif diamonds == 3 or (diamonds == 2 and moneybags == 1):
        winnings = 14
    elif spades == 3 or (spades == 2 and moneybags == 1):
        winnings = 10
    elif cherries == 3:
        winnings = 7
    elif cherries == 2:
        winnings = 5
    elif cherries == 1:
        winnings = 2
    out_string = """| {} | {} | {} |\n\n""".format(val1, val2, val3)
    winnings = int(winnings * int(bet_amount))
    if winnings > 0:
        out_string += "You Won! Total Winnings: {}".format(winnings,)
        log("Member: {} Wins: {}".format(member['member_name'], winnings))

    else:
        out_string += "You lose. Total Winnings: {}".format(winnings,)
    if winnings > 0:
        result, error_message = data.db_update_credit(member['member_id'], winnings)
        if not result:
            send_message(client, message.author, error_message)
            return

    credits = data.db_get_credit(member['member_id'])
    out_string += "\nCredits: {}".format(credits)

    send_message(client, message.author, out_string)
    return


def do_bj_hit(client, message_parts, message):
    member = data.db_get_member(message.author.id)
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
    elif type(message.channel) is not discord.channel.PrivateChannel:
        send_message(client, message.author, "You must make all bets / gaming via private message.")
    else:
        state = data.db_get_minigame_state(member['member_id'], 'blackjack')
        if state:
            out_string = ""
            bj = pickle.loads(str(state))
            bj.draw()
            out_string += bj.print_hand()
            actions = bj.get_actions()
            if len(actions) > 0:
                out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
                data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
            else:
                win, response = bj.is_win()
                out_string += "\n\n" + bj.print_hand(show_dealer=True)
                out_string += "\n\n" + response.format(win,)
                data.db_delete_minigame_state(member['member_id'], 'blackjack')
                log("{} - {}".format(member['member_name'], response.format(win,)))
                result, error_message = data.db_update_credit(member['member_id'], int(win))
                if not result:
                    send_message(client, message.author, error_message)
                    return

                credits = data.db_get_credit(member['member_id'])
                out_string += "\nCredits: {}".format(credits)

            send_message(client, message.author, out_string)

        else:
            send_message(client, message.author, "You must start a game with !bet before you can ask for a new card.")
    return


def do_bj_stay(client, message_parts, message):
    member = data.db_get_member(message.author.id)
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
    elif type(message.channel) is not discord.channel.PrivateChannel:
        send_message(client, message.author, "You must make all bets / gaming via private message.")
    else:
        state = data.db_get_minigame_state(member['member_id'], 'blackjack')
        if state:
            out_string = ""
            bj = pickle.loads(str(state))

            win, response = bj.is_win()
            out_string += "\n\n" + bj.print_hand(show_dealer=True)
            out_string += "\n\n" + response.format(win,)
            data.db_delete_minigame_state(member['member_id'], 'blackjack')
            log("{} - {}".format(member['member_name'], response.format(win,)))
            result, error_message = data.db_update_credit(member['member_id'], int(win))
            if not result:
                send_message(client, message.author, error_message)
                return
            credits = data.db_get_credit(member['member_id'])
            out_string += "\nCredits: {}".format(credits)
            send_message(client, message.author, out_string)
    return


def do_bj_bet(client, message_parts, message):
    member = data.db_get_member(message.author.id)
    if not member:
        send_message(client, message.author, "There was a problem looking up your information.")
    elif type(message.channel) is not discord.channel.PrivateChannel:
        send_message(client, message.author, "You must make all bets / gaming via private message.")
    else:
        state = data.db_get_minigame_state(member['member_id'], 'blackjack')
        if state:
            send_message(client, message.author, "You are already playing a game!")

            out_string = ""
            bj = pickle.loads(str(state))
            out_string += bj.print_hand()
            actions = bj.get_actions()
            if len(actions) > 0:
                out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
                data.db_add_minigame(member['member_id'], 'blackjack', bj.serialize())
            else:
                win, response = bj.is_win()
                out_string += "\n\n" + bj.print_hand(show_dealer=True)
                out_string += "\n\n" + response.format(win,)
                data.db_delete_minigame_state(member['member_id'], 'blackjack')
                log("{} - {}".format(member['member_name'], response.format(win,)))
                result, error_message = data.db_update_credit(member['member_id'], int(win))
                if not result:
                    send_message(client, message.author, error_message)
                    return
                credits = data.db_get_credit(member['member_id'])
                out_string += "\nCredits: {}".format(credits)

            send_message(client, message.author, out_string)

            return

        out_string = ""
        bet_amount = message.content[5:]
        log("Member: {} Bet: {}".format(member['member_name'], bet_amount))

        if not bet_amount.isdigit():
            send_message(client, message.author, "Please provide a bet amount. !bet 10")
            return

        result, error_message = data.db_update_credit(member['member_id'], -int(bet_amount))
        if not result:
            send_message(client, message.author, error_message)
            return
        out_string += "Welcome to BlackJack! :flower_playing_cards: You have placed a bet of: {}\n".format(bet_amount)
        bj = Blackjack(bet_amount)
        out_string += bj.print_hand()
        actions = bj.get_actions()
        if len(actions) > 0:
            out_string += '\n\nPlease choose an option [{}]\n'.format(', '.join(actions))
            data.db_add_minigame(member['member_id'], 'blackjack', pickle.dumps(bj))
        else:
            win, response = bj.is_win()
            out_string += "\n\n" + bj.print_hand(show_dealer=True)
            out_string += "\n\n" + response.format(win,)
            data.db_delete_minigame_state(member['member_id'], 'blackjack')
            log("{} - {}".format(member['member_name'], response.format(win,)))
            result, error_message = data.db_update_credit(member['member_id'], int(win))
            if not result:
                send_message(client, message.author, error_message)
                return
            credits = data.db_get_credit(member['member_id'])
            out_string += "\nCredits: {}".format(credits)

        send_message(client, message.author, out_string)
    return


def do_msg(client, message_parts, message):
    channel = message.channel
    author = message.author
    username = ''
    try:
        # TODO: Switch message_bits with message_parts
        message_bits = message.content.split(" ")
        msg_datetime = datetime.datetime.now()
        msg_idx = 2
        if message_bits[2] == 'in' and message_bits[3].isdigit():
            time = int(message_bits[3])
            msg_idx = 4
            if message_bits[4].startswith('sec'):
                msg_datetime = msg_datetime + datetime.timedelta(seconds=time)
                msg_idx = 5
            elif message_bits[4].startswith('hour'):
                msg_datetime = msg_datetime + datetime.timedelta(hours=time)
                msg_idx = 5
            elif message_bits[4].startswith('day'):
                msg_datetime = msg_datetime + datetime.timedelta(days=time)
                msg_idx = 5
            else: # minutes by default
                msg_datetime = msg_datetime + datetime.timedelta(minutes=time)
                msg_idx = 5
        elif message_bits[2] == 'on':
            try:
                tmp_date = parse(message_bits[3])
                msg_datetime = tmp_date
                msg_idx = 4
            except ValueError:
                send_message(client, channel, 'Your shitty message has been rejected {}. Next time learn how to date...MM\\DD\\YYYY'.format(message.author.mention()))
                return

        username = message_bits[1]
        user_mention = ''
        # TODO: have it look in the database. Do this AFTER on startup we add all users.
        for member in client.get_all_members():
            if username.lower() == member.name.lower():
                user_mention = member.mention()
                user_id = member.id
                break
        if user_mention == '':
            send_message(client, channel, 'Your shitty message has been rejected {}. That user does not exist.'.format(message.author.name))
            return

        msg_text = byteify(' '.join(message_bits[msg_idx:]))
        message = {'user_id': user_id, 'channel': channel.id, 'delivery_time': msg_datetime.strftime('%Y/%m/%d %H:%M:%S'), 'message': msg_text}
        log("Message: %s" % byteify(message))
        data.db_add_message(msg_text, msg_datetime.strftime('%Y-%m-%d %H:%M:%S'), channel.id, author.mention(), user_mention, user_id)
        # print("Data: %s" % data)
        #test_ch = Object(channel.id)
        #client.send_message(test_ch, 'Test Message {}.'.format(author))
    except Exception as e:
        send_message(client, channel, 'Your shitty message has been rejected {}. {}'.format(author.name, format_exception(e)))
        return
    if msg_datetime < datetime.datetime.now():
        send_message(client, channel, '{} your message will be delivered to {} as soon as they are available.'.format(author.name, user_mention))
    else:
        send_message(client, channel, '{} your message will be delivered to {} {}.'.format(author.name, user_mention, human(msg_datetime)))            
    check_msg_queue(client)
    return


def do_addfortune(client, message_parts, message):
    try:
        fortune = message.content[11:]
        if 'aa737a5846' in fortune:
            send_message(client, message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
            return
        date_added = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        data.db_add_fortune(fortune, date_added)
        log("Added fortune")
    except Exception as e:
        log(e.message)
        send_message(client, message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
        return
    send_message(client, message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))
    return


def do_fortune(client, message_parts, message):
    fortune = None
    try:
        fortune = data.db_get_fortune()
        log(fortune)
    except Exception as e:
        log(e)
        pass
    if not fortune:
        send_message(client, message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))
    else:
        send_message(client, message.channel, '{} Your fortune is... {}'.format(message.author.mention(), byteify(fortune)))
    return


def do_question(client, message_parts, message):
    question = message.content[10:]
    if "is it gay" in question:
        send_message(client, message.channel, 'Yes {}, it is gay.'.format(message.author.mention()))
        return
    res = wolf.query(question)
    try:
        if len(res.pods):
            pod_text = []
            for pod in res.pods:
                if pod.text:
                    pod_text.append(pod.text)
            send_message(client, message.channel, '{} {}.'.format(message.author.mention(), byteify("\n".join(pod_text)[:1990])))
        else:
            tagged_sent = pos_tag(question.replace('?', '').split())
            proper_nouns = [word for word, pos in tagged_sent if pos == 'NNP']
            wiki_search = " ".join(proper_nouns)
            if wiki_search.strip() != "":
                log("Looking up {}".format(wiki_search))
                wiki_out = wikipedia.summary(wiki_search, sentences=3)
                send_message(client, message.channel, '{} {}.'.format(message.author.mention(), byteify(wiki_out)))
            else:
                send_message(client, message.channel, 'I don\'t know {}.'.format(message.author.mention()))
        return
    except Exception as e:
        log(format_exception(e))
        send_message(client, message.channel, 'I don\'t know {}.'.format(message.author.mention()))
        return


def do_addjoke(client, message_parts, message):
    try:
        joke = message.content[8:]
        if 'aa737a5846' in joke:
            send_message(client, message.channel, '{} you stop it, you are a pedofile, stop looking at little girls.'.format(message.author.mention()))
            return
        data.db_add_joke(joke)
        log("Added joke")
    except Exception as e:
        log(e.message)
        send_message(client, message.channel, 'Your shitty joke has been rejected {}.'.format(message.author.mention()))
        return
    send_message(client, message.channel, 'Your shitty joke has been added {}.'.format(message.author.mention()))
    return


def do_joke(client, message_parts, message):
    joke = None
    try:
        joke = data.db_get_joke()
        log(joke)
    except Exception as e:
        log(e)
        pass
    if not joke:
        send_message(client, message.channel, 'Try adding a joke with "!addjoke <joke>" {}!'.format(message.author.mention()))
    else:
        send_message(client, message.channel, '{} {}'.format(message.author.mention(), byteify(joke)))
    return


def do_secret(client, message_parts, message):
    send_message(client, message.channel, 'git gud {}! My source is here: http://git.savsoul.com/barry/discordbot\nVersion: {}'.format(message.author.mention(), VERSION))
    return


def do_waifu(client, message_parts, message):
    send_message(client, message.channel, 'http://orig13.deviantart.net/b25e/f/2014/175/3/d/no_waifu_no_laifu_by_imtheonenexttome-d7nsx3b.gif {}!'.format(message.author.mention()))
    return


def do_hillary(client, message_parts, message):
    send_message(client, message.channel, ':bomb: Ohhhhhh, now you done it...:bomb:'.format(message.author.mention()))
    return


def do_squid(client, message_parts, message):
    send_message(client, message.channel, 'くコ:彡         くコ:彡            くコ:彡          くコ:彡')
    return


def do_stars(client, message_parts, message):
    send_message(client, message.channel, '✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈  ✮═━┈  ✰═━┈ ✰═━┈┈ ✰═━┈┈')
    return


def do_rigged(client, message_parts, message):
    lines = open('studylyrics.txt').read().splitlines()
    send_message(client, message.channel, ":musical_note: {} :musical_note:".format(byteify(random.choice(lines))))
    return

#### PANKRATION


def do_pankration(client, message_parts, message):
        send_message(client, message.channel, """**NOTE! This is NOT implemented yet.. only partially**
{} Available Commands:

*Hunting for Soul Plates:*
    **!listzones** - Returns a list of zones available for hunting and how many credits it costs to search in that zone. Depending on the weather and other factors some zones may not always be available.
    **!hunt <zone>** - An attempt will be made to search for a soul plate (monster) in the zone specified. Each search costs a certain amount of credits. Each zone has a different cost.

*Viewing Your Inventory:*
    **!soulplates** - Returns a list of all soul plates you have in your posession.
    **!reflectors** - Returns a list of all reflectors you have in your posession (The available monsters you can fight with).
    **!skills** - Returns a list of all feral skills you have in your inventory

*Editing Your Collections:*
    **!convert <plate number> <convert_to>** - From the list of soul plates you can choose to either convert the plate into a \"reflector\" or \"skill\".
        Ex:  **!convertplate 1 reflector**
             **!convertplate 4 skill**
    **!equip <skill num> <reflector number>** - Assigns a skill to a reflector. Each skill is worth a certain amount of feral points, each monster has a maximum of feral points available.
    **!setreflectorname <reflector number> <name>** - This will rename a monster in your collection to a custom name.

*Arena Battle:*
    **!battle <reflector number>** - Adds your reflector to the queue in the arena.  When the arena is available your monster will be paired with either another players monster or a similarly matched arena monster.
    **!battle <reflector number> <player name>** - If you want to challenge a specific user to a battle just provide their user name. Have them do the same and your battle will start when the arena is available.

""".format(message.author.mention()))

def do_set_reflector_name(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    if len(message_parts) < 2:
        send_message(client, message.channel, 'You must provide the reflector number and the new name.')
        return

    reflector_num = message_parts[0]
    new_name = ' '.join(message_parts[1:])
    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and pankration_data['reflectors']:
        reflectors = pickle.loads(str(pankration_data['reflectors']))

        if not reflector_num.isdigit() or int(reflector_num) < 1 or int(reflector_num) > len(reflectors):
            send_message(client, message.channel, 'The requested reflector is invalid. Please provide the number from !reflectors')
            return
        reflector_num = int(reflector_num) - 1
        reflectors[reflector_num].set_monster_name(new_name)
        data.db_update_pankration_record(member['member_id'], 'reflectors', pickle.dumps(reflectors))
        send_message(client, message.channel, 'The reflector (monster) name has been updated.')        
    else:
        send_message(client, message.channel, 'Unable to find the reflector data.')

def do_register_battle(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    if len(message_parts) < 1:
        send_message(client, message.channel, 'You must provide at least 1 arguments to register for a battle. The reflector number and optionally a user name you wish to battle.  Please see !pankration for an example.')
        return

    reflector_num = message_parts[0]
    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and pankration_data['reflectors']:
        reflectors = pickle.loads(str(pankration_data['reflectors']))

        if not reflector_num.isdigit() or int(reflector_num) < 1 or int(reflector_num) > len(reflectors):
            send_message(client, message.channel, 'The requested reflector is invalid. Please provide the number from !reflectors')
            return
        reflector_num = int(reflector_num) - 1

        if len(message_parts) > 1:
            username = ' '.join(message_parts[1:])

            target_member = data.db_get_member(username=username)
            if target_member and 'member_id' in target_member:
                data.db_register_battle(member['member_id'], reflectors[reflector_num], reflector_num, target_member['member_id'])
                send_message(client, message.channel, "Your *{} level {}* has been registered for battle with {}. The battle will begin when the arena is availble with the next challenger".format(reflectors[reflector_num].get_monster_name(), reflectors[reflector_num].level, username))
            else:
                send_message(client, message.channel, "There was a problem looking up that user.")
        else:
            data.db_register_battle(member['member_id'], reflectors[reflector_num], reflector_num)
            send_message(client, message.channel, "Your *{} level {}* has been registered for battle. The battle will begin when the arena is availble with the next challenger".format(reflectors[reflector_num].get_monster_name(), reflectors[reflector_num].level))
    else:
        send_message(client, message.channel, 'You have no available reflectors. You can get reflectors by converting soul plates with !convert')
        return


def do_assign_skill(client, message_parts, message):
    send_message(client, message.channel, '**Feral Skills are not yet supported**')


def do_convert_plate(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and pankration_data['soul_plates']:
        log(message_parts)
        if len(message_parts) < 2:
            send_message(client, message.channel, 'You must provide at least 2 arguments for converting a plate. The plate number and the type of conversion.  Please see !pankration for an example.')
            return

        plate_num = message_parts[0]
        convert_to = message_parts[1]

        soul_plates = pickle.loads(str(pankration_data['soul_plates']))
        if not plate_num.isdigit() or int(plate_num) < 1 or int(plate_num) > len(soul_plates):
            send_message(client, message.channel, 'The requested plate is invalid. Please provide the number from !plates')
            return
        plate_num = int(plate_num) - 1
        if convert_to == "reflector":
            # do reflector stuff
            if data.db_convert_soul_plate_to_reflector(member['member_id'], soul_plates[plate_num], plate_num):
                send_message(client, message.channel, 'The soul plate was successfully converted into an official reflector. To view your reflectors: !reflectors')
                return
            else:
                send_message(client, message.channel, 'There was an issue converting your soul plate...Conversion failed.')                
                return
        elif convert_to == "skill":
            soul_plates[plate_num].convert_to_feral_skill()
            skill = soul_plates[plate_num].convert_to_feral_skill()
            if not skill:
                send_message(client, message.channel, 'The conversion **failed** the soul plate has been destroyed in the process.')
                return
            else:
                send_message(client, message.channel, 'Congratulations! The soul plate was converted to feral skill: **{}**'.format(byteify(skill)))
                data.db_convert_soul_plate_to_skill(member['member_id'], soul_plates[plate_num], plate_num, skill)
                do_list_feral_skills(client, message_parts, message)
                return
        else:
            send_message(client, message.channel, 'A plate can only be converted into a reflector or skill.  Please see !pankration for an example.')
            return

        #send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(soul_plate)) for idx, soul_plate in enumerate(soul_plates)))
    else:
        send_message(client, message.channel, 'You have no soul plates to convert.')


def do_list_soul_plates(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and 'soul_plates' in pankration_data:
        soul_plates = pickle.loads(str(pankration_data['soul_plates']))
        if len(soul_plates) > 0:
            send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(soul_plate.get_soul_plate_description())) for idx, soul_plate in enumerate(soul_plates)))
        else:
            send_message(client, message.channel, 'You have no soul plates.')
    else:
        send_message(client, message.channel, 'You have no soul plates.')


def do_list_reflectors(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and pankration_data['reflectors']:
        reflectors = pickle.loads(str(pankration_data['reflectors']))
        if len(reflectors) > 0:
            send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(reflector)) for idx, reflector in enumerate(reflectors)))
        else:
            send_message(client, message.channel, 'You have no reflectors.')
    else:
        send_message(client, message.channel, 'You have no reflectors.')


def do_equip_feral_skills(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    skill_num = message_parts[0]
    reflector_num = message_parts[1]

    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and pankration_data['reflectors']:
        reflectors = pickle.loads(str(pankration_data['reflectors']))

        if pankration_data and pankration_data['feral_skills']:
            feral_skills = pickle.loads(str(pankration_data['feral_skills']))

            if not skill_num.isdigit() or int(skill_num) < 1 or int(skill_num) > len(feral_skills):
                send_message(client, message.channel, 'The requested feral skill is invalid. Please provide the number from !skills')
                return
            skill_num = int(skill_num) - 1
            if not reflector_num.isdigit() or int(reflector_num) < 1 or int(reflector_num) > len(reflectors):
                send_message(client, message.channel, 'The requested reflector is invalid. Please provide the number from !reflectors')
                return
            reflector_num = int(reflector_num) - 1

            skill_name = feral_skills[skill_num]
            print(reflector_num)
            print(reflectors[reflector_num])
            success, err_message = reflectors[reflector_num].equip_feral_skill(skill_name)
            if not success:
                send_message(client, message.channel, byteify(err_message))
            else:
                data.db_update_pankration_record(member['member_id'], 'reflectors', pickle.dumps(reflectors))
                send_message(client, message.channel, "{} has been equipped.\n{}".format(skill_name, reflectors[reflector_num]))

        else:
            send_message(client, message.channel, 'You have no feral skills. You can get more feral skills by hunting for soul plates and converting them into skills.')
    else:
        send_message(client, message.channel, 'You have no reflectors. You can get more reflectors by hunting monsters and converting soul plates into reflectors.')


def do_list_feral_skills(client, message_parts, message):
    member = data.db_get_member(message.author.id)

    pankration_data = data.db_get_pankration_record(member['member_id'])
    if pankration_data and pankration_data['feral_skills']:
        feral_skills = pickle.loads(str(pankration_data['feral_skills']))
        send_message(client, message.channel, "\n\n".join("{}. {}".format(idx+1, str(feral_skill)) for idx, feral_skill in enumerate(feral_skills)))
    else:
        send_message(client, message.channel, 'You have no feral skills.')


def do_hunt_monster(client, message_parts, message):
    p = Pankration()
    zone = ' '.join(message_parts)
    cost = p.get_zone_cost(zone)
    if cost == False:
        send_message(client, message.channel, 'The zone was not found.')
        return
    else:
        member = data.db_get_member(message.author.id)
        if not member:
            send_message(client, message.author, "There was a problem looking up your information.")
            return
        result, error_message = data.db_update_credit(member['member_id'], -cost)
        if not result:
            send_message(client, message.author, error_message)
            return
    send_message(client, message.channel, '{} Soul Plate purchased for {} credits\n Hunting in {}'.format(message.author.name, cost, zone))
    time.sleep(3)
    hunt_response = p.hunt_monster(' '.join(message_parts))
    str_out = hunt_response.message + "\n\n"
    if hunt_response.result == HuntResponse.SUCCESS:
        soul_plate = hunt_response.monster
        member = data.db_get_member(message.author.id)
        data.db_add_soul_plate(member['member_id'], soul_plate)
        str_out += str(soul_plate.get_soul_plate_description())
    send_message(client, message.channel, "{} {}".format(message.author.name, str_out))


def do_list_zones(client, message_parts, message):
    p = Pankration()
    zones = p.list_zones()
    # out_str = ""
    # for zone_name, zone in zones.iteritems():
    #     out_str += "{} - {}\n".format(zones[idx]['cost'], idx)
    # send_message(client, message.channel, out_str)
    out_str = 'Credit Cost - Zone Name\n--------------------------------\n' + '\n'.join(["{} - {}".format(zone['cost'], zone_name.title()) for zone_name, zone in zones.iteritems()])
    send_message(client, message.channel, out_str)
    return


def check_arena():
    global battle_in_progress
    if battle_in_progress:
        return
    try:
        battle_in_progress = True
        battle = data.db_get_battle_queue()
        if len(battle) == 0:
            return
        battle = battle[0]

        for channel in client.get_all_channels():
            if channel.id == '151942626130657280':
                arena_channel = channel
                break
        # pop first battle off queue
        log("Starting Battle: {}".format(battle['battle_id']))
        monster = pickle.loads(str(battle['reflector_primary']))
        monster2 = pickle.loads(str(battle['reflector_secondary']))

        send_message(client, arena_channel, "Ladies and gentlemen!\nFor our next match...")
        time.sleep(5)
        send_message(client, arena_channel, "In the red corner we have...\n  **{}**!".format(monster.get_monster_name()))
        time.sleep(5)
        send_message(client, arena_channel, "Hmmm... This monster seems {} and {}.".format(monster.get_current_posture()["name"], monster.get_current_attitude()["name"]))
        time.sleep(5)
        send_message(client, arena_channel, "And in the blue corner is...\n  **{}**!".format(monster2.get_monster_name()))
        time.sleep(5)
        send_message(client, arena_channel, "Hmmm... This monster seems {} and {}.".format(monster2.get_current_posture()["name"], monster2.get_current_attitude()["name"]))
        time.sleep(5)
        send_message(client, arena_channel, "Alright, Pankration fans, the match is about to begin!\n  *Chaaaaaarge!*".format(monster2.get_monster_name()))
        time.sleep(5)
        data.db_start_battle(battle['battle_id'])

        p = Pankration()
        
        battle_arena = p.start_battle(monster, monster2, "not used")
        fighting = True
        winner = 1
        while fighting:
            actions = battle_arena.step()
            time.sleep(3)
            out_str = ""
            for action in actions:
                # TODO: Decide if I should merge magicresistaction with miss action
                if isinstance(action, MagicResistAction):
                    out_str += "{} {} {} while casting {}.\n".format(action.attacker.get_monster_name(), action.message, action.target.get_monster_name(), action.spell)
                if isinstance(action, MissAction):
                    if action.spell:
                        out_str += "{} {} {} while casting {}.\n".format(action.attacker.get_monster_name(), action.message, action.target.get_monster_name(), action.spell)
                    else:
                        out_str += "{} {} {}.\n".format(action.attacker.get_monster_name(), action.message, action.target.get_monster_name())
                if isinstance(action, AttackAction):
                    if action.spell:
                        out_str += "{} {} {} against {} for {}.\n".format(action.attacker.get_monster_name(), action.message, action.spell, action.target.get_monster_name(), int(action.damage))
                    else:
                        out_str += "{} {} {} for {}.\n".format(action.attacker.get_monster_name(), action.message, action.target.get_monster_name(), int(action.damage))
                if isinstance(action, DefeatAction):
                    out_str += "\n\n**{}** {}. {} gains {} xp.\n\n".format(action.target.get_monster_name(), action.message, action.attacker.get_monster_name(), action.xp)
                    fighting = False
                    if action.attacker == monster:
                        result, xp_msg = monster.add_xp(action.xp)
                        # give a small amount to the loser
                        if result:
                            out_str += xp_msg
                        result, xp_msg = monster2.add_xp(action.losing_xp)
                        if result:
                            out_str += xp_msg
                        winner = 1
                        monster.wins += 1
                        monster2.losses += 1
                    else:
                        # give a small amount to the loser
                        result, xp_msg = monster2.add_xp(action.xp)
                        # give a small amount to the loser
                        if result:
                            out_str += xp_msg
                        result, xp_msg = monster.add_xp(action.losing_xp)
                        if result:
                            out_str += xp_msg
                        winner = 2
                        monster2.wins += 1
                        monster.losses += 1
                    break
            if fighting:
                out_str += "\n{} {}%    -    {} {}%\n".format(monster.get_monster_name(), monster.get_hp_percent(), monster2.get_monster_name(), monster2.get_hp_percent())
            log(out_str)
            send_message(client, arena_channel, byteify(out_str))
        # Heal the monsters before they are returned to the player inventory
        monster.hp = monster.get_hp()
        monster2.hp = monster2.get_hp()
        data.db_complete_battle(battle['battle_id'], battle['primary_member_id'], monster, battle['secondary_member_id'], monster2, winner)

        #wait after each match before starting a new fight.
        time.sleep(30)
    except Exception as e:
        log("{} - {}".format(format_exception(e), e.message))
    finally:
        battle_in_progress = False

### END PANKRATION
def start_timer(client):
    needs_loot = True
    time_to_ping = 6
    while not quitting:
        if time_to_ping >= 6:
            check_pings()
            time_to_ping = 0
        time_to_ping += 1
        if not battle_in_progress:
            thread.start_new_thread(check_arena, ())

        if datetime.datetime.now().hour == grant_hour:
            needs_loot = True
        # This should fire anytime they need loot and it isn't 9.. this will change to 11 after testing
        if datetime.datetime.now().hour != grant_hour and needs_loot:
            for channel in client.get_all_channels():
                if channel.id == '47934985176354816':
                    do_grantcredits(client, None, None, channel)
                    needs_loot = False
        time.sleep(10)
        # log('Sleeping... Time: {}'.format(datetime.datetime.now()))


def thread_exception_handler(method, client, message_parts, message):
    try:
        if message:
            globals()[method](client, message_parts, message)
        else:
            globals()[method](client)
    except Exception as e:
        error_message = "{} - {}".format(format_exception(e), e.message)
        message_bot_owner("Exception: {}".format(error_message))
        log(error_message)


#################
# Client Events
#################
@client.event
def on_socket_raw_send(payload, binary=False):
    check_msg_queue(client)


@client.event
def on_status(member):
    for member in client.get_all_members():
        try:
            db_member = data.db_get_member(member.id)

            if not db_member:
                log("Creating new member: {}".format(member))
                data.db_create_member(member)
            else:
                data.db_update_member(member, db_member)

            check_msg_queue(client)
        except Exception as e:
            log("Exception: {}".format(format_exception(e)))
            pass


@client.event
def on_message(message):
    # print message.content
    # print message.author
    # print client.user
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    message_parts = message.content.split(" ")
    for command, method in registered_commands.iteritems():
        if message_parts[0] == command:
            try:
                log("Calling {}".format(method,))
                thread.start_new_thread(thread_exception_handler, (method, client, message_parts[1:], message))
            except Exception as e:
                log("{} - {}".format(format_exception(e), e.message))
            return

    if message.content.lower().startswith(client.user.name.lower()):
        log('Someone is talking to %s' % (client.user.name.lower(),))
        if ' or ' in message.content:
            questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
            send_message(client, message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8', errors='ignore')))

def message_bot_owner(message):
    for member in client.get_all_members():
        if member.id == '78767557628133376':
            send_message(client, member, message)
            break

@client.event
def on_ready():
    log('Logged in as')
    log(client.user.name)
    log(client.user.id)
    log('------')
    message_bot_owner("Bot Started.")

    check_msg_queue(client)

    thread.start_new_thread(thread_exception_handler, ('start_timer', client, None, None))

retries = 0
while retries < 1000:
    try:
        json_data = open(credentials).read()
        creds = json.loads(json_data)
        wolf = wolframalpha.Client(creds['wolframkey'])
        client.login(creds['username'], creds['password'])
        client.run()
    except KeyboardInterrupt:
        quitting = True
        conn.close
        quit()
    except Exception as e:
        retries += 1
        log("Shit I crashed: {}\nRetry {}".format(e, retries))
        #time.sleep(1)