-
Notifications
You must be signed in to change notification settings - Fork 0
/
irc.rb
86 lines (78 loc) · 2.41 KB
/
irc.rb
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
#!/usr/local/bin/ruby
require "socket"
# Don't allow use of "tainted" data by potentially dangerous operations
$SAFE=1
# The irc class, which talks to the server and holds the main event loop
class IRC
def initialize(server, port, nick, channel)
@server = server
@port = port
@nick = nick
@channel = channel
end
def send(s)
# Send a message to the irc server and print it to the screen
puts "--> #{s}"
@irc.send "#{s}\n", 0
end
def connect()
# Connect to the IRC server
@irc = TCPSocket.open(@server, @port)
send "USER blah blah blah :blah blah"
send "NICK #{@nick}"
send "JOIN #{@channel}"
end
def evaluate(s)
# Make sure we have a valid expression (for security reasons), and
# evaluate it if we do, otherwise return an error message
if s =~ /^[-+*\/\d\s\eE.()]*$/ then
begin
s.untaint
return eval(s).to_s
rescue Exception => detail
puts detail.message()
end
end
return "Error"
end
def handle_server_input(s)
# This isn't at all efficient, but it shows what we can do with Ruby
# (Dave Thomas calls this construct "a multiway if on steroids")
case s.strip
when /^PING :(.+)$/i
puts "[ Server ping ]"
send "PONG :#{$1}"
when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]PING (.+)[\001]$/i
puts "[ CTCP PING from #{$1}!#{$2}@#{$3} ]"
send "NOTICE #{$1} :\001PING #{$4}\001"
when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s.+\s:[\001]VERSION[\001]$/i
puts "[ CTCP VERSION from #{$1}!#{$2}@#{$3} ]"
send "NOTICE #{$1} :\001VERSION Ruby-irc v0.042\001"
# when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s(.+)\s:EVAL (.+)$/i
# puts "[ EVAL #{$5} from #{$1}!#{$2}@#{$3} ]"
# send "PRIVMSG #{(($4==@nick)?$1:$4)} :#{evaluate($5)}"
when /^:(.+?)!(.+?)@(.+?)\sPRIVMSG\s(.+)\s:(.*)insult(.*)$/i
send "PRIVMSG #{(($4==@nick)?$1:$4)} :#{$insult.generate}"
else
puts s
end
end
def main_loop()
# Just keep on truckin' until we disconnect
while true
ready = select([@irc, $stdin], nil, nil, nil)
next if !ready
for s in ready[0]
if s == $stdin then
return if $stdin.eof
s = $stdin.gets
send s
elsif s == @irc then
return if @irc.eof
s = @irc.gets
handle_server_input(s)
end
end
end
end
end