summaryrefslogblamecommitdiff
path: root/plugins/manaboy.py
blob: b145cdbebc66b11bcfb26cd9b24b53731a2f2c78 (plain) (tree)
1
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
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
                 







































                                                            


                                               

                               
        




                                                                
                                                          
                  
                                         
         
                                                                  



                                           

























                                                                                                                                                 






                                                                                              











































































































                                                                                                                                             
                                                             





                                                                                                                                                                                                                    
                                                                                                                
                       





















                                                                                                          

























































































                                                                                                                                                                                          












                                                                    
                                                

                                   






































































                                                                                                                                                                                                               

                                                               










































                                                                       
                                            
















                             
                              
                       



















                                                          
                         





















                                       
                       












                                                                               

                           





                               


                                                                 

                                                      









                                            
                                      




                                                   
                                        





























































































































































































































































































































































































































































































                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    
                           













































































































































































































































































































































































                                                                                 




                        





                               
                            





                                           
 






































                                                                                     
import subprocess
import time
import net.mapserv as mapserv
import net.charserv as charserv
import net.stats as stats
import commands
import walkto
import logicmanager
import status
import plugins
import itemdb
import random
from collections import deque
from net.inventory import get_item_index, get_storage_index
from utils import extends
from actor import find_nearest_being
from chat import send_whisper as whisper

from net.onlineusers import OnlineUsers

__all__ = [ 'PLUGIN', 'init' ]

def preloadArray(nfile):
    try:
        file = open(nfile, "r")
        array=[]
        for x in file.readlines():
            x = x.replace("\n", "")
            x = x.replace("\r", "")
            array.append(x)
        file.close()
        return array
    except:
        print "preloadArray: File " +  nfile + " not found!"

joke_answers        = preloadArray("bot/jokes.txt")
ignored_players     = preloadArray("bot/ignored.txt")
disliked_players    = preloadArray("bot/disliked.txt")
admins              = preloadArray("bot/admins.txt")
friends             = preloadArray("bot/friends.txt")

# ====================== XECUTE =============

def XECUTE(nick, is_whisper, command, args=""):
    if nick in ignored_players:
        return
    try:
        if args=="":
            s = subprocess.check_output([command])
        else:
            s = subprocess.check_output([command, args])        
    except:
        s=("Damn! Command has failed! " + command).strip()
    if is_whisper:
        whisper(nick,(s.strip('\r\n\t')))
    else:
        mapserv.cmsg_chat_message(nick + ": " + s.strip('\r\n\t'))

# ====================== XCAL =============

def XCAL(nick, message, is_whisper, match):

    XECUTE(nick, is_whisper, "calc",match.group(1))
    # ~ XECUTE(nick, is_whisper, "echo \'" + match.group(1) + "\' | bc")

    # ~ try:
        # ~ p = subprocess.Popen(['/home/livio/livio/a.out'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        # ~ p.stdin.write("\'" + match.group(1) + "\'")
        # ~ p.stdin.flush()
        # ~ while p.poll() == None:
    
            # ~ s = p.stdout.readline().strip()
    # ~ except OSError as e:
        # ~ s = "Execution dammit failed!"
        # ~ print e

    # ~ if is_whisper:
        # ~ whisper(nick,s)
    # ~ else:
        # ~ mapserv.cmsg_chat_message(s)
    # ~ try:
        # ~ s = subprocess.getoutput("echo \'" + match.group(1) + "\' | bc") # Dammit. This one is not good. Shell command injection is possible.

    # ~ except OSError as e:
        # ~ s = "Execution dammit failed: "+  e



# === eXecute on Unix ===========

def XUfortune(nick, message, is_whisper, match):    XECUTE(nick, is_whisper, "fortune", "-s")
def XUdate(nick, message, is_whisper, match):       XECUTE(nick, is_whisper, "/bin/date")
def XUpom(nick, message, is_whisper, match):        XECUTE(nick, is_whisper, "/usr/games/pom")

# ====================== XCOM =============
XCOMList            = preloadArray("bot/XCOM.txt")
XCOMServerStatInterested = [] #List of nicks interested in server status change
XCOMBroadcastPrefix = "##B##G "


def online_list_update(curr,prev):
    for x in curr:
        found = False
        for y in prev:
            if x==y: found = True
        if found == False: #detected change
            for nicks in XCOMList: #For every XCOM user...
                if nicks in online_users.online_users: #That's online...
                    if nicks in XCOMServerStatInterested: #If XCOM player is interested
                        if x in XCOMList: #An XCOM user connected?
                            XCOMDelay() #Share its status
                            whisper(nicks, "##W" + x + " is now online [XCOM]")
                        else: #Is a regular server player
                            if x not in XCOMList:
                                XCOMDelay() #Share its status
                                whisper(nicks, "##W" + x + " is now online")

    for x in prev:
        found = False
        for y in curr:
            if x==y: found = True
        if found == False:
            for nicks in XCOMList: #For every XCOM user...
                if nicks in online_users.online_users: #That's online...
                    if nicks in XCOMServerStatInterested: #If XCOM player is interested
                        if x in XCOMList: #An XCOM user connected?
                            XCOMDelay() #Share its status
                            whisper(nicks, "##L" + x + " is now offline [XCOM]")
                        else: #Is a regular server player
                            if x not in XCOMList:
                                XCOMDelay() #Share its status
                                whisper(nicks, "##L" + x + " is now offline")
                                
