如何正确关闭Bot :: BasicBot bot(基于POE :: Component :: IRC)?

时间:2010-03-18 16:06:24

标签: perl irc bots poe

这是一个示例脚本。当我按下Ctrl + C时,机器人退出IRC但一段时间后它重新连接。如何正确关闭机器人?

#!/usr/bin/perl

package main;

my $bot = Perlbot->new (server => 'irc.dal.net');

$SIG{'INT'} = 'Handler';
$SIG{'TERM'} = 'Handler';

sub Handler {
print "\nShutting down bot...\n";
$bot->shutdown('Killed.');
};

$bot->run;

package Perlbot;
use base qw(Bot::BasicBot);

sub connected {
my $self = shift;
$self->join('#codetestchan');
}

2 个答案:

答案 0 :(得分:2)

我接管了Bot :: BasicBot的维护工作,从版本0.82开始,您可以使用$bot->shutdown($quit_message)正确关闭它。

答案 1 :(得分:0)

从Bot :: BasicBot的文档和源代码看,我找不到一种优雅的方法来关闭它。如您所示,调用$bot->shutdown()(实际上将shutdown事件发送到POE::Component::IRC)只会导致Bot::BasicBot重新连接(顺便提一下$bot->quit()

用户遇到的此限制和其他限制导致我建议直接使用POE::Component::IRC。它现在有许多插件用于Bot::BasicBot提供的功能,这些功能在创建Bot::BasicBot时丢失了。虽然您可能需要输入更多内容才能启动并运行基本的机器人,但您可以获得更大的灵活性。以下是您的示例中的机器人,而不使用Bot::BasicBot。当您按CTRL + C时,它将向IRC服务器发送退出消息,等待它断开连接,然后退出:

#!/usr/bin/env perl

use strict;
use warnings;
use POE;
use POE::Component::IRC::State;
use POE::Component::IRC::Common qw(parse_user);
use POE::Component::IRC::Plugin::Connector;
use POE::Component::IRC::Plugin::AutoJoin;

# create our session
POE::Session->create(
    package_states => [
        # event handlers
        (__PACKAGE__) => [qw(_start int irc_join irc_disconnected)]
    ]
);

# start the event loop
POE::Kernel->run();

# session start handler
sub _start {
    my ($kernel, $heap) = @_[KERNEL, HEAP];

    # handle CTRL+C
    $kernel->sig(INT => 'int');

    # create bot object
    my $irc = POE::Component::IRC::State->spawn(
        server => 'irc.freenode.net',
        nick   => 'basic123bot',
        debug  => 1,
    );

    # save $irc in our session's storage heap
    $heap->{irc} = $irc;

    # handle reconnects
    $irc->plugin_add('Connector', POE::Component::IRC::Plugin::Connector->new());

    # handle channel joining
    $irc->plugin_add('AutoJoin', POE::Component::IRC::Plugin::AutoJoin->new(
        Channels => ['#foo123bar'],
    ));

    # connect to IRC
    $irc->yield('connect');
}

# interrupt signal handler
sub int {
    my ($kernel, $heap) = @_[KERNEL, HEAP];

    $heap->{irc}->yield('quit', 'Quitting, bye!');
    $heap->{shutting_down} = 1;
    $kernel->sig_handled();
}

# join handler
sub irc_join {
    my ($who, $chan) = @_[ARG0, ARG1];
    my $irc = $_[HEAP]->{irc};

    my ($nick, $user, $host) = parse_user($who);
    if ($nick eq $irc->nick_name()) {
        # say hello to channel members
        $irc->yield('privmsg', $chan, 'Hello everybody');
    }
}

# disconnect handler
sub irc_disconnected {
    my ($heap) = $_[HEAP];

    # shut down if we disconnected voluntarily
    $heap->{irc}->yield('shutdown') if $heap->{shutting_down};
}