This file is indexed.

/usr/share/perl5/Bot/BasicBot.pm is in libbot-basicbot-perl 0.89-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
package Bot::BasicBot;
BEGIN {
  $Bot::BasicBot::AUTHORITY = 'cpan:HINRIK';
}
BEGIN {
  $Bot::BasicBot::VERSION = '0.89';
}

use strict;
use warnings;

use Carp;
use Encode qw(encode);
use Exporter;
use IRC::Utils qw(decode_irc);
use POE::Kernel;
use POE::Session;
use POE::Wheel::Run;
use POE::Filter::Line;
use POE::Component::IRC::State;
use POE::Component::IRC::Plugin::Connector;
use Text::Wrap ();

use base 'Exporter';
our @EXPORT = qw(say emote);

sub new {
    my $class = shift;
    my $self = bless {}, $class;

    $self->{IRCNAME} = 'wanna'.int(rand(100000));
    $self->{ALIASNAME} = 'pony'.int(rand(100000));

    # call the set methods
    my %args = @_;
    for my $method (keys %args) {
        if ($self->can($method)) {
            $self->$method($args{$method});
        }
        else {
            $self->{$method} = $args{$method};
            #croak "Invalid argument '$method'";
        }
    }
    $self->{charset} = 'utf8' if !defined $self->{charset};

    $self->init or die "init did not return a true value - dying";

    return $self;
}

sub run {
    my $self = shift;

    # create the callbacks to the object states
    POE::Session->create(
        object_states => [
            $self => {
                _start => "start_state",
                die    => "die_state",

                irc_001          => "irc_001_state",
                irc_msg          => "irc_said_state",
                irc_public       => "irc_said_state",
                irc_ctcp_action  => "irc_emoted_state",
                irc_notice       => "irc_noticed_state",

                irc_disconnected => "irc_disconnected_state",
                irc_error        => "irc_error_state",

                irc_join         => "irc_chanjoin_state",
                irc_part         => "irc_chanpart_state",
                irc_kick         => "irc_kicked_state",
                irc_nick         => "irc_nick_state",
                irc_quit         => "irc_quit_state",

                fork_close       => "fork_close_state",
                fork_error       => "fork_error_state",

                irc_366          => "names_done_state",

                irc_332          => "topic_raw_state",
                irc_topic        => "topic_state",

                irc_shutdown     => "shutdown_state",

                tick => "tick_state",
            }
        ]
    );

    # and say that we want to recive said messages
    $poe_kernel->post($self->{IRCNAME}, 'register', 'all');

    # run
    $poe_kernel->run() if !$self->{no_run};
    return;
}

sub init { return 1; }

sub said { return }

sub emoted {
    return shift->said(@_);
}

sub noticed {
    return shift->said(@_);
}

sub chanjoin { return }

sub chanpart { return }

sub got_names { return }

sub topic { return }

sub nick_change { return }

sub kicked { return }

sub tick { return 0; }

sub help { return "Sorry, this bot has no interactive help." }

sub connected { return }

sub userquit {
    my ($self, $mess) = @_;
    return;
}

sub schedule_tick {
    my $self = shift;
    my $time = shift || 5;
    $poe_kernel->delay('tick', $time);
    return;
}

sub forkit {
    my $self = shift;
    my $args;

    if (ref($_[0])) {
        $args = shift;
    }
    else {
        my %args = @_;
        $args = \%args;
    }

    return if !$args->{run};

    $args->{handler}   = $args->{handler}   || "_fork_said";
    $args->{arguments} = $args->{arguments} || [];

    #install a new handler in the POE kernel pointing to
    # $self->{$args{handler}}
    $poe_kernel->state( $args->{handler}, $args->{callback} || $self  );

    my $run;
    if (ref($args->{run}) =~ /^CODE/) {
        $run = sub {
            $args->{run}->($args->{body}, @{ $args->{arguments} })
        };
    }
    else {
        $run = $args->{run};
    }

    my $wheel = POE::Wheel::Run->new(
        Program      => $run,
        StdoutFilter => POE::Filter::Line->new(),
        StderrFilter => POE::Filter::Line->new(),
        StdoutEvent  => "$args->{handler}",
        StderrEvent  => "fork_error",
        CloseEvent   => "fork_close"
    );

    # Use a signal handler to reap dead processes
    $poe_kernel->sig_child($wheel->PID, "got_sigchld");

    # store the wheel object in our bot, so we can retrieve/delete easily

    $self->{forks}{ $wheel->ID } = {
        wheel => $wheel,
        args  => {
            channel => $args->{channel},
            who     => $args->{who},
            address => $args->{address}
        }
    };
    return;
}

sub _fork_said {
    my ($self, $body, $wheel_id) = @_[OBJECT, ARG0, ARG1];
    chomp $body;    # remove newline necessary to move data;

    # pick up the default arguments we squirreled away earlier
    my $args = $self->{forks}{$wheel_id}{args};
    $args->{body} = $body;

    $self->say($args);
    return;
}

