javasubclassircsendmessagepircbot

sendMessage to IRC channel with PircBot


I am in the process of making an IRC bot for practise but am stuck. I use the PircBot library as a base.

I have the problem, that I can send messages to the channel as follows:

public void onMessage(String channel, String sender,
String login, String hostname, String message){

    if(message.equalsIgnoreCase("hello")){

    sendMessage(channel, "Hello "+sender);
    }
}

This is in the normal "bot" class and works. But that gets messy really fast, so I created two classes to sort that out. They are called with:

public void onMessage(String channel, String sender, String message) {`
    MessageHandler mh = new MessageHandler();
    CommandHandler ch = new CommandHandler();

    if (message.startsWith("+")){
    ch.commandQuery(channel, sender, message);
    }
    else{mh.messageRespondQuery(channel, sender, message);
    }
}

Which ALSO works fine. But if I try to send a message in the subclasses like

if (message.contains("test")){
            sendMessage("test successful");
        }

It does not send a message at all. Even if I "nest" the sendMessage() method in another method in the "bot" class it does not work. Only inside the onMessage() method. I debugged it and it moves to everywhere correctly, exept that it does not send a message. The same problem applies to the sendRawLine() method.

Can anyone with IRC/pircbot knowledge help me?


Solution

  • Answer

    Your problem is that the handler classes have no reference to the bot at all, and since the class itself has no sendMessage function, it won't send the message.

    You should include the bot object in the constructor of the handler class, i.e;

    MessageHandler mh = new MessageHandler(this);
    CommandHandler ch = new CommandHandler(this);
    

    Explanation

    this is a keyword in Java that refers to the instance of the class itself. By sending an instance of your bot class to the constructor and setting up the constructor to accept it, you have essentially sent a copy of the bot instance to the handler class. You would accept it using a constructor like:

    public MessageHandler(BotClassName b) {
        this.b = b;
    }
    

    And then send a message using:

    if (message.contains("test")) {
        b.sendMessage("test successful")
    }