online_users = OnlineUsers(online_url=' https://server.themanaworld.org/online-old.txt', update_interval=20, refresh_hook=online_list_update)

def XCOMOnlineList(nick, message, is_whisper, match):
    XCOMDelay()
    msg=""
    for nicks in XCOMList:
        if nicks in online_users.online_users:
            msg = msg + nicks + " | "
    XCOMDelay()
    whisper(nick, msg)

def XCOMPrintStat():
    pOnline=0
    xOnline=0
    for p in online_users.online_users:
        pOnline=pOnline+1
        if p in XCOMList:
            xOnline=xOnline+1
    return "%(xOnline)d/%(pOnline)d"%{"pOnline": pOnline, "xOnline": xOnline,}

def XCOMDelay():
    time.sleep(0.1)

def XCOMBroadcast(message):
    for nicks in XCOMList:
        if nicks in online_users.online_users:
            if nicks not in ignored_players:
                XCOMDelay()
                whisper(nicks, message)

def XCOMCommunicate(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    if message[0]=="!":
        return
    if message.startswith("*AFK*:"): # AFK bug workaround
        return
    if nick in XCOMList:
        for nicks in XCOMList:
            if nicks in online_users.online_users:
                if nick==nicks:
                    pass
                else:
                    XCOMDelay()
                    whisper(nicks, "##B##LXCOM[" + XCOMPrintStat() + "]##l " + nick + ": ##b" + message)
    else:
        whisper(nick, XCOMBroadcastPrefix + "XCOM is not enabled (Use !xcon)")

def XCOMSilentInvite(nick, message, is_whisper, match):
    XCOMDelay()
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    if nick in admins:
        XCOMList.append(match.group(1))
        if match.group(1) not in ignored_players:
            whisper(nick, "##W--- " + nick + " silently invited " + match.group(1) + " on XCOM ---")
        else:
            whisper(nick, "##W" + match.group(1) + " has been ignored by bot and cannot be added to XCOM.")

def XCOMInvite(nick, message, is_whisper, match):
    XCOMDelay()
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    if nick in admins: # FIXME Do not add if already there!!!
        XCOMList.append(match.group(1))
        XCOMBroadcast("##W--- " + nick + " (Admin) invited " + match.group(1) + " on XCOM ---" + XCOMBroadcastPrefix + match.group(1) + " XCOM enabled! Use !xcoff to disable, use !xclist to see XCOM online list")
    else:
        if nick in ignored_players:
            whisper(nick, "You cannot invite banned players.") 
        else:
            whisper(match.group(1), "##W--- " + nick + " invited you to chat on XCOM --- Answer !xcon to join.")
            XCOMDelay()
            whisper(nick, "Invited " + match.group(1) + " to join XCOM. Waiting for his/her reply...")

XCOMServerInvited = []
def XCOMInviteAll(nick, message, is_whisper, match):
    XCOMDelay()
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    if nick in admins: # FIXME Do not add if already there!!!
        for invn in online_users.online_users:
            if invn in XCOMList:
                pass
            elif invn in ignored_players:
                pass
            elif invn in XCOMServerInvited:
                pass
            else:
                XCOMServerInvited.append(invn)
                whisper(invn, "##W--- " + nick + " invited you to chat on XCOM --- Answer !xcon to join.")
                XCOMDelay()


def XCOMEnable(nick, message, is_whisper, match):
    XCOMDelay()
    #accept only whispers
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    #search array
    if nick in XCOMList:
        whisper(nick, XCOMBroadcastPrefix + nick + " XCOM already enabled")
    else:
        XCOMList.append(nick)
        XCOMBroadcast("##W--- " + nick + " is online on XCOM ---" + XCOMBroadcastPrefix + nick + " XCOM enabled! Use !xcoff or !xcom off to disable, use !xclist to see XCOM online list")

def XCOMDisable(nick, message, is_whisper, match):
    XCOMDelay()
    #accept only whispers
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    #search array
    if nick in XCOMList:
        XCOMBroadcast("##L--- " + nick + " disabled XCOM ---")
        XCOMList.remove(nick)
    else:
        whisper(nick, XCOMBroadcastPrefix + nick + " XCOM already disabled")

def XCOMServerInterestEnable(nick, message, is_whisper, match):
    XCOMDelay()
    #accept only whispers
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    #search array
    if nick in XCOMList:
        whisper(nick, XCOMBroadcastPrefix + "Server online status notifications enabled!")
        XCOMServerStatInterested.append(nick)

def XCOMServerInterestDisable(nick, message, is_whisper, match):
    XCOMDelay()
    #accept only whispers
    if not is_whisper:
        return
    if nick in ignored_players:
        return #or say something
    #search array
    if nick in XCOMList:
        whisper(nick, XCOMBroadcastPrefix + "Server online status notifications disabled!")
        XCOMServerStatInterested.remove(nick)

def XCOMBan(nick, message, is_whisper, match):
    XCOMDelay()
    #accept only whispers
    if not is_whisper:
        return
    if nick in admins:
        #search array
        if match.group(1) in ignored_players:
            whisper(nick, "Already banned.")
        else:
            ignored_players.append(match.group(1))
            XCOMList.remove(match.group(1))
            #FIXME array need to be saved!!!
            XCOMBroadcast(XCOMBroadcastPrefix + match.group(1) + " is now banned from XCOM")
    else:
        whisper(nick, "Admins only.")

def XCOMUnBan(nick, message, is_whisper, match):
    XCOMDelay()
    #accept only whispers
    if not is_whisper:
        return
    if nick in admins:
        #search array
        if match.group(1) in ignored_players:
            XCOMList.append(match.group(1))
            ignored_players.remove(match.group(1))
            #FIXME array need to be saved!!!
            XCOMBroadcast(XCOMBroadcastPrefix + match.group(1) + " is now unbanned from XCOM")
            whisper(match.group(1), "You are now unbanned from XCOM. Don't make it happen again.")
        else:
            whisper(nick, "Already banned.")
    else:
        whisper(nick, "Admins only.")

# =============================================

greetings = [
    "Hi {0}!",
    "Hey {0}",
    "Yo {0}",
    "{0}!!!!",
    "{0}!!!",
    "{0}!!",
    "Hello {0}!!!",
    "Hello {0}!",
    "Welcome back {0}!",
    "Hello {0}! You are looking lovely today!",
    "Hello {0}! I'm the bot that you can trust: I want your money!",
    "{0} is back!!",
    "Hello and welcome to the Aperture Science \
computer-aided enrichment center.",
]

drop_items = [
    "a bomb", "a bowl of petunias", "a cake", "a candy", "a chocobo",
    "a coin", "a cookie", "a drunken pirate", "a freight train",
    "a fruit", "a mouboo", "an angry cat",
    "an angry polish spelling of a rare element with the atomic number 78",
    "an anvil", "an apple", "an iten", "a magic eightball", "a GM",
    "a whale", "an elephant", "a piano", "a piece of moon rock", "a pin",
    "a rock", "a tub", "a wet mop", "some bass", "Voldemort", "a sandworm",
    "a princess", "a prince", "an idea", "Luvia", "a penguin",
    "The Hitchhiker's Guide to the Galaxy",
]

dropping_other = [
    "Hu hu hu.. {0} kicked me!",
    "Ouch..",
    "Ouchy..",
    "*drops dead*",
    "*sighs*",
    "Leave me alone.",
    "Whoa, dammit!",
]

explain_sentences = {
    "livio" : "He created Liviobot.",
    "party" : "Is a group of players with their chat tab and they can share exp, items and HP status. See [[@@https://wiki.themanaworld.org/index.php/Legacy:Party_Skill|Party Wiki@@] for more informations.",
}

dropping_special = {
    "ShaiN2" : "*drops a nurse on {0}*",
    "Shainen" : "*drops a nurse on {0}*",
    "Silent Dawn" : "*drops a box of chocolate on {0}*",
    "veryape" : "*drops a chest of rares on {0}*",
    "veryapeGM" : "*drops a chest of rares on {0}*",
    "Ginaria" : "*drops a bluepar on {0}*",
    "Rift Avis" : "*drops an acorn on {0}*",
}

die_answers = [
    "Avada Kedavra!",
    "Make me!",
    "Never!!",
    "You die, {0}!",
    "You die, {0}!",
    "You die, {0}!",
    "You die, {0}!",
    "No!",
    "In a minute..",
    "Suuure... I'll get right on it",
]

healme_answers = [
    "Eat an apple, they're good for you.",
    "If I do it for you, then I have to do it for everybody.",
    "Oh, go drink a potion or something.",
    "Whoops! I lost my spellbook.",
    "No mana!",
]

whoami_answers = [
    "An undercover GM.",
    "An exiled GM.",
    "I'm not telling you!",
    "I'm a bot! I'll be level 135 one day! Mwahahahaaha!!!111!",
    "Somebody said I'm a Chinese copy of Confused Tree",
    "I am your evil twin.",
    "I don't remember anything after I woke up! What happened to me?",
    "I don't know. Why am I here??",
    "Who are you?",
    "On the 8th day, God was bored and said 'There will be bots'. \
So here I am.",
    " I'm your hell, I'm your dream, I'm nothing in between ",
    " Aperture Science. We do what we must, because.. we can ",
    "I'm just a reincarnation of a copy.",
]

burn_answers = [
    "*curses {0} and dies %%c*",
    "Help! I'm on fire!",
    "Oh hot.. hot hot!",
    "*is glowing*",
    "*is flaming*",
    "ehemm. where are firefighters? I need them now!",
    "*is so hot!*",
]

noidea_answers = [
    "What?", "What??", "Whatever...", "Hmm...", "Huh?", "*yawns*",
    "Wait a minute...", "What are you talking about?",
    "Who are you?", "What about me?",
    "I don't know what you are talking about",
    "Excuse me?", "Very interesting", "Really?",
    "Go on...",  "*Scratches its leafy head*",
    "*feels a disturbance in the force*",
    "*senses a disturbance in the force*",
    "*humming*", "I'm bored..", "%%j", "%%U", "%%[",
]

pain_answers = [ "Ouch..", "Ouchy..", "Argh..", "Eckk...", "*howls*",
                 "*screams*", "*groans*", "*cries*", "*faints*", "%%k",
                 "Why.. What did I do to you? %%i" ]

hurt_actions = [ "eat", "shoot", "pluck", "torture", "slap", "poison",
                 "break", "stab", "throw", "drown" ]

like_answers = [
    "Yay it's",
    "You are the sunshine in this beautiful land",
    "Can't do this because I like you",
]

dislike_answers = [
    "Oh, no! It's you!",
    "Go away!!!",
    "I don't want to see!",
    "Your face makes onions cry.",
    "You look like I need another drink...",
    "Mayas were right...",
]

bye_answers = [
    "See you soon!",
    "Come back anytime!!!",
    "See ya!",
    "Hope to see you again!",
    "More beer for me."
]


dislikebye_answers = [
    "Finally!",
    "Go away!!!",
    "Don't come back!",
    "Whew...",
    "I need another drink...",
    "*picking my nose*"
]

attack_answers = [
    "Attack!!!",
    "Whoa, dammit!",
    "Alright!!!",
    "I have some pain to deliver.",
    "Fire at will!!!",
    "...I'm all out of gum.",
    "His name is: JOHN CENA!!!",
    "Target acquired!",
    "Puah!",
    "Grr!!!",
    "Eat this!",
    "Ha!",
    "Come on!",
    "Party time!!!",
    "I will burn you down.",
    "The show begins...",
    "I'm better than makeup artists, prepare yourself!!!",
    "Yeah! A challenge!",
]

notattack_answers = [
    "Nope!",
    "*picking his nose*",
    "Do it yourself.",
    "Meh.",
    "I will attack you instead.",
    "What about my reward?",
]

story_introductions = [
    "I was with",
    "Yesterday I got bored and called",
    "With none else around I've asked",
]

story_action_fail = [
    "failed at it",
    "stomped on the soul menhir",
    "slipped on a terranite ore",
    "got interrupted by phone call",
    "got disconnected",
]

# FIXME Unused
story_actions = [
    "jumping on",
    "speaking with",
    "attacking",
    "poking",
    "playing cards",
]

# -----------------------------------------------------------------------------
def say_greeting(nick, _, is_whisper, match):
    if nick == "Liviobot" :
        return
    if is_whisper:
        return

    if nick in ignored_players:
        return

    if nick in disliked_players:
        mapserv.cmsg_chat_message(random.choice(dislike_answers))
    else:
        answer = random.choice(greetings)
        mapserv.cmsg_chat_message(answer.format(nick))
    time.sleep(1)

def say_goodbye(nick, _, is_whisper, match):
    if is_whisper:
        return

    if nick in ignored_players:
        return

    total_weight = 0
    for w in bye_answers.itervalues():
        total_weight += w

    random_weight = random.randint(0, total_weight)
    total_weight = 0
    random_greeting = 'Hi {0}'
    for g, w in bye_answers.iteritems():
        if total_weight >= random_weight:
            random_greeting = g
            break
        total_weight += w
    if nick in disliked_players:
        mapserv.cmsg_chat_message(random.choice(dislikebye_answers))
    else:
        mapserv.cmsg_chat_message(random.choice(bye_answers))
    time.sleep(1)


def drop_on_head(nick, _, is_whisper, match):
    if is_whisper:
        return

    if nick in ignored_players:
        return

    answer = 'yeah'
    if nick in dropping_special:
        answer = dropping_special[nick]
    else:
        r = random.randint(0, len(drop_items) + len(dropping_other))
        if r < len(drop_items):
            answer = "*drops {} on {}'s head*".format(drop_items[r], nick)
        else:
            answer = random.choice(dropping_other)

    mapserv.cmsg_chat_message(answer.format(nick))


def answer_threat(nick, _, is_whisper, match):
    if is_whisper:
        return

    if nick in ignored_players:
        return

    answer = random.choice(die_answers)
    mapserv.cmsg_chat_message(answer.format(nick))


# -----------------------------------------------------------------------------
def admin_additem(nick, _, is_whisper, match):
    if not is_whisper:
        return

    if nick not in tree_admins:
        return

    item = match.group(1)
    if item not in drop_items:
        drop_items.append(item)

    send_whisper(nick, "Added item '{}' to drop list".format(item))


def admin_addjoke(nick, _, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in tree_admins:
        return

    joke = match.group(1)
    if joke not in joke_answers:
        joke_answers.append(joke)

    send_whisper(nick, "Added joke")


# -----------------------------------------------------------------------------

PLUGIN = {
    'name': 'manaboy',
    'requires': ('chatbot', 'npc', 'autofollow'),
    'blocks': (),
}

npcdialog = {
    'start_time': -1,
    'program': [],
}

_times = {
    'follow': 0,
    'where' : 0,
    'status' : 0,
    'inventory' : 0,
    'say' : 0,
    'zeny' : 0,
    'storage' : 0,
}

allowed_drops = [535, 719, 513, 727, 729, 869]
allowed_sells = [531, 521, 522, 700, 1201]

npc_owner = ''
history = deque(maxlen=10)
storage_is_open = False
bugs = deque(maxlen=100)


def set_npc_owner(nick):
    global npc_owner
    # if plugins.npc.npc_id < 0:
    npc_owner = nick


@extends('smsg_being_remove')
def bot_dies(data):
    if data.id == charserv.server.account:
        mapserv.cmsg_player_respawn()


@extends('smsg_player_chat')
def player_chat(data):
    if not npc_owner:
        return

    whisper(npc_owner, data.message)


@extends('smsg_npc_message')
@extends('smsg_npc_choice')
@extends('smsg_npc_close')
@extends('smsg_npc_next')
@extends('smsg_npc_int_input')
@extends('smsg_npc_str_input')
def npc_activity(data):
    npcdialog['start_time'] = time.time()


@extends('smsg_npc_message')
def npc_message(data):
    if not npc_owner:
        return

    npc = mapserv.beings_cache.findName(data.id)
    m = '[npc] {} : {}'.format(npc, data.message)
    whisper(npc_owner, m)


@extends('smsg_npc_choice')
def npc_choice(data):
    if not npc_owner:
        return

    choices = filter(lambda s: len(s.strip()) > 0,
        data.select.split(':'))

    whisper(npc_owner, '[npc][select] (use !input <number> to select)')
    for i, s in enumerate(choices):
        whisper(npc_owner, '    {}) {}'.format(i + 1, s))


@extends('smsg_npc_int_input')
@extends('smsg_npc_str_input')
def npc_input(data):
    if not npc_owner:
        return

    t = 'number'
    if plugins.npc.input_type == 'str':
        t = 'string'

    whisper(npc_owner, '[npc][input] (use !input <{}>)'.format(t))


@extends('smsg_storage_status')
def storage_status(data):
    global storage_is_open
    storage_is_open = True
    _times['storage'] = time.time()
    if npc_owner:
        whisper(npc_owner, '[storage][{}/{}]'.format(
            data.used, data.max_size))


@extends('smsg_storage_items')
def storage_items(data):
    if not npc_owner:
        return

    items_s = []
    for item in data.storage:
        s = itemdb.item_name(item.id, True)
        if item.amount > 1:
            s = str(item.amount) + ' ' + s
        items_s.append(s)

    for l in status.split_names(items_s):
        whisper(npc_owner, l)


@extends('smsg_storage_equip')
def storage_equipment(data):
    if not npc_owner:
        return

    items_s = []
    for item in data.equipment:
        s = itemdb.item_name(item.id, True)
        items_s.append(s)

    for l in status.split_names(items_s):
        whisper(npc_owner, l)


@extends('smsg_storage_close')
def storage_close(data):
    global storage_is_open
    storage_is_open = False
    _times['storage'] = 0


@extends('smsg_player_arrow_message')
def arrow_message(data):
    if npc_owner:
        if data.code == 0:
            whisper(npc_owner, "Equip arrows")


def cmd_where(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    msg = status.player_position()
    whisper(nick, msg)


def cmd_goto(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    try:
        x = int(match.group(1))
        y = int(match.group(2))
    except ValueError:
        return

    set_npc_owner(nick)
    plugins.autofollow.follow = ''
    mapserv.cmsg_player_change_dest(x, y)


def cmd_goclose(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
        
    x = mapserv.player_pos['x']
    y = mapserv.player_pos['y']

    if message.startswith('!left'):
        x -= 1
    elif message.startswith('!right'):
        x += 1
    elif message.startswith('!up'):
        y -= 1
    elif message.startswith('!down'):
        y += 1

    set_npc_owner(nick)
    plugins.autofollow.follow = ''
    mapserv.cmsg_player_change_dest(x, y)


def cmd_pickup(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    commands.pickup()


def cmd_drop(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
        
    try:
        amount = int(match.group(1))
        item_id = int(match.group(2))
    except ValueError:
        return

    if nick not in admins:
        if item_id not in allowed_drops:
            return

    index = get_item_index(item_id)
    if index > 0:
        mapserv.cmsg_player_inventory_drop(index, amount)


def cmd_item_action(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    try:
        itemId = int(match.group(1))
    except ValueError:
        return

    index = get_item_index(itemId)
    if index <= 0:
        return

    if message.startswith('!equip'):
        mapserv.cmsg_player_equip(index)
    elif message.startswith('!unequip'):
        mapserv.cmsg_player_unequip(index)
    elif message.startswith('!use'):
        mapserv.cmsg_player_inventory_use(index, itemId)


def cmd_emote(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    try:
        emote = int(match.group(1))
    except ValueError:
        return

    mapserv.cmsg_player_emote(emote)


def cmd_attack(nick, message, is_whisper, match):
#    if not is_whisper:
#        return
    if nick in ignored_players:
        return
    if nick not in admins:
        mapserv.cmsg_chat_message(random.choice(notattack_answers))
        return

    target_s = match.group(1)

    try:
        target = mapserv.beings_cache[int(target_s)]
    except (ValueError, KeyError):
        target = find_nearest_being(name=target_s,
                                    ignored_ids=walkto.unreachable_ids)

    if target in ignored_players:
        return

    if target is not None:
        set_npc_owner(nick)
        plugins.autofollow.follow = ''
        if target_s=="Bee": 
            mapserv.cmsg_chat_message("Forget it " + nick + "!!!")
        elif target_s=="Pink Flower":
                mapserv.cmsg_chat_message("Yeah, I love those.")
        elif target_s=="Squirrel":
            mapserv.cmsg_chat_message("Die, you rodent!!!")
            mapserv.cmsg_player_emote(5)
            walkto.walkto_and_action(target, 'attack', mapserv.player_attack_range)
            time.sleep(5)
            mapserv.cmsg_chat_message("Go to squirrel's heaven.")
        elif target_s in friends:
            mapserv.cmsg_chat_message(random.choice(like_answers)+ " " + target_s + "!")
            time.sleep(5)
            mapserv.cmsg_player_emote(32)
        else:
            mapserv.cmsg_chat_message(random.choice(attack_answers))
            time.sleep(1)
            walkto.walkto_and_action(target, 'attack', mapserv.player_attack_range)
            time.sleep(5)
            mapserv.cmsg_chat_message(random.choice(attack_answers))
    else:
        mapserv.cmsg_chat_message(random.choice(noidea_answers))

def cmd_come(nick, message, is_whisper, match):
    if nick in ignored_players:
        return
    if nick not in admins:
        mapserv.cmsg_chat_message(random.choice(notattack_answers))
        return

    target_s = match.group(1)

    try:
        target = mapserv.beings_cache[int(nick)]
    except (ValueError, KeyError):
        target = find_nearest_being(name=nick,
                                    ignored_ids=walkto.unreachable_ids)

    if target is not None:
        set_npc_owner(nick)
        plugins.autofollow.follow = ''
        walkto.walkto_and_action(target, '', mapserv.player_attack_range)
        mapserv.cmsg_chat_message(random.choice(attack_answers))
    else:
        mapserv.cmsg_chat_message(random.choice(noidea_answers))

def say_explain(nick, msg, is_whisper, match):
    if is_whisper:
        return

    if nick in ignored_players:
        return

    if msg.split(' ',1)[1].lower() in explain_sentences:
        mapserv.cmsg_chat_message(explain_sentences[msg.split(' ',1)[1].lower()])
        mapserv.cmsg_player_emote(3)
    else:
        mapserv.cmsg_chat_message(random.choice(noidea_answers))
#        mapserv.cmsg_chat_message(msg.split(' ',1)[1].lower())

def say_think(nick, msg, is_whisper, match):
    if is_whisper:
        return

    if nick in ignored_players:
        return
    random_weight = random.randint(0, 2)
    if random_weight == 0:
        mapserv.cmsg_chat_message(random.choice(noidea_answers))
    if random_weight == 1:
        mapserv.cmsg_chat_message("Maybe " + nick + " " + random.choice(hurt_actions) + " " + msg.split(' ')[-1][:-1]+"?")
    if random_weight == 2:
        mapserv.cmsg_chat_message(nick + " I have to check the wiki.")
#    mapserv.cmsg_chat_message(msg.split(' ')[-1][:-1])

def make_story(self):
    return "asd"

def say_story(nick, msg, is_whisper, match):
    if nick in ignored_players:
        return
    # ~ random_weight = random.randint(0, 2)
    # ~ if random_weight == 0:
        # ~ mapserv.cmsg_chat_message(random.choice(noidea_answers))
    # ~ if random_weight == 1:
        # ~ mapserv.cmsg_chat_message("Maybe " + nick + " " + random.choice(hurt_actions) + " " + msg.split(' ')[-1][:-1]+"?")
    # ~ if random_weight == 2:
        # ~ mapserv.cmsg_chat_message(nick + " I have to check the wiki.")
    players = []
    for being in mapserv.beings_cache.itervalues():
        if ((being.type == 'player' or being.type == 'npc') and len(being.name) > 1):
            players.append(being.name)
    monsters = ["monster"]
    for being in mapserv.beings_cache.itervalues():
        if being.type == 'monster' and len(being.name) > 1:
            monsters.append(being.name)
    mapserv.cmsg_chat_message(random.choice(story_introductions) + " " + random.choice(players) + " to " + random.choice(hurt_actions) + " a " + random.choice(monsters) + " with " + random.choice(drop_items) + " but " + random.choice(story_action_fail) +" and said: \"" + random.choice(pain_answers) + "\". Then the " + random.choice(monsters) + " said:  \"" + random.choice(noidea_answers) + "\". But " + random.choice(players) +" replied: \"" + random.choice(attack_answers) + "\"")
    #mapserv.cmsg_chat_message()

# Doesn't work.
def cmd_say(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    # ~ set_npc_owner(nick)
    msg = message.group(1)
    mapserv.cmsg_chat_message(msg)


def cmd_sit(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    plugins.autofollow.follow = ''
    mapserv.cmsg_player_change_act(0, 2)


def cmd_turn(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    commands.set_direction('', message[6:])


def cmd_follow(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    if plugins.autofollow.follow == nick:
        plugins.autofollow.follow = ''
    else:
        set_npc_owner(nick)
        plugins.autofollow.follow = nick


def cmd_lvlup(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    stat = match.group(1).lower()
    stats = {'str': 13, 'agi': 14, 'vit': 15,
             'int': 16, 'dex': 17, 'luk': 18}

    skills = {'mallard': 45, 'brawling': 350, 'speed': 352,
              'astral': 354, 'raging': 355, 'resist': 353}

    if stat in stats:
        mapserv.cmsg_stat_update_request(stats[stat], 1)
    elif stat in skills:
        mapserv.cmsg_skill_levelup_request(skills[stat])

#FIXME it fails: leads bot to spam
def cmd_invlist(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    ls = status.invlists(50)
    for l in ls:
        whisper(nick, l)
        time.delay(2)

#FIXME it fails
def cmd_inventory(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    ls = status.invlists2(255)
    for l in ls:
        whisper(nick, l)
    time.delay(2)


def cmd_status(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    all_stats = ('stats', 'hpmp', 'weight', 'points',
                 'zeny', 'attack', 'skills')

    sr = status.stats_repr(*all_stats)
    whisper(nick, ' | '.join(sr.values()))


def cmd_zeny(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    whisper(nick, 'I have {} GP'.format(mapserv.player_stats[stats.MONEY]))


def cmd_nearby(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    btype = message[8:]
    if btype.endswith('s'):
        btype = btype[:-1]

    ls = status.nearby(btype)
    for l in ls:
        whisper(nick, l)


def cmd_talk2npc(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    npc_s = match.group(1).strip()
    jobs = []
    name = ''
    try:
        jobs = [int(npc_s)]
    except ValueError:
        name = npc_s

    b = find_nearest_being(name=name, type='npc', allowed_jobs=jobs)
    if b is None:
        whisper(nick, '[error] NPC not found: {}'.format(npc_s))
        return

    set_npc_owner(nick)
    plugins.autofollow.follow = ''
    plugins.npc.npc_id = b.id
    mapserv.cmsg_npc_talk(b.id)


def cmd_input(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    plugins.npc.cmd_npcinput('', match.group(1))


def cmd_close(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    if storage_is_open:
        reset_storage()
    else:
        plugins.npc.cmd_npcclose()


def cmd_history(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    for user, cmd in history:
        whisper(nick, '{} : {}'.format(user, cmd))


def cmd_store(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    if not storage_is_open:
        return

    try:
        amount = int(match.group(1))
        item_id = int(match.group(2))
    except ValueError:
        return

    index = get_item_index(item_id)
    if index > 0:
        mapserv.cmsg_move_to_storage(index, amount)


def cmd_retrieve(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    if nick not in admins:
        return
    if not storage_is_open:
        return

    try:
        amount = int(match.group(1))
        item_id = int(match.group(2))
    except ValueError:
        return

    index = get_storage_index(item_id)
    if index > 0:
        mapserv.cmsg_move_from_storage(index, amount)


def cmd_sell(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return
    try:
        amount = int(match.group(1))
        item_id = int(match.group(2))
        npc_s = match.group(3).strip()
    except ValueError:
        return

    if item_id not in allowed_sells:
        return

    index = get_item_index(item_id)
    if index < 0:
        return

    jobs = []
    name = ''
    try:
        jobs = [int(npc_s)]
    except ValueError:
        name = npc_s

    b = find_nearest_being(name=name, type='npc', allowed_jobs=jobs)
    if b is None:
        return

    mapserv.cmsg_npc_buy_sell_request(b.id, 1)
    mapserv.cmsg_npc_sell_request(index, amount)


def cmd_help(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return

    m = ('[@@https://forums.themanaworld.org/viewtopic.php?f=12&t=19673|Forum@@]'
         '[@@https://bitbucket.org/rumly111/manachat|Sources@@] '
         'Try !commands for list of commands')
    whisper(nick, m)


def cmd_commands(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return

    c = []
    for cmd in manaboy_commands:
        if cmd.startswith('!('):
            br = cmd.index(')')
            c.extend(cmd[2:br].split('|'))
        elif cmd.startswith('!'):
            c.append(cmd[1:].split()[0])

    c.sort()
    whisper(nick, ', '.join(c))


def cmd_report_bug(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return

    bug_s = match.group(1)
    bugs.append((nick, bug_s))
    whisper(nick, 'Thank you for your bug report')


def cmd_check_bugs(nick, message, is_whisper, match):
    if not is_whisper:
        return
    if nick in ignored_players:
        return

    if nick not in admins:
        return

    for user, bug in bugs:
        whisper(nick, '{} : {}'.format(user, bug))

    bugs.clear()


def reset_storage():
    mapserv.cmsg_storage_close()
    mapserv.cmsg_npc_list_choice(plugins.npc.npc_id, 6)


# =========================================================================
def manaboy_logic(ts):

    def reset():
        global npc_owner
        npc_owner = ''
        npcdialog['start_time'] = -1
        plugins.npc.cmd_npcinput('', '6')
        # plugins.npc.cmd_npcclose()

    if storage_is_open and ts > _times['storage'] + 150:
        reset_storage()

    if npcdialog['start_time'] <= 0:
        return

    if not storage_is_open and ts > npcdialog['start_time'] + 30.0:
        reset()
    
# =========================================================================
manaboy_commands = {
    '!where' : cmd_where,
    '!goto (\d+) (\d+)' : cmd_goto,
    '!(left|right|up|down)' : cmd_goclose,
    '!pickup' : cmd_pickup,
    '!drop (\d+) (\d+)' : cmd_drop,
    '!equip (\d+)' : cmd_item_action,
    '!unequip (\d+)' : cmd_item_action,
    '!use (\d+)' : cmd_item_action,
    '!emote (\d+)' : cmd_emote,
    '!attack (.+)' : cmd_attack,
    '!say ((@|#).+)' : cmd_say,
    '!sit' : cmd_sit,
    '!turn' : cmd_turn,
    '!follow' : cmd_follow,
    '!lvlup (\w+)' : cmd_lvlup,
    '!inventory' : cmd_inventory,
    '!invlist' : cmd_invlist,
    '!status' : cmd_status,
    '!zeny' : cmd_zeny,
    '!nearby' : cmd_nearby,
    '!talk2npc (.+)' : cmd_talk2npc,
    '!input (.+)' : cmd_input,
    '!close' : cmd_close,
    '!store (\d+) (\d+)' : cmd_store,
    '!retrieve (\d+) (\d+)' : cmd_retrieve,
    '!sell (\d+) (\d+) (.+)' : cmd_sell,
    '!(help|info)' : cmd_help,
    '!commands' : cmd_commands,
    '!history' : cmd_history,
    '!bug (.+)' : cmd_report_bug,
    '!bugs' : cmd_check_bugs,

    '!xcal (.*)' : XCAL,
    '!xuf': XUfortune,
    '!xudate': XUdate,
    '!xupom': XUpom,
    '!xcon' : XCOMEnable,
    '!xcom' : XCOMEnable,
    '!xcoff' : XCOMDisable,
    '!xcom off' : XCOMDisable,
    '!xclist' : XCOMOnlineList,
    '!xci (.*)' : XCOMInvite,
    '!xcia' : XCOMInviteAll,
    '!xcsi (.*)' : XCOMSilentInvite,
    '!xcb (.*)' : XCOMBan,
    '!xcu (.*)' : XCOMUnBan,
    '!xcsion' : XCOMServerInterestEnable,
    '!xcsioff' : XCOMServerInterestDisable,
    r'(.*)' : XCOMCommunicate,

    r'^(?i)explain (.*)': say_explain,
    r'^(?i)(hello|hi|hey|heya|hiya|yo) (?i)(livio|liviobot)' : say_greeting,
    r'^(?i)(hello|hi|hey|heya|hiya) (?i)(all|everybody|everyone)(.*)' : say_greeting,
    r'\*(?i)?((shake|kick)s?) (?i)(livio|liviobot)' : drop_on_head,
    r'\*(?i)?(bye|cya|gtg)' : say_goodbye,
    r'(?i)(die|go away|\*?((nuke|kill)s?)) (?i)(livio|liviobot)' : answer_threat,
    r'^(?i)(livio|liviobot) (?i)Will (.*)' : noidea_answers,
    r'^(?i)heal me([ ,]{1,2})(livio|liviobot)' : healme_answers,
    r'^(?i)(who|what) are you([ ,]{1,3})(livio|liviobot)' : whoami_answers,
    r'^!additem (.*)' : admin_additem,
    r'^!addjoke (.*)' : admin_addjoke,
    r'\*(?i)?(burn(s?)) (livio|liviobot)' : burn_answers,
    r'\*(?i)?(come) (livio|liviobot)' : cmd_come,
    r'\*(?i)?(' + '|'.join(hurt_actions) + ')s?(?i)(livio|liviobot)' : pain_answers,
    r'^(?i)what do you think about(.*)' : say_think,
    '!story': say_story,
    '!joke' : joke_answers,
}


def chatbot_answer_mod(func):
    '''modifies chatbot.answer to remember last 10 commands'''

    def mb_answer(nick, message, is_whisper):
        if is_whisper:
            history.append((nick, message))
        return func(nick, message, is_whisper)

    return mb_answer

def init(config):

    online_users.start()
    
    for cmd, action in manaboy_commands.items():
        plugins.chatbot.add_command(cmd, action)
    plugins.chatbot.answer = chatbot_answer_mod(plugins.chatbot.answer)

    logicmanager.logic_manager.add_logic(manaboy_logic)