Skip to content
This repository was archived by the owner on Dec 28, 2018. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 27 additions & 12 deletions lib/shout-bot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,14 @@

require "addressable/uri"
require "socket"
require "openssl"

class ShoutBot
def self.shout(uri, password = nil, &block)
def self.shout(uri, password = nil, ssl = false, &block)
raise ArgumentError unless block_given?

uri = Addressable::URI.parse(uri)
irc = new(uri.host, uri.port, uri.user, uri.password) do |irc|
irc = new(uri.host, uri.port, uri.user, uri.password, ssl) do |irc|
if channel = uri.fragment
irc.join(channel, password, &block)
else
Expand All @@ -47,31 +48,45 @@ def self.shout(uri, password = nil, &block)

attr_accessor :channel

def initialize(server, port, nick, password=nil)
def sendln(cmd)
@socket.write("#{cmd}\r\n")
STDOUT.flush
end

def initialize(server, port, nick, password, ssl)
raise ArgumentError unless block_given?

@socket = TCPSocket.open(server, port || 6667)
@socket.puts "PASSWORD #{password}" if password
@socket.puts "NICK #{nick}"
@socket.puts "USER #{nick} #{nick} #{nick} :#{nick}"
tcp_socket = TCPSocket.new(server, port || 6667)
if ssl
ssl_context = OpenSSL::SSL::SSLContext.new
ssl_context.verify_mode = OpenSSL::SSL::VERIFY_NONE
@socket = OpenSSL::SSL::SSLSocket.new(tcp_socket, ssl_context)
@socket.sync = true
@socket.connect
else
@socket = tcp_socket
end
sendln "PASS #{password}" if password
sendln "NICK #{nick}"
sendln "USER #{nick} 0 * :#{nick}"
sleep 1
yield self
@socket.puts "QUIT"
sendln "QUIT :quit"
@socket.gets until @socket.eof?
end

def join(channel, password = nil)
def join(channel, password)
raise ArgumentError unless block_given?

@channel = "##{channel}"
password = password && " #{password}" || ""
@socket.puts "JOIN #{@channel}#{password}"
sendln "JOIN #{@channel}#{password}"
yield self
@socket.puts "PART #{@channel}"
sendln "PART #{@channel}"
end

def say(message)
return unless @channel
@socket.puts "PRIVMSG #{@channel} :#{message}"
sendln "PRIVMSG #{@channel} :#{message}"
end
end