Skip to content

Instantly share code, notes, and snippets.

@joakimk
Created January 28, 2010 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joakimk/288965 to your computer and use it in GitHub Desktop.
Save joakimk/288965 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
CHANNEL = "#shrug_bots"
SERVER = 'irc.freenode.net'
PORT = 6667
NICK = 'notify'
PASS = ''
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
@@instance = self
end
def self.send_message(s)
@@instance.send "PRIVMSG #{CHANNEL} :#{s}"
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 "PASS #{PASS}" if PASS
send "USER bot bot bot :bot bot"
send "NICK #{@nick}"
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 /376/i
send "JOIN #{@channel}"
else
puts s
end
end
def main_loop
# Just keep on truckin' until we disconnect
while true
ready = select([@irc], nil, nil, nil)
if ready
return if @irc.eof
s = @irc.gets
handle_server_input(s)
end
end
end
end
Thread.new do
irc = IRC.new(SERVER, PORT, NICK, CHANNEL)
while true
irc.connect
begin
irc.main_loop
rescue Interrupt
rescue Exception => detail
puts detail.message()
print detail.backtrace.join("\n")
retry
end
sleep 2
end
end
require 'rubygems'
require 'sinatra'
get '/irc' do
IRC.send_message params["m"]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment