-
Notifications
You must be signed in to change notification settings - Fork 3
/
chatbot.pl
92 lines (70 loc) · 2.2 KB
/
chatbot.pl
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
###### TODO
## add multiple server support
use strict;
use warnings;
use Irssi;
use Irssi::Irc;
use IO::Socket::INET;
use Time::HiRes qw(usleep gettimeofday tv_interval);
use vars qw($VERSION %IRSSI);
$VERSION = '0.01';
%IRSSI = (
authors => "Premysl 'Anydot' Hruby",
contact => "dfenze\@gmail.com",
name => "chatbot",
description => "megahal connector",
);
our $megahal;
sub on_msg {
my ($server, $message, $nick, $hostmask, $channel) = @_;
my $mynick = $server->{nick};
my $isprivate = !defined $channel;
my $dst = $isprivate ? $nick : $channel;
my $request;
return if grep {lc eq lc $nick} split(/ /, Irssi::settings_get_str('bot_megahal_ignore'));
if ($message !~ s/^\s*$mynick[,:]\s*(.*)$/$1/i) {
return
unless Irssi::settings_get_int('bot_megahal_triggerchance');
return
if (int(rand(Irssi::settings_get_int('bot_megahal_triggerchance'))));
# With very small chance, we will reply to the user.
}
# Ensure we do not reply ridiculously quickly:
my $delay = Irssi::settings_get_int('bot_megahal_mindelay');
my $t0 = [gettimeofday()];
my $response = megahal_response($message);
my $dt = tv_interval($t0, [gettimeofday()]) * 1000000;
usleep($delay - $dt)
if $dt < $delay;
$server->send_message($dst, "$nick: $response", 0);
}
sub megahal_response {
my ($data) = @_;
$data =~ s/\s+/ /;
$data =~ s/\s*$/\n/;
megahal_connect() unless defined $megahal;
return ">> Can't connect to megahal, try latter or alert my master"
unless defined $megahal;
$megahal->printflush($data);
my $response = $megahal->getline;
if (! defined $response) {
$megahal = undef;
goto &megahal_response; ## restart
}
chomp($response);
return $response;
}
sub megahal_connect {
my $address = Irssi::settings_get_str('bot_megahal');
$megahal = IO::Socket::INET->new(
PeerAddr => $address,
Type => SOCK_STREAM,
);
}
Irssi::signal_add('message public', 'on_msg');
Irssi::signal_add('message private', 'on_msg');
Irssi::settings_add_str('bot', 'bot_megahal', 'localhost:4566');
Irssi::settings_add_str('bot', 'bot_megahal_ignore', '');
# minimal response time in microseconds
Irssi::settings_add_int('bot', 'bot_megahal_mindelay', 0);
Irssi::settings_add_int('bot', 'bot_megahal_triggerchance', 1000);