IRC_Address = "irc.your-irc-server.net"
IRC_Port = 6667
IRC_Nick = "yournick"
IRC_Default_Channel = "#yourchannel"




function GetWords(str)
	local ret = {}
	i = 1
	for v in string.gmatch(str, "[^%s]+") do 
		table.insert(ret, v)		
	end
	return ret
end

function GetLines(str)
	local ret = {}
	i = 1
	for v in string.gmatch(str, "[^\n]+") do 
		table.insert(ret, v)		
	end
	return ret
end

IRC_Client = -1
Packet_Construct = ""

IRC_Client = Client(IRC_Address, IRC_Port)

if IRC_Client == -1 then
	print("Failed to connect.\n")
else
	print("Connected to IRC server.\n")
	Send(IRC_Client, "NICK "..IRC_Nick.."\nUSER "..IRC_Nick.." 0 * :Lua bot\nJOIN :"..IRC_Default_Channel.."\nPRIVMSG "..IRC_Default_Channel..":Hello world from Lua!\n")
end

function IRC_Channel_Chat(Channel, User, Message)
	io.write(string.format("User: \"%s\"\nChannel: \"%s\"\n Message: \"%s\"\n", User, Channel, Message))
	if User == "jnz" and string.match(Message, "%a+") == "!lua" then
		proc, err = loadstring(string.match(Message, "%a+%s(.+)")
		if proc == nil then
			Send(IRC_Client, "PRIVMSG " .. IRC_Default_Channel .. " :" .. err .. "\n")
		else
			proc()
		end
	end
			
end

function IRC_Callback(Packet)
	local tok = GetWords(Packet)
	if tok[1] == "PING" then
		Send(IRC_Client, string.format("PONG %s\n", tok[2]))
		return
	end
	
	if tok[2] == "PRIVMSG" then
		channel = tok[3];
		message = string.match(Packet, "[^%s]+%s*[^%s]+%s*[^%s]+%s*:(.+)")
		user = string.match(tok[1], ":([^:!]+)!")
		IRC_Channel_Chat(channel, user, message)
	end
end

function IRC_Think()
	if IRC_Client > -1 then
		if DataAvaliable(IRC_Client) == 0 then
			if Packet_Construct == nil then
				Packet_Construct = string.char()
			end
			Packet_Construct = Packet_Construct .. Recv(IRC_Client)
		end	
	end
	
	if Packet_Construct ~= nil then
		if string.find(Packet_Construct, "\n") ~= nil then
				IRC_Callback(string.match(Packet_Construct, "[^\n]+"))
				Packet_Construct = string.match(Packet_Construct, "\n(.+)")
		end
	end
end


function OnThink()
	IRC_Think()
end



function OnChat(PlayerID, Type, Message, Target)
	if IRC_Client ~= -1 then
		teamColour = "04"
		if Get_Team(PlayerID) == 1 then
			teamColour = "08"
		end

		if Type == 1 then
			Send(IRC_Client, "PRIVMSG "..IRC_Default_Channel.." :" .. string.char(3) .. teamColour .. Get_Player_Name_By_ID(PlayerID) .. " [Team]: " .. Message .. string.char(3) .. "\n")
		end
		if Type == 0 then
			Send(IRC_Client, "PRIVMSG "..IRC_Default_Channel.." :" .. string.char(3) .. teamColour .. Get_Player_Name_By_ID(PlayerID) .. ": " .. string.char(3) .. Message .. "\n")
		end
	end
	return 1
end