summaryrefslogtreecommitdiff
path: root/rirc.lua
blob: 95445addd9381de4e4f741dd40032a96fa7ccf58 (plain)
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
local irc = {}

function irc.sendmsg(conn, ch, msg)
	local m = msg:gsub("[\r\n]+"," ")
	local l = 512-12-#ch
	m = m:sub(1,l)
	conn:send("PRIVMSG "..ch.." :"..m.."\r\n")
end

function irc.send(sock, args)
	local out = ''
	if args.source then
		out = ':' .. args.source .. ' '
	end
	for i = 1, #args-1 do
		local arg = tostring(args[i])
		out = out .. arg:gsub("[\r\n ]+","") .. ' '
	end
	local last = tostring(args[#args]):gsub("[\r\n]+"," ")
	out = out .. ':' .. last
	sock:write(out..'\r\n')
	return out
end

function irc.parse(line)
	local words = {}
	local idx = 1
	while true do
		local word,nidx = line:match("(%g+)%s*()",idx)
		if not word then
			break
		elseif word:sub(1,1) == ":" and idx ~= 1 then
			-- first word can start with :
			local rest = line:sub(idx+1)
			table.insert(words,rest)
			break
		else
			table.insert(words,word)
			idx = nidx
		end
	end

	local from = nil
	if words[1] and words[1]:sub(1,1) == ":" then
		-- we have a source
		from = table.remove(words,1):sub(2)
	end

	local op = words[1]
	local args = {}
	for i=2,#words do
		args[i-1] = words[i]
	end
	return {source=from,op=op:upper(),args=args}
end

function irc.parse_src(src)
	local s, _, nick, user, host = src:find("^(.*)!(.*)@(.*)$")
	if s then
		return true, nick, user, host
	else
		return false
	end
end

return irc