sub say {
    # If we're called without an object ref, then we're handling saying
    # stuff from inside a forked subroutine, so we'll freeze it, and toss
    # it out on STDOUT so that POE::Wheel::Run's handler can pick it up.
    if (!ref $_[0]) {
        print $_[0], "\n";
        return 1;
    }

    # Otherwise, this is a standard object method

    my $self = shift;
    my $args;
    if (ref $_[0]) {
        $args = shift;
    }
    else {
        my %args = @_;
        $args = \%args;
    }

    my $body = $args->{body};

    # add the "Foo: bar" at the start
    if ($args->{channel} ne "msg" && defined $args->{address}) {
        $body = "$args->{who}: $body";
    }

    # work out who we're going to send the message to
    my $who = $args->{channel} eq "msg" ? $args->{who} : $args->{channel};

    if (!defined $who || !defined $body) {
        $self->log("Can't send a message without target and body\n"
              . " called from "
              . ( [caller]->[0] )
              . " line "
              . ( [caller]->[2] ) . "\n"
              . " who = '$who'\n body = '$body'\n");
        return;
    }

    # if we have a long body, split it up..
    local $Text::Wrap::columns = 300;
    local $Text::Wrap::unexpand = 0; # no tabs
    my $wrapped = Text::Wrap::wrap('', '..', $body); #  =~ m!(.{1,300})!g;
    # I think the Text::Wrap docs lie - it doesn't do anything special
    # in list context
    my @bodies = split /\n+/, $wrapped;

    # Allows to override the default "PRIVMSG". Used by notice()
    my $irc_command = defined $args->{irc_command}
        && $args->{irc_command} eq 'notice'
        ? 'notice'
        : 'privmsg';

    # post an event that will send the message
    for my $body (@bodies) {
        my ($enc_who, $enc_body) = $self->charset_encode($who, $body);
        #warn "$enc_who => $enc_body\n";
        $poe_kernel->post(
            $self->{IRCNAME},
            $irc_command,
            $enc_who,
            $enc_body,
        );
    }

    return;
}

sub emote {
    # If we're called without an object ref, then we're handling emoting
    # stuff from inside a forked subroutine, so we'll freeze it, and
    # toss it out on STDOUT so that POE::Wheel::Run's handler can pick
    # it up.
    if (!ref $_[0]) {
        print $_[0], "\n";
        return 1;
    }

    # Otherwise, this is a standard object method

    my $self = shift;
    my $args;
    if (ref $_[0]) {
        $args = shift;
    }
    else {
        my %args = @_;
        $args = \%args;
    }

    my $body = $args->{body};

    # Work out who we're going to send the message to
    my $who = $args->{channel} eq "msg"
        ? $args->{who}
        : $args->{channel};

    # post an event that will send the message
    # if there's a better way of sending actions i'd love to know - jw
    # me too; i'll look at it in v0.5 - sb

    $poe_kernel->post(
        $self->{IRCNAME},
        'ctcp',
        $self->charset_encode($who, "ACTION $body"),
    );
    return;
}

sub notice {
    if (!ref $_[0]) {
        print $_[0], "\n";
        return 1;
    }

    my $self = shift;
    my $args;
    if (ref $_[0]) {
        $args = shift;
    }
    else {
        my %args = @_;
        $args = \%args;
    }

    # Don't modify '$args' hashref in-place, or we might
    # make all subsequent calls into notices
    return $self->say(
        %{ $args },
        irc_command => 'notice'
    );

}

sub pocoirc {
    my $self = shift;
    return $self->{IRCOBJ};
}

sub reply {
    my $self = shift;
    my ($mess, $body) = @_;
    my %hash = %$mess;
    $hash{body} = $body;
    return $self->say(%hash);
}

sub channel_data {
    my $self = shift;
    my $channel = shift or return;
    my $irc = $self->{IRCOBJ};
    my $channels = $irc->channels();
    return if !exists $channels->{$channel};

    return {
        map {
            $_ => {
                op    => $irc->is_channel_operator($channel, $_) || 0,
                voice => $irc->has_channel_voice($channel, $_) || 0,
            }
        } $irc->channel_list($channel)
    };
}

sub server {
    my $self = shift;
    $self->{server} = shift if @_;
    return $self->{server} || "irc.perl.org";
}

sub port {
    my $self = shift;
    $self->{port} = shift if @_;
    return $self->{port} || "6667";
}

sub password {
    my $self = shift;
    $self->{password} = shift if @_;
    return $self->{password} || undef;
}

sub ssl {
    my $self = shift;
    $self->{ssl} = shift if @_;
    return $self->{ssl} || 0;
}

sub localaddr {
    my $self = shift;
    $self->{localaddr} = shift if @_;
    return $self->{localaddr} || 0;
}

