简体   繁体   English

使用 PircBot 将消息发送到 IRC 频道

[英]sendMessage to IRC channel with PircBot

I am in the process of making an IRC bot for practise but am stuck.我正在制作一个用于练习的 IRC 机器人,但被卡住了。 I use the PircBot library as a base.我使用 PircBot 库作为基础。

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.这是在正常的“bot”类中并且有效。 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.即使我将 sendMessage() 方法“嵌套”在“bot”类中的另一个方法中,它也不起作用。 Only inside the onMessage() method.仅在 onMessage() 方法内部。 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.同样的问题也适用于 sendRawLine() 方法。

Can anyone with IRC/pircbot knowledge help me?有 IRC/pircbot 知识的人可以帮助我吗?

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.您的问题是处理程序类根本没有对机器人的引用,并且由于类本身没有 sendMessage 函数,因此它不会发送消息。

You should include the bot object in the constructor of the handler class, ie;您应该在处理程序类的构造函数中包含 bot 对象,即;

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. this是 Java 中的一个关键字,指的是类本身的实例。 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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM