aboutsummaryrefslogtreecommitdiff
path: root/sciteco-bot.lua
blob: a8ecd792b1248a3052d4f98b0d14888b77f8ecc7 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/local/bin/lua54
-- Logs the IRC channel at https://sciteco.fmsbw.de/irclogs/`date '+sciteco-%Y%m.log'`
-- Monitored by daemon(8) and auto-rotates the logs.
-- It does not require any cronjob.

local socket = require "socket"

local curdate, log

local client = assert(socket.connect("irc.libera.chat", 6667))
client:setoption("keepalive", true)

local nick = "FSB"
local channel = "#sciteco"

client:send("NICK "..nick.."\r\n"..
            "USER "..nick.." B * "..nick.."\r\n")
socket.sleep(2)
client:send("JOIN "..channel.."\r\n")

local function handle_message(line)
	if line:sub(1, 5) == "PING " then
		-- we will be kicked if not responding to PINGs
		client:send("PONG "..line:sub(6).."\r\n")
		return
	end

	if os.date("%Y%m") ~= curdate then
		-- rotate log
		if log then log:close() end
		curdate = os.date("%Y%m")
		log = assert(io.open("/var/www/htdocs/projects/sciteco/irclogs/sciteco-"..curdate..".log", 'a+'))
	end

	local r_user, r_channel, r_msg = line:match("^:([^!]+)![^ ]+ PRIVMSG ([^ ]+) :(.*)")
	if r_channel == channel then
		-- message from user
		log:write(os.date("%d %b %H:%M "), "<", r_user, "> ", r_msg, "\n"):flush()
		return
	end 

	r_user, r_channel = line:match("^:([^!]+)![^ ]+ JOIN (.*)")
	if r_channel == channel then
		-- user has joined
		log:write(os.date("%d %b %H:%M "), "-!- ", r_user, " has joined.\n"):flush()
		return
	end 

	-- TODO: capture the optional message after `:` at the end
	r_user, r_channel = line:match("^:([^!]+)![^ ]+ PART ([^ ]+)")
	if r_channel == channel then
		-- user has left the channel
		log:write(os.date("%d %b %H:%M "), "-!- ", r_user, " has left.\n"):flush()
		return
	end 

	-- TODO: capture the optional message after `:` at the end
	r_user = line:match("^:([^!]+)![^ ]+ QUIT")
	if r_user then
		-- user has quit
		log:write(os.date("%d %b %H:%M "), "-!- ", r_user, " has quit.\n"):flush()
		return
	end 
end

while true do
	local line, err = client:receive('*l')
	if not line then
		io.stderr:write("ERROR: ", err, "\n")
		-- we will be supervised and restarted by daemon(8)
		-- FIXME: Does not reliably work.
		-- Perhaps decrease the keepalive timeout?
		os.exit(1)
	end

	-- print all messages from the server (for debugging)
	-- NOTE: line does not contain any EOL characters
	print(line)
	handle_message(line)
end

client:close()
log:close()