sub useipv6 {
    my $self = shift;
    $self->{useipv6} = shift if @_;
    return $self->{useipv6} || 0;
}

sub nick {
    my $self = shift;
    $self->{nick} = shift if @_;
    return $self->{nick} if defined $self->{nick};
    return _random_nick();
}

sub _random_nick {
    my @things = ( 'a' .. 'z' );
    return join '', ( map { @things[ rand @things ] } 0 .. 4 ), "bot";
}

sub alt_nicks {
    my $self = shift;
    if (@_) {
        # make sure we copy
        my @args = ( ref $_[0] eq "ARRAY" ) ? @{ $_[0] } : @_;
        $self->{alt_nicks} = \@args;
    }
    return @{ $self->{alt_nicks} || [] };
}

sub username {
    my $self = shift;
    $self->{username} = shift if @_;
    return defined $self->{username} ? $self->{username} : $self->nick;
}

sub name {
    my $self = shift;
    $self->{name} = shift if @_;
    return defined $self->{name} ? $self->{name} : $self->nick . " bot";
}

sub channels {
    my $self = shift;
    if (@_) {
        # make sure we copy
        my @args = ( ref $_[0] eq "ARRAY" ) ? @{ $_[0] } : @_;
        $self->{channels} = \@args;
    }
    return @{ $self->{channels} || [] };
}

sub quit_message {
    my $self = shift;
    $self->{quit_message} = shift if @_;
    return defined $self->{quit_message} ? $self->{quit_message} : "Bye";
}

sub ignore_list {
    my $self = shift;
    if (@_) {
        # make sure we copy
        my @args = ( ref $_[0] eq "ARRAY" ) ? @{ $_[0] } : @_;
        $self->{ignore_list} = \@args;
    }
    return @{ $self->{ignore_list} || [] };
}

sub charset {
    my $self = shift;
    if (@_) {
        $self->{charset} = shift;
    }
    return $self->{charset};
}

sub flood {
    my $self = shift;
    $self->{flood} = shift if @_;
    return $self->{flood};
}

sub no_run {
    my $self = shift;
    $self->{no_run} = shift if @_;
    return $self->{no_run};
}

sub start_state {
    my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
    $kernel->sig('DIE', 'die');
    $self->{session} = $session;

    # Make an alias for our session, to keep it from getting GC'ed.
    $kernel->alias_set($self->{ALIASNAME});
    $kernel->delay('tick', 30);

    $self->{IRCOBJ} = POE::Component::IRC::State->spawn(
        alias => $self->{IRCNAME},
    );
    $self->{IRCOBJ}->plugin_add(
        'Connector',
        POE::Component::IRC::Plugin::Connector->new(),
    );
    $kernel->post($self->{IRCNAME}, 'register', 'all');

    $kernel->post(
	$self->{IRCNAME},
	'connect',
	{
	    Nick      => $self->nick,
	    Server    => $self->server,
	    Port      => $self->port,
	    Password  => $self->password,
	    UseSSL    => $self->ssl,
	    Flood     => $self->flood,
	    LocalAddr => $self->localaddr,
            useipv6   => $self->useipv6,
	    $self->charset_encode(
		Nick     => $self->nick,
		Username => $self->username,
		Ircname  => $self->name,
	    ),
	},
    );

    return;
}

sub die_state {
    my ($kernel, $self, $ex) = @_[KERNEL, OBJECT, ARG1];
    warn $ex->{error_str};
    $self->{IRCOBJ}->yield('shutdown');
    $kernel->sig_handled();
    return;
}

sub irc_001_state {
    my ($self, $kernel) = @_[OBJECT, KERNEL];

    # ignore all messages from ourselves
    $kernel->post(
        $self->{IRCNAME},
        'ignore',
        $self->charset_encode($self->nick),
    );

    # connect to the channel
    for my $channel ($self->channels) {
        $self->log("Trying to connect to '$channel'\n");
        $kernel->post(
            $self->{IRCNAME},
            'join',
            $self->charset_encode($channel),
        );
    }

    $self->schedule_tick(5);
    $self->connected();
    return;
}

sub irc_disconnected_state {
    my ($self, $kernel, $server) = @_[OBJECT, KERNEL, ARG0];
    $self->log("Lost connection to server $server.\n");
    return;
}

sub irc_error_state {
    my ($self, $err, $kernel) = @_[OBJECT, ARG0, KERNEL];
    $self->log("Server error occurred! $err\n");
    return;
}

