-
Notifications
You must be signed in to change notification settings - Fork 1
/
juiz
executable file
·344 lines (328 loc) · 12.5 KB
/
juiz
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env lua
-- _ _
-- | |_ _(_)____
-- _ | | | | | |_ /
-- | |_| | |_| | |/ /
-- \___/ \__,_|_/___|
--
-- age: 1 year
-- birth: 27/06/09
--
pcall(function () require("luarocks.require") end)
require("socket")
local tcp,alive,lastsend,sendqueue,configfile = socket.tcp(),true,0,{},"config"
version,url,config,jmodule,loaded,hook,hooks,juiz,util = "Juiz IRC Bot 1.4.0 MINEFIELD","http://github.com/thelinx/Juiz",{},{},{},{},{},{},{}
print(string.format("This is the %s. (%s)", version, url))
for _,v in pairs(arg) do
if v == "--help" then
print([[Command line options:
-c or --config <filename>
Use a different configuration file than ./config
-d or --debug
Activates debugging mode.
-r or --display-raw-data
Activates printing of raw irc data received.
-D or --dont-connect
Loads modules then stops.]])
os.exit()
end
if v == "--debug" or v == "-d" then
DEBUG = true
print("Debug mode activated.")
end
if v == "--display-raw-data" or v == "-r" then
DISPLAYRAWDATA = true
print("Will print raw data received.")
end
if v == "--dont-connect" or v == "-D" then
DONTCONNECT = true
print("Not gonna connect.")
end
if prevv == "--config" or prevv == "-c" then
configfile = v
CUSTOMCONFIG = v
print(string.format("Setting configfile as %s.", configfile))
end
prevv = v
end
--- Print info to the console.
-- Useful for debugging, use DEBUG for info that you only need while
-- debugging, ERROR for fatal errors and NOTIFY for stuff that may
-- be useful to the user.
-- @param mtype The verbosity level.
-- @param mtext The string to print.
-- @param ... Extra parameters to be applied to mtext with a string.format.
function util.msg(mtype, mtext, ...)
local _,text = pcall(function(t, ...) return string.format(t, ...) end, mtext, ...)
text = text or mtext
local out = text
if mtype == "INSTALL" then
out = string.format("Loaded %s", text)
elseif mtype == "ERROR" then
out = string.format("ERROR: %s", text)
elseif DEBUG and (mtype == "TRACE" or mtype == "DEBUG") then
out = string.format("%s: %s", mtype, text)
elseif DISPLAYRAWDATA and mtype == "RAW" then
out = string.format("%s", text)
end
if out ~= "" then
print(out)
end
end
local function send(stext)
local sbytes, serror = tcp:send(stext)
if sbytes ~= stext:len() then
return false, serror or "unknown error"
end
lastsend = os.time()
return true
end
--- Send raw IRC data.
-- Use this function to send any raw IRC data to the server.
-- Note that you should not include \r\n at the end, it is
-- applied automatically.
-- @param stext The data to send.
function juiz.send(stext)
util.msg("RAW", "<-- %s", stext)
if os.time() - lastsend > 0.1 then
send(stext.."\r\n")
else
table.insert(sendqueue, stext.."\r\n")
end
end
--- Send a message.
-- This function makes Juiz talk, either via private messaging
-- or to an entire channel.
-- @param srecp The recipient of the message.
-- @param stext The message.
-- @param ... Extra parameters to be applied to stext with a string.format.
function juiz.say(srecp, stext, ...)
juiz.send(string.format("PRIVMSG %s :%s", srecp, string.format(stext, ...)))
end
--- Hooks a function to an event.
-- Allows functions to be triggered on events like messages,
-- channel joins, et.c.
-- @param trigger The event to hook to.
-- @param func The function that should be triggered on the event.
-- @param identifier (Optional) Prevents hook duplication.
function juiz.addhook(trigger, func, identifier)
util.msg("TRACE", "Hooking %s to trigger %s with identifier %s", tostring(func), trigger, identifier or "nil")
hooks[identifier or #hooks + 1] = {trigger, func}
return true
end
--- Call all functions hooked to an event.
-- Use this function in your module to allow other modules to use that data.
-- @param trigger The event to call.
-- @param ... Any other arguments will be forwarded to the hooked functions.
function juiz.callhook(trigger, ...)
for _,v in pairs(hooks) do
if v[1] == trigger then
local co = coroutine.create(function(a, b, c, d, e, f, g) return pcall(v[2], a or nil, b or nil, c or nil, d or nil, e or nil, f or nil, g or nil) end)
local _,cret,cerr = coroutine.resume(co, ...)
util.msg("TRACE", "hook to '%s' returned %s, err = %s", trigger, tostring(cret), tostring(cerr) or "nil")
end
end
end
local function connect()
tcp:settimeout(1,"t")
tcp:settimeout(1,"b")
-- Connect to the server
local cstatus,cerror = tcp:connect(config.server, config.port)
if not cstatus then
-- Something went wrong!
util.msg("ERROR", "Connection to %s:%d failed: %s", config.server, config.port, cerror)
error()
return false
end
util.msg("NOTIFY", "Connected.")
local sstatus, serror = send(string.format("NICK %s\r\nUSER %s %s %s :%s\r\n", config.nick, os.getenv("USER"), io.popen("hostname"):read("*line"), config.server, version))
if not sstatus then
util.msg("ERROR", "Sending login failed: %s", serror)
error()
end
util.msg("TRACE", "Sent login.")
return true
end
local function processdata(pdata)
util.msg("RAW", "--> %s", pdata)
local origin, command, recp, param = string.match(pdata, "^:(%S+) (%S+) (%S+)[^:]*:(.+)")
if not origin then origin, command, param = string.match(pdata, "^:(%S+) (%S+)[^:]*:(.+)") end
if not origin then origin, command, param = string.match(pdata, "^:(%S+) (%S+) (%S+)(.*)") end
if not origin then command, param = string.match(pdata, "^:([^:]+ ):(.+)") end
if not command then command, param = string.match(pdata, "^(%S+) :(%S+)") end
if not command then
util.msg("TRACE", "Unparsed: " .. pdata)
return true
end
if origin ~= nil then onick,ohost = origin:match("^(%S+)!(%S+)") end
if command:lower() == "ping" then
juiz.send(string.format("PONG %s", param))
util.msg("TRACE", "Ping requested from server")
elseif command:lower() == "privmsg" then
if not param then return end
if recp:lower() == config.nick:lower() and onick:lower() ~= config.nick:lower() then
if param:match("[^%w]?VERSION[^%w]?") then
juiz.say(onick, version)
util.msg("TRACE", "Version requested from %s", onick)
return true
elseif param:match("[^%w]?PING[^%w]?") then
juiz.send(string.format("PONG %s", ohost))
util.msg("TRACE", "Ping requested from %s", onick)
return true
end
end
if param:find(string.char(001).."ACTION") then
param = "/me "..param:gsub(string.char(001), ""):gsub("ACTION ", "")
end
juiz.callhook("message", onick, recp, param, ohost)
elseif command:lower() == "join" then
if onick:lower() == config.nick:lower() then
util.msg("NOTIFY", "Joined channel %s.", param)
end
juiz.callhook("join", onick, param, ohost)
elseif command:lower() == "part" then
if onick:lower() == config.nick:lower() then
util.msg("NOTIFY", "Left channel %s.", param)
end
juiz.callhook("part", onick, param, ohost)
end
return true
end
local function queue()
if sendqueue[1] and os.time() - lastsend > 0.1 then
local ret,err = send(table.remove(sendqueue,1))
if not ret then error(err)
elseif sendqueue[1] then return "more" end
end
return "done"
end
--- Splits a string into a table.
-- @param div The divider.
-- @param str The string.
-- @return table The resulting table.
function util.explode(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
--- Tells Juiz that your module has been loaded.
-- Use this so both the user can see that the module has loaded
-- and so other developers can use your functions in their
-- modules without big trouble.
-- @param safename The module name that other modules will refer to your module by.
-- @param humanname The module name that other users will refer to your module by.
-- @param version Just in case another module requires a recent version of your module.
-- @param info A link to your website or something.
function juiz.registermodule(safename, humanname, version, info)
if info == nil then
util.msg("INSTALL", "%s r%d", humanname, version)
else
util.msg("INSTALL", "%s r%d (%s)", humanname, version, info)
end
table.insert(loaded, {safename,version})
end
--- Loads a module -- the safe way.
-- @param filename The filename (without modules/) that should be loaded.
function juiz.loadmodule(filen)
if not filen then return false end
filename = string.format("modules/%s.lua", filen:gsub(".lua", ""))
util.msg("TRACE", "Loading module %s", filen)
local ret,err = pcall(dofile, filename)
if not ret then
util.msg("ERROR", "Could not load module '%s', error: %s", filename:gsub("modules/", ""), err or "nil")
end
return ret
end
--- Checks that all dependencies has been loaded.
-- Note that you have to specify a version. Use 1 if no special
-- version is required. Errors if dependencies are not satisfied.
-- @param dmodules A table (it has to be) with the safenames of the required modules.
-- @param dversions A table (it has to be) with the versions of the required modules.
function juiz.depcheck(dmodules,dversions)
for k,dmodule in pairs(dmodules) do
util.msg("TRACE", "Checking if module %s has been loaded", dmodule)
local dversion,mloaded = dversions[k],false
for _,v in pairs(loaded) do
if v[1] == dmodule then
if v[2] < dversion then
mloaded = {"old",v[2]}
else
mloaded = true
end
end
end
if mloaded == true then
util.msg("TRACE", "Module %s r%d has been loaded", dmodule, dversion)
else
util.msg("TRACE", "Module %s r%d has not been loaded", dmodule, dversion)
if type(mloaded) == "table" then
if mloaded[1] == "old" then
util.msg("ERROR", "Module %s is outdated (r%d is installed, r%d is required)", dmodule, mloaded[2], dversion)
error("Dependencies not satisfied.", 2)
return false
end
else
util.msg("TRACE", "Attempting to load module %s r%d...", dmodule, dversion)
if not juiz.loadmodule(dmodule) then
util.msg("ERROR", "Module %s is not available", dmodule)
error("Dependencies not satisfied.", 2)
return false
end
end
end
end
return true
end
-- Let's load the config
local fopn = io.open(configfile, "r")
if not fopn then
local fopn = io.open(configfile, "w")
fopn:write([[config = {}
config.server = "SERVER"
config.port = "PORT"
config.nick = "NICKNAME"
config.pass = "ADMIN PASSWORD"
config.trigger = "TRIGGER"
-- Add additional configuration items after this line, refer to individual module documentation for more information.]])
fopn:close()
util.msg("NOTIFY", "Please edit the configuration file created in %s.", configfile)
alive = false
else
fopn:close()
dofile(configfile)
config.admins = {}
end
-- Load the selected modules
if alive == true and config.modules then
for _,file in pairs(config.modules) do
file = tostring(file)
juiz.loadmodule(file)
end
end
if DONTCONNECT then alive = false end
-- All functions set, time to connect
if alive == true then
if connect() then
juiz.callhook("connected")
else
alive = false
end
end
-- Now that we're alive and well, let's start receiving data
while alive do
local rdata, rerror = tcp:receive("*l")
while queue() ~= "done" do end
if not rdata and rerror and #rerror > 0 and rerror ~= "timeout" then
util.msg("ERROR", "Lost connection to %s:%d: %s", config.server, config.port, rerror)
alive = false
elseif rdata then
processdata(rdata)
end
end
print("Shutting down...")