-
Notifications
You must be signed in to change notification settings - Fork 0
/
ircbot.pl
executable file
·116 lines (106 loc) · 3.44 KB
/
ircbot.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/perl -w
# irc.pl
# A simple IRC MPD adapter. Display the current playing song, if somebody writes !song.
# Usage: perl ircbot.pl
use strict;
use warnings;
# We will use a raw socket to connect to the IRC server.
use IO::Socket;
# The server to connect to and our details.
my $server = "server";
my $nick = "mpd_bot";
my $login = "mpd_bot";
my $mpd_host = "server";
my $mpd_port = "6600";
# The channel which the bot will join.
my $channel = "#lan";
# Connect to the IRC server.
my $sock = new IO::Socket::INET(PeerAddr => $server,
PeerPort => 6667,
Proto => 'tcp') or
die "Can't connect\n";
# Log on to the server.
print $sock "NICK $nick\r\n";
print $sock "USER $login 8 * :MPD-Now Playing Bot\r\n";
# Read lines from the server until it tells us we have connected.
while (my $input = <$sock>) {
# Check the numerical responses from the server.
if ($input =~ /004/) {
# We are now logged in.
last;
}
elsif ($input =~ /433/) {
die "Nickname is already in use.";
}
}
# Join the channel.
print $sock "JOIN $channel\r\n";
# Keep reading lines from the server.
while (my $input = <$sock>) {
chop $input;
if ($input =~ /^PING(.*)$/i) {
# We must respond to PINGs to avoid being disconnected.
print $sock "PONG $1\r\n";
}
if ($input =~ /!Song/i) {
current_song();
}
else {
# Print the raw line received by the bot.
print "$input\n";
}
}
sub current_song {
my $song = "";
my $artist = "";
my $album = "";
my $date = "";
my $current = "";
my $state = "";
my $socket = new IO::Socket::INET(PeerAddr => $mpd_host,
PeerPort => $mpd_port,
Proto => "tcp",
timeout => 5);
printf "Could not create socket: $!\n" unless $socket;
if ( not $socket->getline() =~ /^OK MPD*/ ) {
print"Could not connect: $!\n";
} else {
my $ans = "";
print $socket "status\n";
while ( not $ans =~ /^(OK|ACK)/ ) {
$ans = <$socket>;
if ( $ans =~ s/^state: //) {
$state = $ans;
chomp $state;
}
}
if ( $state eq "play") {
my $ans = "";
print $socket "currentsong\n";
while ( not $ans =~ /^(OK|ACK)/ ) {
$ans = <$socket>;
if ( $ans =~ s/^Artist: //) {
$artist = $ans;
chomp $artist;
}
if ( $ans =~ s/^Title: //) {
$song = $ans;
chomp $song;
}
if ( $ans =~ s/^Album: //) {
$album = $ans;
chomp $album;
}
if ( $ans =~ s/^Date: //) {
$date = $ans;
chomp $date;
}
}
$current = "♫ ${song} - ${artist} (${album}, ${date})\r\n";
} else {
$current = "No song is currently playing (State: ${state})\r\n";
}
close($socket);
print $sock "PRIVMSG ${channel} :${current}";
}
}