sub irc_kicked_state {
    my ($self, $kernel, $heap, $session) = @_[OBJECT, KERNEL, HEAP, SESSION];
    my ($nickstring, $channel, $kicked, $reason) = @_[ARG0..$#_];
    my $nick = $self->nick_strip($nickstring);
    $_[OBJECT]->_remove_from_channel( $channel, $kicked );
    $self->kicked(
        {
            channel => $channel,
            who     => $nick,
            kicked  => $kicked,
            reason  => $reason,
        }
    );
    return;
}

sub irc_join_state {
    my ($self, $nick) = @_[OBJECT, ARG0];
    return;
}

sub irc_nick_state {
    my ($self, $nick, $newnick) = @_[OBJECT, ARG0, ARG1];
    $nick = $self->nick_strip($nick);
    $self->nick_change($nick, $newnick);
    return;
}

sub irc_quit_state {
    my ($self, $kernel, $session) = @_[OBJECT, KERNEL, SESSION];
    my ($nick, $message) = @_[ARG0..$#_];

    $nick = $self->nick_strip($nick);
    $self->userquit({ who => $nick, body => $message });
    return;
}

sub irc_said_state {
    irc_received_state( 'said', 'say', @_ );
    return;
}

sub irc_emoted_state {
    irc_received_state( 'emoted', 'emote', @_ );
    return;
}

sub irc_noticed_state {
    irc_received_state( 'noticed', 'emote', @_ );
    return;
}

sub irc_received_state {
    my $received = shift;
    my $respond  = shift;
    my ($self, $nick, $to, $body) = @_[OBJECT, ARG0, ARG1, ARG2];

    ($nick, $to, $body) = $self->charset_decode($nick, $to, $body);

    my $return;
    my $mess = {};

    # pass the raw body through
    $mess->{raw_body} = $body;

    # work out who it was from
    $mess->{who} = $self->nick_strip($nick);
    $mess->{raw_nick} = $nick;

    # right, get the list of places this message was
    # sent to and work out the first one that we're
    # either a memeber of is is our nick.
    # The IRC protocol allows messages to be sent to multiple
    # targets, which is pretty clever. However, noone actually
    # /does/ this, so we can get away with this:

    my $channel = $to->[0];
    if (lc($channel) eq lc($self->nick)) {
        $mess->{channel} = "msg";
        $mess->{address} = "msg";
    }
    else {
        $mess->{channel} = $channel;
    }

    # okay, work out if we're addressed or not

    $mess->{body} = $body;
    if ($mess->{channel} ne "msg") {
        my $own_nick = $self->nick;

        if ($mess->{body} =~ s/^(\Q$own_nick\E)\s*[:,-]?\s*//i) {
          $mess->{address} = $1;
        }

        for my $alt_nick ($self->alt_nicks) {
            last if $mess->{address};
            if ($mess->{body} =~ s/^(\Q$alt_nick\E)\s*[:,-]?\s*//i) {
              $mess->{address} = $1;
            }
        }
    }

    # strip off whitespace before and after the message
    $mess->{body} =~ s/^\s+//;
    $mess->{body} =~ s/\s+$//;

    # check if someone was asking for help
    if ($mess->{address} && $mess->{body} =~ /^help/i) {
        $mess->{body} = $self->help($mess) or return;
        $self->say($mess);
        return;
    }

    # okay, call the said/emoted method
    $return = $self->$received($mess);

    ### what did we get back?

    # nothing? Say nothing then
    return if !defined $return;

    # a string?  Say it how we were addressed then
    if (!ref $return && length $return) {
        $mess->{body} = $return;
        $self->$respond($mess);
        return;
    }
}

sub irc_chanjoin_state {
    my $self = $_[OBJECT];
    my ($channel, $nick) = @_[ ARG1, ARG0 ];
    $nick = $_[OBJECT]->nick_strip($nick);

    if ($self->nick eq $nick) {
      my @channels = $self->channels;
      push @channels, $channel unless grep { $_ eq $channel } @channels;
      $self->channels(\@channels);
    }
    irc_chan_received_state('chanjoin', 'say', @_);
    return;
}

sub irc_chanpart_state {
    my $self = $_[OBJECT];
    my ($channel, $nick) = @_[ ARG1, ARG0 ];
    $nick = $_[OBJECT]->nick_strip($nick);

    if ($self->nick eq $nick) {
      my @channels = $self->channels;
      @channels = grep { $_ ne $channel } @channels;
      $self->channels(\@channels);
    }
    irc_chan_received_state('chanpart', 'say', @_);
    return;
}

sub irc_chan_received_state {
    my $received = shift;
    my $respond  = shift;
    my ($self, $nick, $channel) = @_[OBJECT, ARG0, ARG1];

    my $return;
    my $mess = {};
    $mess->{who} = $self->nick_strip($nick);

    $mess->{channel} = $channel;
    $mess->{body} = $received; #chanjoin or chanpart
    $mess->{address} = "chan";

    # okay, call the chanjoin/chanpart method
    $return = $self->$received($mess);

    ### what did we get back?

    # nothing? Say nothing then
    return if !defined $return;

    # a string?  Say it how we were addressed then
    if (!ref $return) {
        $mess->{body} = $return;
        $self->$respond($mess);
        return;
    }
}


sub fork_close_state {
    my ($self, $wheel_id) = @_[OBJECT, ARG0];
    delete $self->{forks}{$wheel_id};
    return;
}

sub fork_error_state { }

sub tick_state {
    my ($self, $kernel, $heap) = @_[OBJECT, KERNEL, HEAP];
    my $delay = $self->tick();
    $self->schedule_tick($delay) if $delay;
    return;
}

sub names_done_state {
    my ($self, $kernel, $server, $message) = @_[OBJECT, KERNEL, ARG0, ARG1];
    my ($channel) = split /\s/, $message;
    $self->got_names(
        {
            channel => $channel,
            names   => $self->channel_data($channel),
        }
    );
  return;
}

sub topic_raw_state {
    my ($self, $kernel, $server, $raw) = @_[OBJECT, KERNEL, ARG0, ARG1];
    my ($channel, $topic) = split / :/, $raw, 2;
    $self->topic(
        {
            channel => $channel,
            who     => undef,
            topic   => $topic,
        }
    );
    return;
}

sub topic_state {
    my ($self, $kernel, $nickraw, $channel, $topic)
        = @_[OBJECT, KERNEL, ARG0, ARG1, ARG2];
    my $nick = $self->nick_strip($nickraw);
    $self->topic(
        {
            channel => $channel,
            who     => $nick,
            topic   => $topic,
        }
    );
    return;
}

sub shutdown_state {
    my ($kernel, $self) = @_[KERNEL, OBJECT];
    $kernel->delay('tick');
    $kernel->alias_remove($self->{ALIASNAME});
    for my $fork (values %{ $self->{forks} }) {
        $fork->{wheel}->kill();
    }
    return;
}

sub AUTOLOAD {
    my $self = shift;
    our $AUTOLOAD;
    $AUTOLOAD =~ s/.*:://;
    $poe_kernel->post(
        $self->{IRCNAME},
        $AUTOLOAD,
        $self->charset_encode(@_),
    );
    return;
}

# so it won't get AUTOLOADed
sub DESTROY { return }

sub log {
    my $self = shift;
    for (@_) {
      my $log_entry = $_;
      chomp $log_entry;
      print STDERR "$log_entry\n";
    }
    return;
}

sub ignore_nick {
    local $_ = undef;
    my $self = shift;
    my $nick = shift;
    return grep { $nick eq $_ } @{ $self->{ignore_list} };
}

sub nick_strip {
    my $self = shift;
    my $combined = shift || "";
    my ($nick) = $combined =~ m/(.*?)!/;
    return $nick;
}

sub charset_decode {
    my $self = shift;

    my @r;
    for (@_) {
        if (ref($_) eq 'ARRAY') {
            push @r, [ $self->charset_decode(@$_) ];
        }
        elsif (ref($_) eq "HASH") {
            push @r, { $self->charset_decode(%$_) };
        }
        elsif (ref($_)) {
            die "Can't decode object $_\n";
        }
        else {
            push @r, decode_irc($_);
        }
    }
    #warn Dumper({ decoded => \@r });
    return @r;
}

sub charset_encode {
    my $self = shift;

    my @r;
    for (@_) {
        if (ref($_) eq 'ARRAY') {
            push @r, [ $self->charset_encode(@$_) ];
        }
        elsif (ref($_) eq "HASH") {
            push @r, { $self->charset_encode(%$_) };
        }
        elsif (ref($_)) {
            die "Can't encode object $_\n";
        }
        else {
            push @r, encode($self->charset, $_);
        }
    }
    #warn Dumper({ encoded => \@r });
    return @r;
}

1;

=head1 NAME

Bot::BasicBot - simple irc bot baseclass

=head1 SYNOPSIS

  # with all defaults
  my $bot = Bot::BasicBot->new( channels => ["#bottest"] );
  $bot->run();

  # with all known options
  my $bot = Bot::BasicBot->new(

    server => "irc.example.com",
    port   => "6667",
    channels => ["#bottest"],

    nick      => "basicbot",
    alt_nicks => ["bbot", "simplebot"],
    username  => "bot",
    name      => "Yet Another Bot",

    ignore_list => [qw(dipsy dadadodo laotse)],

  );
  $bot->run();


=head1 DESCRIPTION

Basic bot system designed to make it easy to do simple bots, optionally
forking longer processes (like searches) concurrently in the background.

There are several examples of bots using Bot::BasicBot in the examples/
folder in the Bot::BasicBot tarball.

A quick summary, though - You want to define your own package that
subclasses Bot::BasicBot, override various methods (documented below),
then call L<C<new>|/new> and L<C<run>|/run> on it.

=head1 STARTING THE BOT

=head2 C<new>

Creates a new instance of the class. Key/value pairs may be passed
which will have the same effect as calling the method of that name
with the value supplied. Returns a Bot::BasicBot object, that you can
call 'run' on later.

eg:

  my $bot = Bot::BasicBot->new( nick => 'superbot', channels => [ '#superheroes' ] );

=head2 C<run>

Runs the bot.  Hands the control over to the POE core.

=head1 STOPPING THE BOT

To shut down the bot cleanly, use the L<C<shutdown>|/shutdown> method,
which will (through L<C<AUTOLOAD>|/AUTOLOAD>) send an
L<event|POE::Component::IRC/shutdown> of the same name to
POE::Component::IRC, so it takes the same arguments:

 $bot->shutdown( $bot->quit_message() );

=head1 METHODS TO OVERRIDE

In your Bot::BasicBot subclass, you want to override some of the following
methods to define how your bot works. These are all object methods - the
(implicit) first parameter to all of them will be the bot object.

=head2 C<init>

called when the bot is created, as part of new(). Override to provide
your own init. Return a true value for a successful init, or undef if
you failed, in which case new() will die.

=head2 C<said>

This is the main method that you'll want to override in your subclass -
it's the one called by default whenever someone says anything that we
can hear, either in a public channel or to us in private that we
shouldn't ignore.

You'll be passed a hashref that contains the arguments described below. 
Feel free to alter the values of this hash - it won't be used later on.

=over 4

=item who

Who said it (the nick that said it)

=item raw_nick

The raw IRC nick string of the person who said it. Only really useful
if you want more security for some reason.

=item channel

The channel in which they said it.  Has special value "msg" if it was in
a message.  Actually, you can send a message to many channels at once in
the IRC spec, but no-one actually does this so this is just the first
one in the list.

=item body

The body of the message (i.e. the actual text)

=item address

The text that indicates how we were addressed.  Contains the string
"msg" for private messages, otherwise contains the string off the text
that was stripped off the front of the message if we were addressed,
e.g. "Nick: ".  Obviously this can be simply checked for truth if you
just want to know if you were addressed or not.

=back

You should return what you want to say.  This can either be a simple
string (which will be sent back to whoever was talking to you as a
message or in public depending on how they were talking) or a hashref
that contains values that are compatible with say (just changing
the body and returning the structure you were passed works very well.)

Returning undef will cause nothing to be said.

=head2 C<emoted>

This is a secondary method that you may wish to override. It gets called
when someone in channel 'emotes', instead of talking. In its default
configuration, it will simply pass anything emoted on channel through to
the C<said> handler.

C<emoted> receives the same data hash as C<said>.

=head2 C<noticed>

This is like C<said>, except for notices instead of normal messages.

=head2 C<chanjoin>

Called when someone joins a channel. It receives a hashref argument
similar to the one received by said(). The key 'who' is the nick of the
user who joined, while 'channel' is the channel they joined.

This is a do-nothing implementation, override this in your subclass.

=head2 C<chanpart>

Called when someone joins a channel. It receives a hashref argument
similar to the one received by said(). The key 'who' is the nick of the
user who parted, while 'channel' is the channel they parted.

This is a do-nothing implementation, override this in your subclass.

=head2 C<got_names>

Whenever we have been given a definitive list of 'who is in the channel',
this function will be called. It receives a hash reference as an argument.
The key 'channel' will be the channel we have information for, 'names' is a
hashref where the keys are the nicks of the users, and the values are more
hashes, containing the two keys 'op' and 'voice', indicating if the user is
a chanop or voiced respectively.

The reply value is ignored.

Normally, I wouldn't override this method - instead, just use the L<names>
call when you want to know who's in the channel. Override this only if you
want to be able to do something as soon as possible. Also be aware that
the names list can be changed by other events - kicks, joins, etc, and this
method won't be called when that happens.

=head2 C<topic>

Called when the topic of the channel changes. It receives a hashref
argument. The key 'channel' is the channel the topic was set in, and 'who'
is the nick of the user who changed the channel, 'topic' will be the new
topic of the channel.

=head2 C<nick_change>

When a user changes nicks, this will be called. It receives two arguments:
the old nickname and the new nickname.

=head2 C<kicked>

Called when a user is kicked from the channel. It receives a hashref which
will look like this:

  {
    channel => "#channel",
    who => "nick",
    kicked => "kicked",
    reason => "reason",
  }

The reply value is ignored.

=head2 C<tick>

This is an event called every regularly. The function should return the
amount of time until the tick event should next be called. The default
tick is called 5 seconds after the bot starts, and the default
implementation returns '0', which disables the tick. Override this and
return non-zero values to have an ongoing tick event.

Use this function if you want the bot to do something periodically, and
don't want to mess with 'real' POE things.

Call the L<schedule_tick> event to schedule a tick event without waiting
for the next tick.

=head2 C<help>

This is the other method that you should override.  This is the text
that the bot will respond to if someone simply says help to it.  This
should be considered a special case which you should not attempt to
process yourself.  Saying help to a bot should have no side effects
whatsoever apart from returning this text.

=head2 C<connected>

An optional method to override, gets called after we have connected
to the server

=head2 C<userquit>

Receives a hashref which will look like:

    {
      who => "nick that quit",
      body => "quit message",
    }

=head1 BOT METHODS

There are a few methods you can call on the bot object to do things. These
are as follows:

=head2 C<schedule_tick>

Takes an integer as an argument. Causes the L<tick> event to be called
after that many seconds (or 5 seconds if no argument is provided). Note
that if the tick event is due to be called already, this will override it.
You can't schedule multiple future events with this funtction.

=head2 C<forkit>

This method allows you to fork arbitrary background processes. They
will run concurrently with the main bot, returning their output to a
handler routine. You should call C<forkit> in response to specific
events in your C<said> routine, particularly for longer running
processes like searches, which will block the bot from receiving or
sending on channel whilst they take place if you don't fork them.

Inside the subroutine called by forkit, you can send output back to the
channel by printing lines (followd by C<\n>) to STDOUT. This has the same
effect as calling L<C<< Bot::BasicBot->say >>|say>.

C<forkit> takes the following arguments:

=over 4

=item run

A coderef to the routine which you want to run. Bear in mind that the
routine doesn't automatically get the text of the query - you'll need
to pass it in C<arguments> (see below) if you want to use it at all.

Apart from that, your C<run> routine just needs to print its output to
C<STDOUT>, and it will be passed on to your designated handler.

=item handler

Optional. A method name within your current package which we can
return the routine's data to. Defaults to the built-in method
C<say_fork_return> (which simply sends data to channel).

=item callback

Optional. A coderef to execute in place of the handler. If used, the value
of the handler argument is used to name the POE event. This allows using
closures and/or having multiple simultanious calls to forkit with unique
handler for each call.

=item body

Optional. Use this to pass on the body of the incoming message that
triggered you to fork this process. Useful for interactive proceses
such as searches, so that you can act on specific terms in the user's
instructions.

=item who

The nick of who you want any response to reach (optional inside a
channel.)

=item channel

Where you want to say it to them in.  This may be the special channel
"msg" if you want to speak to them directly

=item address

Optional.  Setting this to a true value causes the person to be
addressed (i.e. to have "Nick: " prepended to the front of returned
message text if the response is going to a public forum.

=item arguments

Optional. This should be an anonymous array of values, which will be
passed to your C<run> routine. Bear in mind that this is not
intelligent - it will blindly spew arguments at C<run> in the order
that you specify them, and it is the responsibility of your C<run>
routine to pick them up and make sense of them.

=back

=head2 C<say>

Say something to someone. Takes a list of key/value pairs as arguments.
You should pass the following arguments:

=over 4

=item who

The nick of who you are saying this to (optional inside a channel.)

=item channel

Where you want to say it to them in.  This may be the special channel
"msg" if you want to speak to them directly

=item body

The body of the message.  I.e. what you want to say.

=item address

Optional.  Setting this to a true value causes the person to be
addressed (i.e. to have "Nick: " prepended to the front of the message
text if this message is going to a pulbic forum.

=back

You can also make non-OO calls to C<say>, which will be interpreted as
coming from a process spawned by C<forkit>. The routine will serialise
any data it is sent, and throw it to STDOUT, where L<POE::Wheel::Run> can
pass it on to a handler.

=head2 C<emote>

C<emote> will return data to channel, but emoted (as if you'd said "/me
writes a spiffy new bot" in most clients). It takes the same arguments
as C<say>, listed above.

=head2 C<notice>

C<notice> will send a IRC notice to the channel. This is typically used by
bots to not break the IRC conversations flow. The message will appear as:

    -nick- message here

It takes the same arguments as C<say>, listed above. Example:

    $bot->notice(
        channel => '#bot_basicbot_test',
        body => 'This is a notice'
    );

=head2 C<reply>

Takes two arguments, a hashref containing information about an incoming
message, and a reply message. It will reply in a privmsg if the incoming
one was a privmsg, in channel if not, and with prefixes if the incoming
one was prefixed. Mostly a shortcut method - it's roughly equivalent to

 $mess->{body} = $body;
 $self->say($mess);

=head2 C<pocoirc>

Takes no arguments. Returns the underlying
L<POE::Component::IRC::State|POE::Component::IRC::State> object used by
Bot::BasicBot.

=head2 C<channel_data>

Takes a channel names as a parameter, and returns a hash of hashes. The
keys are the nicknames in the channel, the values are hashes containing
the keys "voice" and "op", indicating whether these users are voiced or
opped in the channel. This method is only here for backwards compatability.
You'll probably get more use out of
L<POE::Component::IRC::State|POE::Component::IRC::State>'s methods (which
this method is merely a wrapper for). You can access the
POE::Component::IRC::State object through Bot::BasicBot's C<pocoirc>
method.

=head1 ATTRIBUTES

Get or set methods.  Changing most of these values when connected
won't cause sideffects.  e.g. changing the server will not
cause a disconnect and a reconnect to another server.

Attributes that accept multiple values always return lists and
either accept an arrayref or a complete list as an argument.

The usual way of calling these is as keys to the hash passed to the
'new' method.

=head2 C<server>

The server we're going to connect to.  Defaults to
"irc.perl.org".

=head2 C<port>

The port we're going to use.  Defaults to "6667"

=head2 C<password>

The server password for the server we're going to connect to.  Defaults to
undef.

=head2 C<ssl>

A boolean to indicate whether or not the server we're going to connect to
is an SSL server.  Defaults to 0.

=head2 C<localaddr>

The local address to use, for multihomed boxes.  Defaults to undef (use whatever
source IP address the system deigns is appropriate).

=head C<useipv6>

A boolean to indicate whether IPv6 should be used.  Defaults to undef (use
IPv4).

=head2 C<nick>

The nick we're going to use.  Defaults to five random letters
and numbers followed by the word "bot"

=head2 C<alt_nicks>

Alternate nicks that this bot will be known by.  These are not nicks
that the bot will try if it's main nick is taken, but rather other
nicks that the bot will recognise if it is addressed in a public
channel as the nick.  This is useful for bots that are replacements
for other bots...e.g, your bot can answer to the name "infobot: "
even though it isn't really.

=head2 C<username>

The username we'll claim to have at our ip/domain.  By default this
will be the same as our nick.

=head2 C<name>

The name that the bot will identify itself as.  Defaults to
"$nick bot" where $nick is the nick that the bot uses.

=head2 C<channels>

The channels we're going to connect to.

=head2 C<quit_message>

The quit message.  Defaults to "Bye".

=head2 C<ignore_list>

The list of irc nicks to ignore B<public> messages from (normally
other bots.)  Useful for stopping bot cascades.

=head2 C<charset>

IRC has no defined character set for putting high-bit chars into channel.
This attribute sets the encoding to be used for outgoing messages. Defaults
to 'utf8'.

=head2 C<flood>

Set to '1' to disable the built-in flood protection of POE::Compoent::IRC

=head2 C<no_run>

Tells Bot::BasicBot to B<not> run the L<POE kernel|POE::Kernel> at the end
of L<C<run>|/run>, in case you want to do that yourself.

=head1 OTHER METHODS

=head2 C<AUTOLOAD>

Bot::BasicBot implements AUTOLOAD for sending arbitrary states to the
underlying L<POE::Component::IRC|POE::Component::IRC> component. So for a
C<$bot> object, sending

    $bot->foo("bar");

is equivalent to

    $poe_kernel->post(BASICBOT_ALIAS, "foo", "bar");

=head2 C<log>

Logs the message. This method merely prints to STDERR - If you want smarter
logging, override this method - it will have simple text strings passed in
@_.

=head2 C<ignore_nick>

Takes a nick name as an argument. Return true if this nick should be
ignored. Ignores anything in the ignore list

=head2 C<nick_strip>

Takes a nick and hostname (of the form "nick!hostname") and
returns just the nick

=head2 C<charset_decode>

Converts a string of bytes from IRC (uses
L<C<decode_irc>|IRC::Utils/decode_irc> from L<IRC::Utils|IRC::Utils>
internally) and returns a Perl string.

It can also takes a list (or arrayref or hashref) of strings, and return
a list of strings

=head2 C<charset_encode>

Converts a list of perl strings into a list of byte sequences, using
the bot's charset. See L<charset_decode>.

=head1 HELP AND SUPPORT

If you have any questions or issues, you can drop by in #poe @
irc.perl.org, where I (Hinrik) am usually around.

=head1 AUTHOR

Tom Insam E<lt>tom@jerakeen.orgE<gt>

This program is free software; you can redistribute it
and/or modify it under the same terms as Perl itself.

=head1 CREDITS

The initial version of Bot::BasicBot was written by Mark Fowler,
and many thanks are due to him.

Nice code for dealing with emotes thanks to Jo Walsh.

Various patches from Tom Insam, including much improved rejoining,
AUTOLOAD stuff, better interactive help, and a few API tidies.

Maintainership for a while was in the hands of Simon Kent
E<lt>simon@hitherto.netE<gt>. Don't know what he did. :-)

I (Tom Insam) recieved patches for tracking joins and parts from Silver,
sat on them for two months, and have finally applied them. Thanks, dude.
He also sent me changes for the tick event API, which made sense.

In November 2010, maintainership moved to Hinrik E<Ouml>rn
SigurE<eth>sson (L<hinrik.sig@gmail.com>).

=head1 SEE ALSO

L<POE>, L<POE::Component::IRC>

Possibly Infobot, at http://www.infobot.org

=cut