root/trunk/twcore/src/twcore/bots/messagebot/messagebot.java

Revision 3989, 73.3 KB (checked in by Dexter, 10 days ago)

Allowing ER+ to leave message to a channel without being on it ( to be used in TWD-Op channel ) so the ERs can leave a message on it without the access to read.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1package twcore.bots.messagebot;
2
3import java.io.BufferedReader;
4import java.io.InputStreamReader;
5import java.net.URL;
6import java.net.URLConnection;
7import java.sql.ResultSet;
8import java.sql.SQLException;
9import java.util.HashMap;
10import java.util.HashSet;
11import java.util.Iterator;
12import java.util.LinkedList;
13import java.util.Set;
14import java.util.TimerTask;
15import java.util.Date;
16import java.text.SimpleDateFormat;
17
18import twcore.core.BotAction;
19import twcore.core.EventRequester;
20import twcore.core.SubspaceBot;
21import twcore.core.command.CommandInterpreter;
22import twcore.core.events.InterProcessEvent;
23import twcore.core.events.LoggedOn;
24import twcore.core.events.Message;
25
26import twcore.core.util.Tools;
27import twcore.core.util.ipc.IPCMessage;
28
29/** Bot to host "channels" that allow a player to ?message or pm
30 *  everyone on the channel so that information can be spread easily.
31 *
32 *  @author Ikrit
33 *  @version 1.8
34 *
35 *  Added database support of messages because I forgot SSC messaging only
36 *  allows one message from a person at a time.
37 *
38 *  Added pubbot support so the bot can PM a player that has just logged
39 *  in to tell them if they have messages.
40 *
41 *  Fixed possible SQL injection attacks (cough FINALLY cough).
42 *
43 *  Added support so the bot will sync with the website.
44 *
45 *  Added a news feature for the lobby thing that qan is designing. Highmod+ can add news messages that get arena'd every 90 sec's.
46 *
47 *  Added all new commands to !help thus making !help a 41 PM long help message.
48 *
49 *  Added debugging stuff...
50 *
51 *  Added an alerts chat type thing for in lobby.
52 *
53 *  Fixed help so it doesn't spam 41 lines.
54 *
55 *  Deleted AIM stuff because I dislike it
56 *
57 *  Added ability to leave messages to people instead of channels
58 *
59 *      Editted !help
60 *
61 *      Added ability to message yourself
62 *
63 *      Fixed !help order
64 *
65 *
66 * TODO:
67 *
68 *      Multi-line messages
69 *
70 */
71public class messagebot extends SubspaceBot
72{
73        HashMap <String,Channel>channels;
74        //HashMap defaultChannel;
75        HashSet <String>ops;
76        CommandInterpreter m_CI;
77        TimerTask messageDeleteTask, messageBotSync;
78        public static final String IPCCHANNEL = "messages";
79        boolean bug = false;
80        public String database = "website";//If you change this you must also change line ~1426
81
82        private LinkedList<String> playersOnline = new LinkedList();
83        /** Constructor, requests Message and Login events.
84         *  Also prepares bot for use.
85         */
86        public messagebot(BotAction botAction)
87        {
88                super(botAction);
89                EventRequester events = m_botAction.getEventRequester();
90                events.request(EventRequester.MESSAGE);
91                events.request(EventRequester.LOGGED_ON);
92                channels = new HashMap<String,Channel>();
93                //defaultChannel = new HashMap();
94                ops = new HashSet<String>();
95                m_CI = new CommandInterpreter(m_botAction);
96                registerCommands();
97                createTasks();
98                m_botAction.scheduleTaskAtFixedRate(messageDeleteTask, 30 * 60 * 1000, 30 * 60 * 1000);
99                m_botAction.scheduleTaskAtFixedRate(messageBotSync, 2 * 60 * 1000, 2 * 60 * 1000);
100        }
101
102        /** This method handles an InterProcessEvent
103         *  @param event is the InterProcessEvent to handle.
104         */
105        public void handleEvent(InterProcessEvent event)
106        {
107                IPCMessage ipcMessage = (IPCMessage) event.getObject();
108                String message = ipcMessage.getMessage();
109                checkNewMessages(message.toLowerCase());
110        }
111
112        /** Checks to see if the player has new messages.
113         *  @param Name of player to check.
114         */
115        public void checkNewMessages(String name)
116        {
117                String query = "SELECT * FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name)+"' and fnRead = 0";
118                try {
119                        ResultSet results = m_botAction.SQLQuery(database, query);
120            int unreadMsgs = 0;
121                        while(results.next()) {
122                unreadMsgs++;
123                        }
124            m_botAction.SQLClose(results);
125            if(unreadMsgs > 0) 
126            {
127                //checkPlayerOnline(name);
128                //if( playersOnline.contains(name) ){
129                    m_botAction.sendSmartPrivateMessage(name, "You have "
130                            + unreadMsgs + " new message" + (unreadMsgs==1?"":"s") +
131                        ".  PM me with !read to read " + (unreadMsgs==1?"it":"them") +
132                        ", or !messages for a list.");
133                    playersOnline.remove(name);
134                //}
135                   
136                /*else{
137                        sendSSMessage(name);
138                    }*/
139            }
140                } catch(Exception e) { Tools.printStackTrace(e); }
141        }
142       
143        public void checkPlayerOnline(String name)
144        {
145            m_botAction.locatePlayer(name);
146           
147        }
148        /** Sets up the CommandInterpreter to respond to
149         *  all of the commands.
150         *
151         */
152        public void registerCommands() {
153        int acceptedMessages;
154
155        acceptedMessages = Message.PRIVATE_MESSAGE | Message.REMOTE_PRIVATE_MESSAGE;
156        m_CI.registerCommand( "!create",     acceptedMessages, this, "createChannel" );
157        m_CI.registerCommand( "!destroy",    acceptedMessages, this, "destroyChannel" );
158        m_CI.registerCommand( "!join",       acceptedMessages, this, "joinChannel" );
159        m_CI.registerCommand( "!quit",       acceptedMessages, this, "quitChannel" );
160        m_CI.registerCommand( "!help",       acceptedMessages, this, "doHelp" );
161        m_CI.registerCommand( "!accept",     acceptedMessages, this, "acceptPlayer" );
162        m_CI.registerCommand( "!decline",    acceptedMessages, this, "declinePlayer" );
163        m_CI.registerCommand( "!announce",   acceptedMessages, this, "announceToChannel" );
164        m_CI.registerCommand( "!message",    acceptedMessages, this, "messageChannel" );
165        m_CI.registerCommand( "!requests",   acceptedMessages, this, "listRequests");
166        m_CI.registerCommand( "!ban",        acceptedMessages, this, "banPlayer");
167        m_CI.registerCommand( "!unban",          acceptedMessages, this, "unbanPlayer");
168        m_CI.registerCommand( "!makeop",         acceptedMessages, this, "makeOp");
169        m_CI.registerCommand( "!deop",       acceptedMessages, this, "deOp");
170        m_CI.registerCommand( "!owner",          acceptedMessages, this, "sayOwner");
171        m_CI.registerCommand( "!grant",          acceptedMessages, this, "grantChannel");
172        m_CI.registerCommand( "!private",        acceptedMessages, this, "makePrivate");
173        m_CI.registerCommand( "!public",         acceptedMessages, this, "makePublic");
174        m_CI.registerCommand( "!unread",         acceptedMessages, this, "setAsNew");
175        m_CI.registerCommand( "!read",           acceptedMessages, this, "readMessage");
176        m_CI.registerCommand( "!readnew",    acceptedMessages, this, "readNewMessages");
177        m_CI.registerCommand( "!delete",         acceptedMessages, this, "deleteMessage");
178        m_CI.registerCommand( "!messages",       acceptedMessages, this, "myMessages");
179        m_CI.registerCommand( "!msgs",       acceptedMessages, this, "myMessages");
180        m_CI.registerCommand( "!go",             acceptedMessages, this, "handleGo");
181        m_CI.registerCommand( "!members",        acceptedMessages, this, "listMembers");
182        m_CI.registerCommand( "!banned",         acceptedMessages, this, "listBanned");
183        m_CI.registerCommand( "!me",             acceptedMessages, this, "myChannels");
184        m_CI.registerCommand( "!die",            acceptedMessages, this, "handleDie");
185        m_CI.registerCommand( "!check",          acceptedMessages, this, "playerLogin");
186        m_CI.registerCommand( "!ignore",         acceptedMessages, this, "ignorePlayer");
187        m_CI.registerCommand( "!unignore",       acceptedMessages, this, "unignorePlayer");
188        m_CI.registerCommand( "!ignored",        acceptedMessages, this, "whoIsIgnored");
189        m_CI.registerCommand( "!lmessage",       acceptedMessages, this, "leaveMessage");
190        m_CI.registerCommand( "!regall",         acceptedMessages, this, "registerAll");
191
192        m_CI.registerDefaultCommand( Message.REMOTE_PRIVATE_MESSAGE, this, "doNothing");
193
194    }
195
196    /** Creates a channel
197     *  @param Name of the player creating the channel.
198     *  @param Name of the channel they are trying to create.
199     */
200    public void createChannel(String name, String message)
201    {
202        if(channels.containsKey(message.toLowerCase()))
203        {
204                m_botAction.sendSmartPrivateMessage(name, "Sorry, this channel is already owned.");
205                return;
206        }
207        if(!m_botAction.getOperatorList().isBot(name))
208        {
209                m_botAction.sendSmartPrivateMessage(name, "Sorry, you need to be a ZH+ to create a channel.");
210                return;
211        }
212
213        Channel c = new Channel(name.toLowerCase(), message.toLowerCase(), m_botAction, true, false);
214        channels.put(message.toLowerCase(), c);
215
216        String query = "INSERT INTO tblChannel (fcChannelName, fcOwner, fnPrivate) VALUES('"+Tools.addSlashesToString(message.toLowerCase())+"', '"+Tools.addSlashesToString(name.toLowerCase())+"', 0)";
217        try {
218                m_botAction.SQLClose(m_botAction.SQLQuery(database, query));
219        } catch(SQLException sqle) { Tools.printStackTrace( sqle ); }
220    }
221
222    /** Allows a channel owner or Highmod to delete a channel.
223     *  @param Name of player.
224     *  @param Name of channel being deleted.
225     */
226    public void destroyChannel(String name, String message)
227    {
228        String channel = getChannel(name, message, true).toLowerCase();
229        if(!channels.containsKey(channel))
230        {
231                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
232                return;
233        }
234
235        Channel c = channels.get(channel);
236        if(c.isOwner(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
237        {
238                String query = "DELETE FROM tblChannel WHERE fcChannelName = '" + Tools.addSlashesToString(channel) + "'";
239                String query2 = "DELETE FROM tblChannelUser WHERE fcChannel = '" + Tools.addSlashesToString(channel) + "'";
240                try {
241                        m_botAction.SQLClose(m_botAction.SQLQuery(database, query));
242                        m_botAction.SQLClose(m_botAction.SQLQuery(database, query2));
243                } catch(SQLException sqle) { Tools.printStackTrace( sqle ); }
244                m_botAction.sendSmartPrivateMessage(name, "Channel deleted.");
245                c.messageChannel(name, "Channel " + channel + " deleted.");
246                channels.remove(channel);
247        }
248        else
249                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
250    }
251
252    /** Puts in a request to join a channel.
253     *  @param Name of player.
254     *  @param Name of channel they want to join.
255     */
256    public void joinChannel(String name, String message)
257    {
258        String channel = getChannel(name, message, true).toLowerCase();
259        if(!channels.containsKey(channel))
260        {
261                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
262                return;
263        }
264
265        Channel c = channels.get(channel);
266        c.joinRequest(name);
267    }
268
269    /** Allows a person to quit a channel.
270     *  @param Name of player.
271     *  @param Name of channel being quit.
272     */
273    public void quitChannel(String name, String message)
274    {
275        String channel = getChannel(name, message, true).toLowerCase();
276        if(!channels.containsKey(channel))
277        {
278                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
279                return;
280        }
281
282        Channel c = channels.get(channel);
283        if(c.isOwner(name))
284        {
285                m_botAction.sendSmartPrivateMessage(name, "You cannot leave while you are owner.");
286                return;
287        }
288        c.leaveChannel(name);
289    }
290
291    /** Accepts a player into the channel.
292     *  @param Name of operator.
293     *  @param Name of channel and player beinc accepted.
294     */
295    public void acceptPlayer(String name, String message)
296    {
297        String channel = getChannel(name, message, false).toLowerCase();
298        String pieces[] = message.split(":", 2);
299        if(!channels.containsKey(channel))
300        {
301                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
302                return;
303        }
304
305        Channel c = channels.get(channel);
306        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
307                        c.acceptPlayer(name, pieces[1]);
308                else
309                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
310    }
311
312    /** Declines a player's request to join a channel.
313     *  @param Name of operator.
314     *  @param Name of channel and player being rejected.
315     */
316    public void declinePlayer(String name, String message)
317    {
318        String channel = getChannel(name, message, false).toLowerCase();
319        String pieces[] = message.split(":", 2);
320        if(!channels.containsKey(channel))
321        {
322                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
323                return;
324        }
325
326        Channel c = channels.get(channel);
327        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
328                c.rejectPlayer(name, pieces[1]);
329        else
330                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
331    }
332
333    /** Sends a pm to all players on the channel.
334     *  @param Name of operator.
335     *  @param Name of channel and message to be sent.
336     */
337    public void announceToChannel(String name, String message)
338    {
339        String channel = getChannel(name, message, false).toLowerCase();
340        String pieces[] = message.split(":", 2);
341        if(!channels.containsKey(channel))
342        {
343                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
344                return;
345        }
346
347        Channel c = channels.get(channel);
348        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
349                c.announceToChannel(name, pieces[1]);
350        else
351                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
352    }
353
354        /** Sends ?message's to every player on a channel.
355         *  @param Name of operator.
356         *  @param Name of channel and message to be sent.
357         */
358        public void messageChannel(String name, String message)
359    {
360        String channel = getChannel(name, message, false).toLowerCase();
361        String pieces[] = message.split(":", 2);
362        if(!channels.containsKey(channel))
363        {
364                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
365                return;
366        }
367
368        Channel c = channels.get(channel);
369        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()) || m_botAction.getOperatorList().isER(name)){
370            if(pieces[1].length() > 200){
371                m_botAction.sendSmartPrivateMessage( name, "That message is too long to send. Please create a message of 200 characters or less.");
372                return;
373            }
374            else {
375                int numMsgd = c.messageChannel(name, pieces[1]);
376                m_botAction.sendSmartPrivateMessage(name, "Message sent to " + numMsgd + " members of channel '" + channel + "'.");
377            }
378        }
379        else
380                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
381    }
382
383    /** Lists all requests to join a channel.
384     *  @param Name of operator
385     *  @param Name of channel.
386     */
387    public void listRequests(String name, String message)
388    {
389        String channel = getChannel(name, message, true).toLowerCase();
390        if(!channels.containsKey(channel))
391        {
392                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
393                return;
394        }
395
396        Channel c = channels.get(channel);
397        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
398                c.listRequests(name);
399        else
400                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
401    }
402
403    /** Bans a player from a channel
404     *  @param Name of operator
405     *  @param Name of channel and player being banned.
406     */
407    public void banPlayer(String name, String message)
408    {
409        String channel = getChannel(name, message, false).toLowerCase();
410        String pieces[] = message.split(":", 2);
411        if(!channels.containsKey(channel))
412        {
413                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
414                return;
415        }
416
417        Channel c = channels.get(channel);
418        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
419                c.banPlayer(name, pieces[1]);
420        else
421                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
422    }
423
424    /** Removes a player's ban.
425     *  @param Name of operator.
426     *  @param Name of channel and player being unbanned.
427     */
428    public void unbanPlayer(String name, String message)
429    {
430        String channel = getChannel(name, message, false).toLowerCase();
431        String pieces[] = message.split(":", 2);
432        if(!channels.containsKey(channel))
433        {
434                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
435                return;
436        }
437
438        Channel c = channels.get(channel);
439        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
440                c.unbanPlayer(name, pieces[1]);
441        else
442                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
443    }
444
445    /** Lists all requests to join a channel.
446     *  @param Name of operator
447     *  @param Name of channel.
448     */
449    public void listBanned(String name, String message)
450    {
451        String channel = getChannel(name, message, true).toLowerCase();
452        if(!channels.containsKey(channel))
453        {
454                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
455                return;
456        }
457
458        Channel c = channels.get(channel);
459        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
460                c.listBanned(name);
461        else
462                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
463    }
464
465    /** Lists all requests to join a channel.
466     *  @param Name of operator
467     *  @param Name of channel.
468     */
469    public void listMembers(String name, String message)
470    {
471        String channel = getChannel(name, message, true).toLowerCase();
472        if(!channels.containsKey(channel))
473        {
474                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
475                return;
476        }
477
478        Channel c = channels.get(channel);
479    //  if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
480                c.listMembers(name);
481    //  else
482    //          m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
483    }
484
485    /** Makes a player a channel operator.
486     *  @param Name of owner
487     *  @param Name of channel and player being op'd.
488     */
489    public void makeOp(String name, String message)
490    {
491        String channel = getChannel(name, message, false).toLowerCase();
492        String pieces[] = message.split(":", 2);
493        if(!channels.containsKey(channel))
494        {
495                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
496                return;
497        }
498
499        Channel c = channels.get(channel);
500        if(c.isOwner(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
501                c.makeOp(name, pieces[1]);
502        else
503                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
504    }
505
506    /** Revokes a player's operator status
507     *  @param Name of owner
508     *  @param Name of channel and player.
509     */
510    public void deOp(String name, String message)
511    {
512        String channel = getChannel(name, message, false).toLowerCase();
513        String pieces[] = message.split(":", 2);
514        if(!channels.containsKey(channel))
515        {
516                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
517                return;
518        }
519
520        Channel c = channels.get(channel);
521        if(!c.isOp(name))
522        {
523                m_botAction.sendSmartPrivateMessage(name, "That player is not an operator.");
524                return;
525        }
526
527        if(c.isOwner(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
528                c.deOp(name, pieces[1]);
529        else
530                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
531    }
532
533    /** Grants ownership of a channel to a new player.
534     *  @param Name of owner/Highmod
535     *  @param Name of channel and player beign given operator.
536     */
537    public void grantChannel(String name, String message)
538    {
539        String channel = getChannel(name, message, false).toLowerCase();
540        String pieces[] = message.split(":", 2);
541        if(!channels.containsKey(channel))
542        {
543                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
544                return;
545        }
546
547        Channel c = channels.get(pieces[0].toLowerCase());
548        if(c.isOwner(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
549                c.newOwner(name, pieces[1]);
550        else
551                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
552    }
553
554    /** Tells who the owner of the requested channel is.
555     *  @param Name of player
556     *  @param Name of channel
557     */
558    public void sayOwner(String name, String message)
559    {
560        String channel = getChannel(name, message, true).toLowerCase();
561        if(!channels.containsKey(channel))
562        {
563                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
564                return;
565        }
566
567        Channel c = channels.get(channel);
568        m_botAction.sendSmartPrivateMessage(name, "Owner: " + c.owner);
569    }
570
571    /** Makes a channel public.
572     *  @param Name of operator
573     *  @param Name of channel
574     */
575    public void makePublic(String name, String message)
576    {
577        String channel = getChannel(name, message, true).toLowerCase();
578        if(!channels.containsKey(channel))
579        {
580                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
581                return;
582        }
583
584        Channel c = channels.get(channel);
585        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
586                c.makePublic(name);
587        else
588                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
589    }
590
591    /** Makes a channel private
592     *  @param Name of operator
593     *  @param Name of channel.
594     */
595    public void makePrivate(String name, String message)
596    {
597        String channel = getChannel(name, message, true).toLowerCase();
598        if(!channels.containsKey(channel))
599        {
600                m_botAction.sendSmartPrivateMessage(name, "That channel does not exist.");
601                return;
602        }
603
604        Channel c = channels.get(channel);
605        if(c.isOp(name) || m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
606                c.makePrivate(name);
607        else
608                m_botAction.sendSmartPrivateMessage(name, "You do not have permission to do that on this channel.");
609    }
610
611    /** Tells the player all the channels he/she is on.
612     *  @param Name of player
613     *  @param does nothing
614     */
615
616    public void myChannels(String name, String message)
617    {
618        String query = "SELECT * FROM tblChannelUser WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"'";
619        try {
620                ResultSet results = m_botAction.SQLQuery(database, query);
621                while(results.next())
622                {
623                        String channel = results.getString("fcChannel");
624                        channel = channel.toLowerCase();
625                        Channel c = channels.get(channel);
626                        if( c == null)
627                            return;
628                        if(c.isOwner(name.toLowerCase()))
629                                channel += ": Owner.";
630                        else if(c.isOp(name.toLowerCase()))
631                                channel += ": Operator.";
632                        else
633                                channel += ": Member.";
634                        m_botAction.sendSmartPrivateMessage(name, channel);
635                }
636                m_botAction.SQLClose(results);
637        } catch(Exception e) { Tools.printStackTrace(e); }
638    }
639
640
641    /** Sends help messages
642     *  @param Name of player.
643     */
644    public void doHelp(String name, String message)
645    {
646        if(message.toLowerCase().startsWith("m")) {
647                m_botAction.sendSmartPrivateMessage(name, "Messaging system commands:");
648            m_botAction.sendSmartPrivateMessage(name, "    !messages   (Shortcut: !msgs) - PM's you all your message numbers.");
649            m_botAction.sendSmartPrivateMessage(name, "    !messages all                 - PM's you all your message numbers.");
650            m_botAction.sendSmartPrivateMessage(name, "    !messages #<channel>          - PM's you alll message numbers on <channel>.");
651            m_botAction.sendSmartPrivateMessage(name, "    !read                         - Reads all unread messages.");
652                m_botAction.sendSmartPrivateMessage(name, "    !read <num>                   - Reads you message <num>.");
653            m_botAction.sendSmartPrivateMessage(name, "    !read r                       - Reads all old/read messages.");
654            m_botAction.sendSmartPrivateMessage(name, "    !read a                       - Reads all read & unread messages.");
655            m_botAction.sendSmartPrivateMessage(name, "    !read #<channel>              - Reads all unread messages on <channel>.");
656            m_botAction.sendSmartPrivateMessage(name, "    !read #<channel>:r            - Reads all old/read messages on <channel>.");
657            m_botAction.sendSmartPrivateMessage(name, "    !read #<channel>:a            - Reads all messages on <channel>.");
658            m_botAction.sendSmartPrivateMessage(name, "    !unread <num>                 - Sets message <num> as unread.");
659                m_botAction.sendSmartPrivateMessage(name, "    !delete <num>                 - Deletes message <num>.");
660            m_botAction.sendSmartPrivateMessage(name, "    !delete read                  - Deletes messages already read.");
661            m_botAction.sendSmartPrivateMessage(name, "    !delete all                   - Deletes all messages.");
662                m_botAction.sendSmartPrivateMessage(name, "    !lmessage <name>:<message>    - Leaves <message> for <name>.");
663            } else if(message.toLowerCase().startsWith("c")) {
664                m_botAction.sendSmartPrivateMessage(name, "    !me                           - Tells you what channels you have joined.");
665                m_botAction.sendSmartPrivateMessage(name, "    !join <channel>               - Puts in request to join <channel>.");
666                m_botAction.sendSmartPrivateMessage(name, "    !quit <channel>               - Removes you from <channel>.");
667                m_botAction.sendSmartPrivateMessage(name, "    !owner <channel>              - Tells you who owns <channel>.");
668                m_botAction.sendSmartPrivateMessage(name, "    !announce <channel>:<message> - Sends everyone on <channel> a pm of <message>.");
669                m_botAction.sendSmartPrivateMessage(name, "    !message <channel>:<message>  - Leaves a message for everyone on <channel>.");
670                m_botAction.sendSmartPrivateMessage(name, "    !requests <channel>           - PM's you with all the requests to join <channel>.");
671                m_botAction.sendSmartPrivateMessage(name, "    !banned <channel>             - Lists players banned on <channel>.");
672                m_botAction.sendSmartPrivateMessage(name, "    !members <channel>            - Lists all members on <channel>.");
673                m_botAction.sendSmartPrivateMessage(name, "    !ban <channel>:<name>         - Bans <name> from <channel>.");
674                m_botAction.sendSmartPrivateMessage(name, "    !unban <channel>:<name>       - Lifts <name>'s ban from <channel>.");
675                m_botAction.sendSmartPrivateMessage(name, "    !makeop <channel>:<name>      - Makes <name> an operator in <channel>.");
676                m_botAction.sendSmartPrivateMessage(name, "    !deop <channel>:<name>        - Revokes <name>'s operator status in <channel>.");
677                m_botAction.sendSmartPrivateMessage(name, "    !grant <channel>:<name>       - Grants ownership of <channel> to <name>.");
678                m_botAction.sendSmartPrivateMessage(name, "    !private <channel>            - Makes <channel> a request based channel.");
679                m_botAction.sendSmartPrivateMessage(name, "    !public <channel>             - Makes <channel> open to everyone.");
680                m_botAction.sendSmartPrivateMessage(name, "    !destroy <channel>            - Destroys <channel>.");
681                m_botAction.sendSmartPrivateMessage(name, "    !accept <channel>:<name>      - Accepts <name>'s request to join <channel>.");
682                m_botAction.sendSmartPrivateMessage(name, "    !decline <channel>:<name>     - Declines <name>'s request to join <channel>.");
683                    if(m_botAction.getOperatorList().isBot(name))   m_botAction.sendSmartPrivateMessage(name, "    !create <channel>             - Creates a channel with the name <channel>.");
684            } else if((m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase())) && message.toLowerCase().startsWith("smod")) {
685                m_botAction.sendSmartPrivateMessage(name, "Smod+ commands:");
686                m_botAction.sendSmartPrivateMessage(name, "    !go <arena>                   - Sends messagebot to <arena>.");
687                m_botAction.sendSmartPrivateMessage(name, "    !die                          - Kills messagebot.");
688        } else {
689                String defaultHelp = "PM me with !help channel for channel system help, !help message for message system help";
690                if(m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
691                        defaultHelp += ", !help smod for SMod command help.";
692                else
693                        defaultHelp += ".";
694                m_botAction.sendSmartPrivateMessage(name, defaultHelp);
695        }
696
697    }
698
699    /** Does nothing
700     */
701    public void doNothing(String name, String message) {}
702
703        /** Passes a message event to the command interpreter
704         *  @param The message event being passed.
705         */
706        public void handleEvent(Message event)
707        {
708            if(event.getMessageType() == Message.ARENA_MESSAGE){
709                if(event.getMessage().contains(" - ")){
710                    playersOnline.add(event.getMessage().substring(0, event.getMessage().indexOf(" -")));
711                }
712            }
713                m_CI.handleEvent(event);
714        }
715
716        /** Sends the bot to the default arena and reloads all channels.
717         */
718        public void handleEvent(LoggedOn event)
719        {
720                try {
721                        m_botAction.joinArena(m_botAction.getBotSettings().getString("Default arena"));
722                        m_botAction.ipcSubscribe(IPCCHANNEL);
723                        //long before = Runtime.getRuntime().freeMemory();
724                        String opList[] = (m_botAction.getBotSettings().getString("Ops")).split(":");
725                        for(int k = 0;k < opList.length;k++)
726                                ops.add(opList[k].toLowerCase());
727
728                        String query = "SELECT * FROM tblChannel";
729                        try {
730                                ResultSet results = m_botAction.SQLQuery(database, query);
731
732                                while(results.next())
733                                {
734                                        String channelName = results.getString("fcChannelName");
735                                        String owner = results.getString("fcOwner");
736                                        int pub = results.getInt("fnPrivate");
737                                        boolean priv;
738                                        if(pub == 1)
739                                                priv = false;
740                                        else
741                                                priv = true;
742                                        Channel c = new Channel(owner, channelName, m_botAction, priv, true);
743                                        c.reload();
744                                        channels.put(channelName.toLowerCase(), c);
745                                }
746                m_botAction.SQLClose(results);
747                        } catch(SQLException e) { Tools.printStackTrace( e ); }
748
749                        //long after = Runtime.getRuntime().freeMemory();
750                        //long memUsed = before - after;
751                } catch(Exception e) {}
752                m_botAction.setMessageLimit(5);
753        m_botAction.ipcSubscribe(IPCCHANNEL);
754        }
755
756        /** Reads a message from the database.
757         *  @param Name of player reading the message.
758         *  @param Message number being read.
759         */
760        public void readMessage(String name, String message) {
761            /*
762        if( message == "" ) {
763            try {
764                LinkedList <String>messages = new LinkedList<String>();
765                LinkedList <Integer>ids = new LinkedList<Integer>();
766                ResultSet results = m_botAction.SQLQuery(database, "SELECT * FROM tblMessageSystem WHERE fcName='" +
767                    Tools.addSlashesToString(name) + "' AND fnRead='0'" );
768                if( !results.next() ) {
769                    m_botAction.sendSmartPrivateMessage(name, "You have no new messages.");
770                    return;                   
771                }
772                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy MMM d h:mma");
773               
774                while(results.next()) {
775                    String msg = results.getString("fcMessage");
776                    //String timestamp = results.getString("fdTimeStamp");
777
778                    String time = dateFormat.format( new Date( results.getTimestamp("fdTimeStamp").getTime() ) );
779                    //m_botAction.sendSmartPrivateMessage(name, timestamp + " " + message);
780                    String channel = results.getString("fcSender");
781                    messages.add( time + " " + (!channel.equals("") ? " (" + channel + ") " : " " ) + msg );
782                    ids.add( results.getInt("fnID") );
783                }               
784                String resetResults = "";
785                int idNum = 0;
786                for( Integer currentID : ids ) {
787                    if( idNum == 0 )
788                        resetResults += "fnID='" + currentID + "'";
789                    else
790                        resetResults += " OR fnID='" + currentID + "'";
791                    idNum++;
792                }
793                messages.add( "Total " + idNum + " message" + (idNum==1?"":"s") + " displayed." );
794               
795                messages.add( "Now attempting to set messages to read..." );
796                if( !resetResults.equals("") ) {
797                    String query = "UPDATE tblMessageSystem SET fnRead='1' WHERE " + resetResults + "";
798                    Tools.printLog( query );
799                    m_botAction.SQLQueryAndClose(database, query);
800                    messages.add( "Set messages as read." );
801                } else {
802                    messages.add( "Did not set messages as read." );
803                }
804               
805                /*
806                    messageIDs.add(results.getInt("fnID"));
807                Iterator<Integer> it = messageIDs.iterator();
808                if( !it.hasNext() ) {
809                    m_botAction.sendSmartPrivateMessage(name, "You have no new messages.");
810                    return;
811                }
812                while(it.hasNext()) {
813                    // SUCH an idiotic way to handle this... a query for each message?  Jesus Christ.
814                    // You already HAVE the query you need... work with it...
815                    // readMessage(name, "" + (Integer)it.next());                   
816                }
817                */
818            /*
819                SpamTask spamTask = new SpamTask();
820                spamTask.setMsgs( name, messages );
821                m_botAction.scheduleTask(spamTask, 75, 75 );
822                m_botAction.SQLClose(results);
823            } catch(SQLException e) {
824                Tools.printLog("Exception while trying to run SQL query in readMessage." );
825            }
826            return;
827        }
828        */
829                if(!isAllDigits(message)) {
830                        try {
831                                String addAnd = " AND fnRead='0'";
832                ResultSet results;
833                if( message.startsWith("#") && message.length() > 1 ) {
834                    String pieces[] = message.split(":", 2);
835                    if(pieces.length == 2) {
836                        message = pieces[0].substring(1);
837                        if(pieces[1].toLowerCase().startsWith("a"))
838                            addAnd = "";
839                        else if(pieces[1].toLowerCase().startsWith("r"))
840                            addAnd = " AND fnRead='1'";
841                    } else {
842                        message = message.substring(1);
843                    }
844                    results = m_botAction.SQLQuery(database, "SELECT * FROM tblMessageSystem WHERE fcSender = '"
845                            + Tools.addSlashesToString(message) + "' AND fcName = '" + Tools.addSlashesToString(name) + "'"+addAnd);
846                } else {
847                    // Not a channel request; either a standard !read, or reading all messages or only read messages
848                    if( message.toLowerCase().startsWith("a"))
849                        addAnd = "";
850                    else if( message.toLowerCase().startsWith("r"))
851                        addAnd = " AND fnRead='1'";
852                    results = m_botAction.SQLQuery(database, "SELECT * FROM tblMessageSystem WHERE fcName = '" +
853                            Tools.addSlashesToString(name) + "'"+addAnd);
854                }
855
856                LinkedList <String>messages = new LinkedList<String>();
857                LinkedList <Integer>ids = new LinkedList<Integer>();
858                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy MMM d h:mma");
859
860                if( !results.next() ) {
861                    if( addAnd.equals( " AND fnRead='0'" ) )
862                        m_botAction.sendSmartPrivateMessage(name, "You have no new messages.");
863                    else
864                        m_botAction.sendSmartPrivateMessage(name, "You have no messages fitting those criteria.");
865                    return;                   
866                }
867
868                int numMsgs = 0;
869                do {
870                    String msg = results.getString("fcMessage");
871                    //String timestamp = results.getString("fdTimeStamp");
872
873                    String time = dateFormat.format( new Date( results.getTimestamp("fdTimeStamp").getTime() ) );
874                    //m_botAction.sendSmartPrivateMessage(name, timestamp + " " + message);
875                    String channel = results.getString("fcSender");
876                    messages.add( time + " " + (!channel.equals("") ? " (" + channel + ") " : " " ) + msg );
877                    if( results.getInt("fnRead") == 0 )
878                        ids.add( results.getInt("fnID") );
879                    numMsgs++;
880                } while( results.next() );
881               
882                String resetResults = "";
883                int idResetNum = 0;
884                for( Integer currentID : ids ) {
885                    if( idResetNum == 0 )
886                        resetResults += "fnID='" + currentID + "'";
887                    else
888                        resetResults += " OR fnID='" + currentID + "'";
889                    idResetNum++;
890                }
891               
892                if( idResetNum == numMsgs ) {
893                    messages.add( "Total " + numMsgs + " new message" + (numMsgs==1?"":"s") + " displayed." );
894                } else {
895                    messages.add( "Total " + numMsgs + " message" + (numMsgs==1?"":"s") + " displayed." + (idResetNum>0 ? (" (" + idResetNum + " new)") : "") );                   
896                }
897               
898                if( !resetResults.equals("") ) {
899                    String query = "UPDATE tblMessageSystem SET fnRead='1' WHERE " + resetResults + "";
900                    m_botAction.SQLQueryAndClose(database, query);
901                }
902               
903                SpamTask spamTask = new SpamTask();
904                spamTask.setMsgs( name, messages );
905                m_botAction.scheduleTask(spamTask, 75, 75 );
906
907                /*
908                                while(results.next()) {
909                                        messageIDs.add(results.getInt("fnID"));
910                                }
911                                Iterator<Integer> it = messageIDs.iterator();
912                                while(it.hasNext()) {
913                                        int id = (Integer)it.next();
914                                        readMessage(name, ""+id);
915                                }
916                                */
917                m_botAction.SQLClose(results);
918                        } catch(Exception e) {
919                Tools.printLog("Exception while trying to run SQL query in readMessage." );                         
920                        }
921                        return;
922                }
923               
924                // Single message handling ONLY.  This method is NO LONGER recursively (and inefficiently) called.             
925                int messageNumber = -1;
926                try{
927                        messageNumber = Integer.parseInt(message);
928                } catch(Exception e) {
929                        m_botAction.sendSmartPrivateMessage(name, "Invalid message number");
930                        return;
931                }
932                if(!ownsMessage(name.toLowerCase(), messageNumber)) {
933                        m_botAction.sendSmartPrivateMessage(name, "That is not your message!");
934                        return;
935                }
936                String query = "SELECT * FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"' AND fnID='" + messageNumber + "'";
937                try{
938                        ResultSet results = m_botAction.SQLQuery(database, query);
939            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy MMM d h:mma");
940                        if(results.next()) {
941                message = results.getString("fcMessage");
942                String time = dateFormat.format( new Date( results.getTimestamp("fdTimeStamp").getTime() ) );
943                String channel = results.getString("fcSender");
944                m_botAction.sendSmartPrivateMessage(name, time + " " + (!channel.equals("") ? " (" + channel + ") " : " " ) + message);
945                if( results.getInt("fnRead") == 0 ) {
946                    query = "UPDATE tblMessageSystem SET fnRead='1' WHERE fnID='" + messageNumber +"'";
947                    m_botAction.SQLQueryAndClose(database, query);
948                }
949                        } else {
950                                m_botAction.sendSmartPrivateMessage(name, "Could not find that message.  PM !messages to see new messages, or !messages all to see all messages.");
951                        }
952            m_botAction.SQLClose(results);
953                } catch(Exception e) { Tools.printStackTrace( e ); }
954        }
955       
956        /**
957         * Support method to get the text of a given message when reading multiple message
958         * numbers.  The way this should have been written initially.  It took 20 minutes.
959         * (Passing a ResultSet seemed to result in erratic behavior for keeping track of
960         * the row.)
961         * @param rs
962         * @param dateFormat
963         * @return
964        public String getMessageText( ResultSet rs, SimpleDateFormat dateFormat ) {
965        try {
966            String message = rs.getString("fcMessage");
967            //String timestamp = results.getString("fdTimeStamp");
968
969            String time = dateFormat.format( new Date( rs.getTimestamp("fdTimeStamp").getTime() ) );
970            //m_botAction.sendSmartPrivateMessage(name, timestamp + " " + message);
971            String channel = rs.getString("fcSender");
972            return time + " " + (!channel.equals("") ? " (" + channel + ") " : " " ) + message;
973        } catch(Exception e) {
974            Tools.printStackTrace( e );
975            return "";
976        }
977        }
978     */
979
980        /** Marks a message's status as unread.
981         *  @param Name of player.
982         *  @param Message number being reset.
983         */
984        public void setAsNew(String name, String message)
985        {
986                int messageNumber = -1;
987                try{
988                        messageNumber = Integer.parseInt(message);
989                } catch(Exception e) {
990                        m_botAction.sendSmartPrivateMessage(name, "Invalid message number");
991                        return;
992                }
993                if(!ownsMessage(name.toLowerCase(), messageNumber)) {
994                        m_botAction.sendSmartPrivateMessage(name, "That is not your message!");
995                        return;
996                }
997                String query = "UPDATE tblMessageSystem SET fnRead = 0 WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"' AND fnID = " + messageNumber;
998                try {
999                        m_botAction.SQLClose(m_botAction.SQLQuery(database, query));
1000                        m_botAction.sendSmartPrivateMessage(name, "Message marked as unread.");
1001                } catch(SQLException e) {
1002                        Tools.printStackTrace( e );
1003                        m_botAction.sendSmartPrivateMessage(name, "Unable to mark as read.");
1004                }
1005        }
1006
1007        /** Deletes a message from the database.
1008         *  @param Name of player
1009         *  @param Message being deleted.
1010         */
1011        public void deleteMessage(String name, String message)
1012        {
1013                int messageNumber = -1;
1014                String query;
1015                if(message.equalsIgnoreCase("all")) {
1016                        query = "DELETE FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"'";
1017        } else if(message.equalsIgnoreCase("read")) {
1018            query = "DELETE FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"' AND fnRead = 1";
1019        } else {
1020                        try{
1021                                messageNumber = Integer.parseInt(message);
1022                        } catch(Exception e) {
1023                                m_botAction.sendSmartPrivateMessage(name, "Invalid message number");
1024                                return;
1025                        }
1026                        if(!ownsMessage(name.toLowerCase(), messageNumber)) {
1027                                m_botAction.sendSmartPrivateMessage(name, "That is not your message!");
1028                                return;
1029                        }
1030                        query = "DELETE FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"' AND fnID = " + messageNumber;
1031                }
1032                try {
1033                        m_botAction.SQLClose(m_botAction.SQLQuery(database, query));
1034                        m_botAction.sendSmartPrivateMessage(name, "Message(s) deleted.");
1035                } catch(Exception e) {
1036                        m_botAction.sendSmartPrivateMessage(name, "Message(s) unable to be deleted.");
1037                        Tools.printStackTrace( e );
1038                }
1039        }
1040
1041        /** PM's a player with all of his/her message numbers.
1042         *  @param Name of player.
1043         *  @param (does nothing).
1044         */
1045        public void myMessages(String name, String message)
1046        {
1047        boolean allMsgs = message.startsWith("all") || message.startsWith("*");
1048        String query;
1049        if( allMsgs ) {
1050            m_botAction.sendSmartPrivateMessage(name, "You have the following messages:");
1051            query = "SELECT * FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"' ORDER BY fnRead DESC";
1052        } else {
1053            if( message.startsWith("#") && message.length() > 1 ) {
1054                message = message.substring(1);
1055                m_botAction.sendSmartPrivateMessage(name, "You have the following messages on channel '" + message + "':");
1056                query = "SELECT * FROM tblMessageSystem WHERE fcSender = '" + Tools.addSlashesToString(message) + "' AND fcName = '" + Tools.addSlashesToString(name) + "'";
1057            } else { 
1058                m_botAction.sendSmartPrivateMessage(name, "You have the following unread messages (use '!msgs all' for a list of read and unread msgs):");
1059                query = "SELECT * FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(name.toLowerCase())+"' AND fnRead=0";
1060            }
1061        }
1062                try {
1063                        ResultSet results = m_botAction.SQLQuery(database, query);
1064                        LinkedList<String> msgs = new LinkedList<String>();
1065                        while(results.next())
1066                        {
1067                            String thisMessage = "Message #" + String.valueOf(results.getInt("fnID")) +
1068                            "  From: " + Tools.formatString(results.getString("fcSender"), 20 ) +
1069                            "  Read: [";
1070                            if(results.getInt("fnRead") == 1)
1071                                thisMessage += "X]";
1072                            else
1073                                thisMessage += " ]";
1074
1075                            msgs.add( thisMessage );
1076                        }
1077            SpamTask spamTask = new SpamTask();
1078            spamTask.setMsgs(name, msgs);
1079            m_botAction.scheduleTask(spamTask, 75, 75 );
1080           
1081            m_botAction.SQLClose(results);
1082                } catch(Exception e) {
1083                        m_botAction.sendSmartPrivateMessage(name, "Error while reading message database during listing of msgs.");
1084                        Tools.printStackTrace( e );
1085                }
1086                m_botAction.sendSmartPrivateMessage(name, "PM me with !read to read all unread messages, or use !read <num>.");
1087        }
1088
1089        /** Checks the database to make sure a player owns the
1090         *  message that he's trying to do stuff with.
1091         *  @param name Name of the player
1092         *  @param messageNumber Number of the message he/she is
1093         *         trying to do stuff to
1094         */
1095         public boolean ownsMessage(String name, int messageNumber)
1096         {
1097                String query = "SELECT * FROM tblMessageSystem WHERE fnID = " + messageNumber;
1098                try {
1099                        ResultSet results = m_botAction.SQLQuery(database, query);
1100
1101            if( results == null || !results.next() ) {
1102                m_botAction.SQLClose(results);
1103                return false;
1104             }
1105
1106                        if(results.getString("fcName").toLowerCase().equals(name)) {
1107                m_botAction.SQLClose(results);
1108                                return true;
1109                        } else {
1110                m_botAction.SQLClose(results);
1111                                return false;
1112                        }
1113                } catch(Exception e) {
1114        }
1115                return false;
1116         }
1117
1118        /** Retrieves the channel name out of the message.
1119         *  @param name Name of player.
1120         *  @param message Message sent
1121         */
1122         public String getChannel(String name, String message, boolean noParams) {
1123                if(noParams) {
1124                        return message;
1125                } else {
1126                        if(message.indexOf(":") == -1) {
1127                                return "";
1128                        } else {
1129                                String pieces[] = message.split(":");
1130                                return pieces[0];
1131                        }
1132                }
1133         }
1134
1135        /** Handles a message sent by pubbots to tell a player if they have new messages
1136         *  @param Name of player PM'ing
1137         *  @param Name of player logging in
1138         */
1139         public void playerLogin(String name, String player)
1140         {
1141                if(m_botAction.getOperatorList().isSysop(name))
1142                        checkNewMessages(player.toLowerCase());
1143                else checkNewMessages(name.toLowerCase());
1144         }
1145
1146        /** Sends the bot to a new arena.
1147         *  @param Name of player.
1148         *  @param Arena to go to.
1149         */
1150         public void handleGo(String name, String message)
1151         {
1152                if(m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase()))
1153                        m_botAction.changeArena(message);
1154         }
1155
1156        /** Kills the bot
1157         *  @param Name of player
1158         *  @param should be blank
1159         */
1160         public void handleDie(String name, String message)
1161         {
1162                if(m_botAction.getOperatorList().isHighmod(name) || ops.contains(name.toLowerCase())) {
1163                        try {
1164                                m_botAction.die();
1165                        } catch(Exception e) { }
1166                }
1167         }
1168
1169         /** Announces to a channel that they have recieved a new message.
1170          *  @param Name of channel
1171          */
1172         public Set<String> messageSentFromWebsite(String channel)
1173         {
1174                Set <String>s = null;
1175
1176                try {
1177                        Channel c = channels.get(channel.toLowerCase());
1178                        s = c.members.keySet();
1179                        s.removeAll(c.banned);
1180                } catch(Exception e) {  Tools.printStackTrace( e ); }
1181
1182                return s;
1183         }
1184
1185         /** Syncs the website and MessageBot's access levels
1186          *  @param Name of channel
1187          *  @param Name of player
1188          *  @param Access level
1189          */
1190         public void accessUpdateFromWebsite(String channel, String name, int level)
1191         {
1192                try {
1193                        Channel c = channels.get(channel.toLowerCase());
1194                        c.updateAccess(name, level);
1195                } catch(Exception e) { Tools.printStackTrace( e ); }
1196         }
1197
1198        /** Sets up the task that will delete messages that have expired.
1199         */
1200        void createTasks()
1201        {
1202                messageDeleteTask = new TimerTask()
1203                {
1204                        public void run()
1205                        {
1206                        //      String query = "DELETE FROM tblMessageSystem WHERE (fdTimeStamp < DATE_SUB(NOW(), INTERVAL 31 DAY)) AND fnRead = 0";
1207                        //      String query2 = "DELETE FROM tblMessageSystem WHERE (fdTimeStamp < DATE_SUB(NOW(), INTERVAL 15 DAY)) AND fnRead = 1";
1208                        //      try {
1209                        //              m_botAction.SQLQuery(database, query);
1210                        //              m_botAction.SQLQuery(database, query2);
1211                        //              System.out.println("Deleting messages.");
1212                        //      } catch(SQLException e) { Tools.printStackTrace( e ); }
1213                        }
1214                };
1215
1216                messageBotSync = new TimerTask()
1217                {
1218                        public void run()
1219                        {
1220                                HashSet <String>peopleToTell = new HashSet<String>();
1221
1222                                String query = "SELECT * FROM tblMessageToBot ORDER BY fnID ASC";
1223                                String query2 = "DELETE FROM tblMessageToBot";
1224                                try {
1225                                        ResultSet results = m_botAction.SQLQuery(database, query);
1226                                        if(results == null) return;
1227                                        while(results.next()) {
1228                                                String event = results.getString("fcSyncData");
1229                                                String pieces[] = event.split(":");
1230                                                if(pieces.length == 2)
1231                                                        peopleToTell.addAll(messageSentFromWebsite(pieces[1]));
1232                                                else
1233                                                        accessUpdateFromWebsite(pieces[2], pieces[1], Integer.parseInt(pieces[3]));
1234                                        }
1235                                        m_botAction.SQLClose(results);
1236                                        m_botAction.SQLClose(m_botAction.SQLQuery(database, query2));
1237                                } catch(Exception e) { Tools.printStackTrace( e ); }
1238
1239                                Iterator<String> it = peopleToTell.iterator();
1240                                while(it.hasNext()) {
1241                                        String player = (String)it.next();
1242                                        m_botAction.sendSmartPrivateMessage(player, "You have received a new message. PM me with !messages to read it.");
1243                                }
1244                        }
1245                };
1246
1247       
1248        }
1249
1250
1251     public void ignorePlayer(String name, String player) {
1252        try {
1253                if(!isIgnored(name, player)) {
1254                        m_botAction.SQLClose(m_botAction.SQLQuery(database, "INSERT INTO tblMessageBotIgnore (fcIgnorer, fcIgnoree) VALUES('"+Tools.addSlashesToString(name)+"', '"+Tools.addSlashesToString(player)+"');"));
1255                        m_botAction.sendSmartPrivateMessage(name, player + " ignored.");
1256                } else {
1257                        m_botAction.sendSmartPrivateMessage(name, player + " is already ignored.");
1258                }
1259        } catch(Exception e) {}
1260     }
1261
1262     public void unignorePlayer(String name, String player) {
1263        try {
1264                if(isIgnored(name, player)) {
1265                        m_botAction.SQLClose(m_botAction.SQLQuery(database, "DELETE FROM tblMessageBotIgnore WHERE fcIgnorer = '"+Tools.addSlashesToString(name)+"' AND fcIgnoree = '"+Tools.addSlashesToString(player)+"';"));
1266                        m_botAction.sendSmartPrivateMessage(name, player + " unignored.");
1267                } else {
1268                        m_botAction.sendSmartPrivateMessage(name, player + " is not currently ignored.");
1269                }
1270        } catch(Exception e) {}
1271     }
1272
1273     public void whoIsIgnored(String name, String blank) {
1274        try {
1275                ResultSet results = m_botAction.SQLQuery(database, "SELECT * FROM tblMessageBotIgnore WHERE fcIgnorer = '"+Tools.addSlashesToString(name)+"'");
1276                String ignored = "";
1277                while(results.next()) {
1278                        ignored += results.getString("fcIgnoree");
1279                        if(ignored.length() > 150) {
1280                                m_botAction.sendSmartPrivateMessage(name, ignored);
1281                                ignored = "";
1282                        } else {
1283                                ignored += ", ";
1284                        }
1285                }
1286                m_botAction.SQLClose(results);
1287                m_botAction.sendSmartPrivateMessage(name, ignored.substring(0, ignored.length() - 2));
1288        } catch(Exception e) {}
1289     }
1290
1291     public boolean isIgnored(String name, String player) {
1292        try {
1293                ResultSet results = m_botAction.SQLQuery(database, "SELECT * FROM tblMessageBotIgnore WHERE fcIgnorer = '"+Tools.addSlashesToString(name)+"' AND fcIgnoree = '"+Tools.addSlashesToString(player)+"'");
1294                if(results.next()) {
1295                        m_botAction.SQLClose(results);
1296                        return true;
1297                } else {
1298                        m_botAction.SQLClose(results);
1299                        return false;
1300                }
1301        } catch(Exception e) {}
1302        return false;
1303     }
1304
1305     public void leaveMessage(String name, String message) {
1306        if(message.indexOf(":") == -1) {
1307                m_botAction.sendSmartPrivateMessage(name, "Correct usage: !lmessage <name>:<message>");
1308                return;
1309        }
1310        String pieces[] = message.split(":", 2);
1311        String player = pieces[0];
1312        message = pieces[1];
1313        try {
1314                String query1 = "SELECT count(*) AS msgs FROM tblMessageSystem WHERE fcSender = '"+Tools.addSlashesToString(name)+"' AND fdTimeStamp > SUBDATE(NOW(), INTERVAL 7 DAY)";
1315                String query2 = "SELECT count(*) AS msgs FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(player)+"' AND fcSender = '"+Tools.addSlashesToString(name)+"' AND fdTimeStamp > SUBDATE(NOW(), INTERVAL 1 DAY)";
1316                //String query3 = "SELECT count(*) AS msgs FROM tblMessageSystem WHERE fcName = '"+Tools.addSlashesToString(player)+"'";
1317                ResultSet results = m_botAction.SQLQuery(database, query1);
1318                int msgsSent = 0;
1319                if(results.next()) {
1320                        msgsSent = results.getInt("msgs");
1321                }
1322                int plrMsgsRcvdFrmName = 0;
1323                m_botAction.SQLClose(results);
1324                results = m_botAction.SQLQuery(database, query2);
1325                if(results.next()) {
1326                        plrMsgsRcvdFrmName = results.getInt("msgs");
1327                }
1328                m_botAction.SQLClose(results);
1329            /*
1330                int plrMsgsRcvd = 0;
1331                results = m_botAction.SQLQuery(database, query3);
1332                if(results.next()) {
1333                        plrMsgsRcvd = results.getInt("msgs");
1334                }
1335                m_botAction.SQLClose(results);
1336            */
1337                if(msgsSent > 100) {
1338                        m_botAction.sendSmartPrivateMessage(name, "Sorry, you have reached your weekly quota of 100 messages. Please wait until some of your messages reset their stats before trying to send more.");
1339                        return;
1340                } else if(plrMsgsRcvdFrmName > 3) {
1341                        m_botAction.sendSmartPrivateMessage(name, "Sorry, you have reached your daily limit on messages to this player. Please wait before sending more messages.");
1342                        return;
1343            /*
1344                } else if(plrMsgsRcvd > 24) {
1345                        m_botAction.sendSmartPrivateMessage(name, "Sorry, the player's inbox is currently full. Please try to message him/her later.");
1346                        return;
1347            */
1348                } else if(isIgnored(player, name)) {
1349                        return;
1350                } else {
1351                        m_botAction.SQLClose(m_botAction.SQLQuery(database, "INSERT INTO tblMessageSystem (fnID, fcName, fcMessage, fcSender, fnRead, fdTimeStamp) VALUES(0, '"+Tools.addSlashesToString(player)+"', '"+Tools.addSlashesToString(message)+"', '"+Tools.addSlashesToString(name)+"', 0, NOW())"));
1352                        m_botAction.sendSmartPrivateMessage(name, "Message sent.");
1353                        checkPlayerOnline(player);
1354                        if(playersOnline.contains(player))
1355                            m_botAction.sendSmartPrivateMessage(name, "You have a new message, " +
1356                                        "type :MessageBot:!read to check");
1357                        else
1358                            m_botAction.sendUnfilteredPublicMacro("?message "+player+":You have a new message, " +
1359                                        "type :MessageBot:!read to check");
1360                }
1361        } catch(Exception e) {}
1362     }
1363
1364     public void registerAll(String name, String message) {
1365        if(!m_botAction.getOperatorList().isHighmod(name) && !ops.contains(name.toLowerCase()))
1366                return;
1367        try {
1368                String pieces[] = message.split(":",2);
1369                URL site = new URL(pieces[1]);
1370                HashSet <String>nameList = new HashSet<String>();
1371                if(site.getFile().toLowerCase().endsWith("txt"))
1372                {
1373                        URLConnection file = site.openConnection();
1374                        file.connect();
1375                        BufferedReader getnames = new BufferedReader(new InputStreamReader(file.getInputStream()));
1376                        String nextName;
1377                        while((nextName = getnames.readLine()) != null)
1378                                nameList.add(nextName);
1379                        file.getInputStream().close();
1380                        Iterator<String> it = nameList.iterator();
1381                        while(it.hasNext()) {
1382                                String addName = (String)it.next();
1383                                        ResultSet results = m_botAction.SQLQuery(database, "SELECT * FROM tblChannelUser WHERE fcName = '"
1384                                                + Tools.addSlashesToString(addName)+"' AND fcChannel = '"
1385                                                + Tools.addSlashesToString(pieces[0])+"'");
1386                                        if(!results.next()) {
1387                                                m_botAction.SQLClose(m_botAction.SQLQuery(database, "INSERT INTO tblChannelUser (fcName, fcChannel, fnLevel) VALUES ('"
1388                                                        + Tools.addSlashesToString(addName)+"', '"+Tools.addSlashesToString(pieces[0])+"', 1)"));
1389                                        }
1390                                        m_botAction.SQLClose(results);
1391                        }
1392                        m_botAction.sendSmartPrivateMessage(name, "Done");
1393                } else {
1394                        m_botAction.sendSmartPrivateMessage(name, "Please end the file name with .txt");
1395                }
1396        } catch(Exception e) {}
1397     }
1398
1399     public boolean isAllDigits(String test) {
1400                boolean allDigits = true;
1401                for(int k = 0;k < test.length() && allDigits;k++) {
1402                        if(!Character.isDigit(test.charAt(k))) allDigits = false;
1403                }
1404                return allDigits && test.length() != 0;
1405        }
1406     
1407     
1408     /**
1409      * Task used to send a spam of messages at a slower rate than normal.
1410      */
1411     private class SpamTask extends TimerTask {
1412         LinkedList <String>remainingMsgs = new LinkedList<String>();
1413         String nameToSpam = "";
1414
1415         public void setMsgs( String name, LinkedList<String> list ) {
1416             nameToSpam = name;
1417             remainingMsgs = list;
1418         }
1419
1420         public void run() {
1421             if( remainingMsgs == null || remainingMsgs.isEmpty() ) {
1422                 this.cancel();
1423             } else {
1424                 String msg = remainingMsgs.remove();
1425                 if( msg != null )
1426                     m_botAction.sendRemotePrivateMessage( nameToSpam, msg );
1427             }
1428         }
1429     }
1430}
1431
1432class Channel
1433{
1434        String owner;
1435        String channelName;
1436        BotAction m_bA;
1437        HashMap <String,Integer>members;
1438        HashSet <String>banned;
1439        boolean isOpen;
1440        String database = "website";
1441
1442        /** Constructs the new channel.
1443         */
1444        public Channel(String creator, String cName, BotAction botAction, boolean pub, boolean auto)
1445        {
1446                m_bA = botAction;
1447                owner = creator;
1448                channelName = cName.toLowerCase();
1449                isOpen = pub;
1450                members = new HashMap<String,Integer>();
1451                banned = new HashSet<String>();
1452                members.put(owner.toLowerCase(), new Integer(3));
1453                updateSQL(owner.toLowerCase(), 3);
1454
1455                if(!auto)
1456                        m_bA.sendSmartPrivateMessage(owner, "Channel created.");
1457        }
1458
1459        /** Returns wether the person is owner or not.
1460         *  @param Name of player being checked.
1461         */
1462        public boolean isOwner(String name)
1463        {
1464                if(!members.containsKey(name.toLowerCase()))
1465                        return false;
1466
1467                int level = members.get(name.toLowerCase()).intValue();
1468                if(level == 3) return true;
1469                else return false;
1470        }
1471
1472        /** Returns whether the person is an operator or not.
1473         *  @param Name of player being checked.
1474         */
1475        public boolean isOp(String name)
1476        {
1477                if(!members.containsKey(name.toLowerCase()))
1478                        return false;
1479
1480                int level = members.get(name.toLowerCase()).intValue();
1481                if(level >= 2) return true;
1482                else return false;
1483        }
1484
1485        /** Returns wheter the channel is public or private.
1486         *  @return
1487         */
1488        public boolean isOpen()
1489        {
1490                return isOpen;
1491        }
1492
1493        /** Gives channel ownership away
1494         *  @param Name of owner.
1495         *  @param Name of new owner.
1496         */
1497        public void newOwner(String name, String player)
1498        {
1499                if(members.containsKey(player.toLowerCase()))
1500                {
1501                        updateSQL(owner.toLowerCase(), 1);
1502                        updateSQL(player.toLowerCase(), 3);
1503                        try {
1504                                m_bA.SQLClose(m_bA.SQLQuery(database, "UPDATE tblChannel SET fcOwner = '"+Tools.addSlashesToString(player)+"' WHERE fcChannelName = '" + Tools.addSlashesToString(channelName.toLowerCase()) + "'"));
1505                        } catch(Exception e) { Tools.printStackTrace( e ); }
1506                        owner = player;
1507                        m_bA.sendSmartPrivateMessage(player, "I have just left you an important message. PM me with !messages receive it.");
1508                        leaveMessage(name, player, "You have been made the owner of " + channelName + " channel.");
1509                        m_bA.sendSmartPrivateMessage(name, player + " has been granted ownership of " + channelName);
1510                }
1511                else
1512                        m_bA.sendSmartPrivateMessage(name, "This player is not in the channel.");
1513        }
1514
1515        /** Adds an operator.
1516         *  @param Name of owner.
1517         *  @param Name of new operator.
1518         */
1519        public void makeOp(String name, String player)
1520        {
1521                if(isOwner(player)) {
1522                                m_bA.sendSmartPrivateMessage(name, "You can't take away your owner access!");
1523                                return;
1524                }
1525                if(members.containsKey(player.toLowerCase()))
1526                {
1527                        updateSQL(player.toLowerCase(), 2);
1528                        m_bA.sendSmartPrivateMessage(player, "I have just left you an important message. PM me with !messages receive it.");
1529                        leaveMessage(name, player, "You have been made an operator in " + channelName + " channel.");
1530                        m_bA.sendSmartPrivateMessage(name, player + " has been granted op powers in " + channelName);
1531                }
1532                else
1533                        m_bA.sendSmartPrivateMessage(name, "This player is not in the channel.");
1534        }
1535
1536        /** Removes an operator.
1537         *  @param Name of owner.
1538         *  @param Name of op being deleted.
1539         */
1540        public void deOp(String name, String player)
1541        {
1542                if(members.containsKey(player.toLowerCase()))
1543                {
1544                        if(isOwner(player)) {
1545                                m_bA.sendSmartPrivateMessage(name, "You can't take away your owner access!");
1546                                return;
1547                        }
1548                        updateSQL(player.toLowerCase(), 1);
1549                        m_bA.sendSmartPrivateMessage(player, "I have just left you an important message. PM me with !messages receive it.");
1550                        leaveMessage(name, player, "Your operator priveleges in " + channelName + " channel have been revoked.");
1551                        m_bA.sendSmartPrivateMessage(name, player + "'s op powers in " + channelName + " have been revoked.");
1552                }
1553                else
1554                        m_bA.sendSmartPrivateMessage(name, "This player is not in the channel.");
1555        }
1556
1557        /** Makes the channel private.
1558         *  @param Name of owner.
1559         */
1560        public void makePrivate(String name)
1561        {
1562                try {
1563                        m_bA.SQLClose(m_bA.SQLQuery(database, "UPDATE tblChannel SET fnPrivate = 1 WHERE fcChannelName = '" + Tools.addSlashesToString(channelName.toLowerCase()) + "'"));
1564                } catch(Exception e) { Tools.printStackTrace( e ); }
1565                m_bA.sendSmartPrivateMessage(name, "Now private channel.");
1566                isOpen = false;
1567        }
1568
1569        /** Makes the channel public.
1570         *  @param Name of owner.
1571         */
1572        public void makePublic(String name)
1573        {
1574                try {
1575                        m_bA.SQLClose(m_bA.SQLQuery(database, "UPDATE tblChannel SET fnPrivate = 0 WHERE fcChannelName = '" + Tools.addSlashesToString(channelName.toLowerCase()) + "'"));
1576                } catch(Exception e) { Tools.printStackTrace( e ); }
1577                m_bA.sendSmartPrivateMessage(name, "Now public channel.");
1578                isOpen = true;
1579        }
1580
1581        /** Sends a ?message to everyone on channel and pm's the players that
1582         *  are online to tell them they got a message.
1583         *  @param Name of operator.
1584         *  @param Message being sent.
1585         *  @return Number of players messaged
1586         */
1587        public int messageChannel(String name, String message)
1588        {
1589            int numMsgd = 0;
1590                Iterator<String> it = members.keySet().iterator();
1591
1592                while(it.hasNext())
1593                {
1594                        String player = (String)it.next();
1595                        int level = members.get(player.toLowerCase()).intValue();
1596                        if(level > 0)
1597                        {
1598                            // sends a ?message to all players in channel
1599                            m_bA.sendUnfilteredPublicMessage("?message " + player +
1600                ":You have new messages, type :MessageBot:!read to check them!");
1601                           
1602                            numMsgd++;
1603                                leaveMessage(name, player, message);
1604                                m_bA.sendSmartPrivateMessage(player, "I have just left you an important message. PM me with !messages receive it.");
1605                        }
1606                }
1607                return numMsgd;
1608        }
1609
1610        /** PM's everyone on channel.
1611         *  @param Name of operator.
1612         *  @param Message being sent.
1613         */
1614        public void announceToChannel(String name, String message)
1615        {
1616                Iterator<String> it = members.keySet().iterator();
1617
1618                while(it.hasNext())
1619                {
1620                        String player = it.next();
1621                        int level = members.get(player.toLowerCase()).intValue();
1622                        if(level > 0)
1623                        {
1624                                m_bA.sendSmartPrivateMessage(player, channelName + ": " + name + "> " + message);
1625                        }
1626                }
1627        }
1628
1629        /** Puts in request to join channel.
1630         *  @param Name of player wanting to join.
1631         */
1632        public void joinRequest(String name)
1633        {
1634                if(members.containsKey(name.toLowerCase()))
1635                {
1636                        m_bA.sendSmartPrivateMessage(name, "You are already on this channel.");
1637                        return;
1638                }
1639                if(banned.contains(name.toLowerCase()))
1640                {
1641                        m_bA.sendSmartPrivateMessage(name, "You have been banned from this channel.");
1642                        return;
1643                }
1644                if(isOpen)
1645                {
1646                        updateSQL(name.toLowerCase(), 1);
1647                        m_bA.sendSmartPrivateMessage(name, "You have been accepted to " + channelName + " announcement channel.");
1648                }
1649                else
1650                {
1651                        updateSQL(name.toLowerCase(), 0);
1652                        m_bA.sendSmartPrivateMessage(name, "You have been placed into the channel request list. The channel owner will make the decision.");
1653                }
1654        }
1655
1656        /** Removes a player from the channel
1657         *  @param Name of player leaving.
1658         */
1659        public void leaveChannel(String name)
1660        {
1661                if(members.containsKey(name.toLowerCase()))
1662                {
1663                        int level = members.get(name.toLowerCase()).intValue();
1664                        if(level < 0)
1665                        {
1666                                m_bA.sendSmartPrivateMessage(name, "You are not on this channel.");
1667                                return;
1668                        }
1669                        if(isOwner(name)) {
1670                                m_bA.sendSmartPrivateMessage(name, "You have to make a new owner before you leave.");
1671                                return;
1672                        }
1673                        updateSQL(name.toLowerCase(), -5);
1674                        m_bA.sendSmartPrivateMessage(name, "You have been removed from the channel.");
1675                }
1676                else
1677                        m_bA.sendSmartPrivateMessage(name, "You are not on this channel.");
1678        }
1679
1680        /** Lists all requests to join channel.
1681         *  @param Name of operator.
1682         */
1683        public void listRequests(String name)
1684        {
1685                Iterator<String> it = members.keySet().iterator();
1686
1687                m_bA.sendSmartPrivateMessage(name, "People requesting to join: ");
1688
1689                while(it.hasNext())
1690                {
1691                        String p = it.next();
1692                        int level = members.get(p).intValue();
1693                        if(level == 0)
1694                                m_bA.sendSmartPrivateMessage(name, p);
1695                }
1696        }
1697
1698        /** Accepts a player onto channel.
1699         *  @param Name of operator.
1700         *  @param Name of player being accepted.
1701         */
1702        public void acceptPlayer(String name, String player)
1703        {
1704                if(members.containsKey(player.toLowerCase()))
1705                {
1706                        updateSQL(player.toLowerCase(), new Integer(1));
1707                        m_bA.sendSmartPrivateMessage(player, "I have just left you an important message. PM me with !messages receive it.");
1708                        leaveMessage(name, player, "You have been accepted into " + channelName + " channel.");
1709                        m_bA.sendSmartPrivateMessage(name, player + " accepted.");
1710                }
1711                else
1712                        m_bA.sendSmartPrivateMessage(name, "This player has not requested to join.");
1713        }
1714
1715        /** Rejects a player's request.
1716         *  @param Name of operator.
1717         *  @param Name of player being rejected.
1718         */
1719        public void rejectPlayer(String name, String player)
1720        {
1721                if(members.containsKey(player.toLowerCase()))
1722                {
1723                        updateSQL(player, -5);
1724                        m_bA.sendSmartPrivateMessage(player, "I have just left you an important message. PM me with !messages receive it.");
1725                        leaveMessage(name, player, "You have been rejected from " + channelName + " channel.");
1726                        m_bA.sendSmartPrivateMessage(name, player + " rejected.");
1727                }
1728                else
1729                        m_bA.sendSmartPrivateMessage(name, "This player is not on the channel.");
1730        }
1731
1732        /** Bans a player from the channel.
1733         *  @param Name of operator
1734         *  @param Name of player getting banned.
1735         */
1736        public void banPlayer(String name, String player)
1737        {
1738                if(isOwner(player)) {
1739                        m_bA.sendSmartPrivateMessage(name, "You cannot ban the owner!");
1740                        return;
1741                }
1742                if(banned.contains(player.toLowerCase()))
1743                {
1744                        m_bA.sendSmartPrivateMessage(name, "That player is already banned.");
1745                        return;
1746                }
1747                else
1748                {
1749                        banned.add(player.toLowerCase());
1750                        m_bA.sendSmartPrivateMessage(name, player + " has been banned.");
1751                }
1752                if(members.containsKey(player.toLowerCase()))
1753                {
1754                        int level = members.get(player.toLowerCase()).intValue();
1755                        level *= -1;
1756                        updateSQL(player, level);
1757                }
1758        }
1759
1760        /** Unbans a player.
1761         *  @param Name of operator.
1762         *  @param Name of player being unbanned.
1763         */
1764        public void unbanPlayer(String name, String player)
1765        {
1766                if(banned.contains(player.toLowerCase()))
1767                {
1768                        banned.remove(player.toLowerCase());
1769                        m_bA.sendSmartPrivateMessage(name, player + " has been unbanned.");
1770                }
1771                else
1772                {
1773                        m_bA.sendSmartPrivateMessage(name, "That player is not banned.");
1774                        return;
1775                }
1776                if(members.containsKey(player.toLowerCase()))
1777                {
1778                        int level = members.get(player.toLowerCase()).intValue();
1779                        level *= -1;
1780                        updateSQL(player, level);
1781                }
1782        }
1783
1784        /** Updates the database when a player's level of access changes.
1785         *  @param Player being changed.
1786         *  @param New level of access.
1787         */
1788        public void updateSQL(String player, int level)
1789        {
1790                String query = "SELECT * FROM tblChannelUser WHERE fcName = '" + Tools.addSlashesToString(player.toLowerCase())+"' AND fcChannel = '"+Tools.addSlashesToString(channelName)+"'";
1791
1792
1793                try {
1794                        ResultSet results = m_bA.SQLQuery(database, query);
1795                        if(results.next())
1796                        {
1797                                if(level != -5) {
1798                                        query = "UPDATE tblChannelUser SET fnLevel = " + level + " WHERE fcName = '" + Tools.addSlashesToString(player.toLowerCase()) + "' AND fcChannel = '" + Tools.addSlashesToString(channelName) +"'";
1799                                        members.put(player.toLowerCase(), new Integer(level));
1800                                } else {
1801                                        query = "DELETE FROM tblChannelUser WHERE fcName = '" + Tools.addSlashesToString(player.toLowerCase())+"'";
1802                                        members.remove(player.toLowerCase());
1803                                }
1804                                m_bA.SQLClose(m_bA.SQLQuery(database, query));
1805                        }
1806                        else
1807                        {
1808                                query = "INSERT INTO tblChannelUser (fcChannel, fcName, fnLevel) VALUES ('" + Tools.addSlashesToString(channelName) + "', '" + Tools.addSlashesToString(player.toLowerCase()) + "', " + level + ")";
1809                                members.put(player.toLowerCase(), new Integer(level));
1810                                m_bA.SQLClose(m_bA.SQLQuery(database, query));
1811                        }
1812                        m_bA.SQLClose(results);
1813                } catch(SQLException sqle) { Tools.printStackTrace( sqle ); }
1814                  catch(NullPointerException npe) { System.out.println("Silly debugging...."); }
1815        }
1816
1817        /** Leaves a message from for a player in the database.
1818         *  @param Name of player leaving the message.
1819         *  @param Name of player recieving the message.
1820         *  @param Message being left.
1821         */
1822        public void leaveMessage(String name, String player, String message)
1823        {
1824                String query = "INSERT INTO tblMessageSystem (fnID, fcName, fcMessage, fcSender, fnRead, fdTimeStamp) VALUES (0, '"+Tools.addSlashesToString(player.toLowerCase())+"', '"+Tools.addSlashesToString(name) + ": " + Tools.addSlashesToString(message)+"', '"+Tools.addSlashesToString(channelName)+"', 0, NOW())";
1825                try {
1826                        m_bA.SQLClose(m_bA.SQLQuery(database, query));
1827                } catch(SQLException sqle) { Tools.printStackTrace( sqle ); }
1828        }
1829
1830        /** Reload is called when the bot respawns. Allows channel to resume from where it was before bot went offline.
1831         */
1832        public void reload()
1833        {
1834                String query = "SELECT * FROM tblChannelUser WHERE fcChannel = '" + Tools.addSlashesToString(channelName.toLowerCase())+"'";
1835
1836                try {
1837                        ResultSet results = m_bA.SQLQuery(database, query);
1838                        while(results.next())
1839                        {
1840                                String name = results.getString("fcName");
1841                                int level = results.getInt("fnLevel");
1842                                members.put(name.toLowerCase(), new Integer(level));
1843                                if(level < 0)
1844                                        banned.add(name.toLowerCase());
1845                        }
1846                        m_bA.SQLClose(results);
1847                } catch(Exception e) { Tools.printStackTrace( e ); }
1848        }
1849
1850        /** Lists all players on channel.
1851         *  @param Name of player.
1852         */
1853        public void listMembers(String name)
1854        {
1855                Iterator<String> it = members.keySet().iterator();
1856                String message = "";
1857                m_bA.sendSmartPrivateMessage(name, "List of players on " + channelName + ": ");
1858        if( !it.hasNext() ) {
1859            m_bA.sendSmartPrivateMessage(name, "Error: no members found.  Please use ?help to report this problem." );
1860            return;
1861        }
1862
1863                for(int k = 0;it.hasNext();)
1864                {
1865                        String pName = (String)it.next();
1866
1867                        int level = members.get(pName.toLowerCase());
1868
1869                        if(isOwner(pName))
1870                                message += pName + " (Owner), ";
1871                        else if(isOp(pName))
1872                                message += pName + " (Op), ";
1873                        else if(level > 0)
1874                                message += pName + ", ";
1875                        k++;
1876                        if(k % 10 == 0 || !it.hasNext())
1877                        {
1878                if( message.length() > 2 ) {
1879                    m_bA.sendSmartPrivateMessage(name, message.substring(0, message.length() - 2));
1880                    message = "";
1881                }
1882                        }
1883                }
1884        }
1885
1886        /** Lists all players banned from channel.
1887         *  @param Name of player.
1888         */
1889        public void listBanned(String name)
1890        {
1891                Iterator<String> it = banned.iterator();
1892                String message = "";
1893                m_bA.sendSmartPrivateMessage(name, "List of players banned from " + channelName + ": ");
1894                for(int k = 0;it.hasNext();)
1895                {
1896                        String pName = (String)it.next();
1897                        if(k % 10 != 0)
1898                                message += ", ";
1899
1900                        message += pName;
1901                        k++;
1902                        if(k % 10 == 0 || !it.hasNext())
1903                        {
1904                                m_bA.sendSmartPrivateMessage(name, message);
1905                                message = "";
1906                        }
1907                }
1908        }
1909
1910        /** Updates access after website refresh
1911         *  @param Name of player
1912         *  @param New access level
1913         */
1914         public void updateAccess(String name, int level) {
1915                members.put(name.toLowerCase(), new Integer(level));
1916                if(level < 0) {
1917                        banned.add(name.toLowerCase());
1918                } else if(banned.contains(name.toLowerCase())) {
1919                        banned.remove(name.toLowerCase());
1920                }
1921         }
1922
1923}
Note: See TracBrowser for help on using the browser.