Skip to content

Instantly share code, notes, and snippets.

Created March 24, 2015 22:45
Show Gist options
  • Save anonymous/3e713ad53100c80ac51b to your computer and use it in GitHub Desktop.
Save anonymous/3e713ad53100c80ac51b to your computer and use it in GitHub Desktop.
Irc bot
# Very simple irc class for connecting to irc and replying to messages.
#
# https://www.github.com/Virtual-/roobybot
#
# Things to work on:
# Better command handling
# Better logging of commands
# SSL support
# Registration
# Better naming of variables
require "socket"
require "logger"
class Roobybot
def initialize(server, port, nick, channel, password, ssl, trigger)
@server = server
@port = port
@nick = nick
@channel = channel
@password = password
@socket = TCPSocket.open(server, port)
@trigger = trigger
@registered = false # Needs implementing
@log = Logger.new("roobybot.log", 'monthly')
end
def parse_msg(message)
if message.include? "PING :" # Reply to server pings so we don't get dropped
pong
puts "PONG :#{@server}"
end
begin # Begin block so if we get an exception the bot doesn't quit.
hostname, command, channel, *message = message.split # Splitting the messages
message = message.join(" ")
if command == "376"
join_chan(@channel) # Ensures we attempt to join the channel AFTER we fully connect.
elsif command == "PRIVMSG"
on_privmsg(message, hostname)
end
rescue RuntimeError => e
@log.error "#{e}"
end # If there's an exception we log and pass it.
end
def send_msg(channel, message)
@socket.puts "PRIVMSG #{channel}, :#{message}"
@log.debug("Sending #{message} to #{channel}.")
end
def on_privmsg(message, hostname)
arguments = message.split
argument_one = arguments[0]
if argument_one[1] == @trigger # Then we know it's a command
command = argument_one[2..-1].downcase
on_command(arguments, command, hostname)
end
end
def on_command(arguments, command, hostname)
case command
when "quit"
quit
when "hi", "hello"
send_msg(@channel, "Hello!") # Add logging of commands with user, and command issued
when "who"
who(arguments[1])
when "virtual"
send_msg(@channel, "Virtual is the best")
end
end
def who_is(user)
user = hostname.split("!").first
@socket.puts "WHO #{user[0..-1]}"
end
def join_chan(channel)
@socket.puts "JOIN #{channel}"
@log.debug("Joined #{channel}")
end
def quit
@socket.puts "QUIT #{@channel}"
@log.debug("Quitting.")
@socket.close
end
def pong
@socket.puts "PONG #{@server}"
end
def connect
print("addr: ", @socket.addr.join(":"), "\n")
print("peer: ", @socket.peeraddr.join(":"), "\n")
@socket.puts "USER #{@nick} 0 * #{@nick}"
@socket.puts "NICK #{@nick}"
until @socket.eof?
msg = @socket.gets
@log.debug(msg)
puts msg
parse_msg(msg)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment