1
0
mirror of https://github.com/ShadowNinja/LuaIRC.git synced 2025-07-20 16:40:26 +02:00

29 Commits

Author SHA1 Message Date
2fd732dc1f Add support for arbritrary status modes via the ISUPPORT PREFIX value 2014-02-26 23:45:29 -05:00
86c7cb3fe9 Allow hooking to any IRC command 2014-02-26 16:42:10 -05:00
1bd7833f18 Add RPL_ISUPPORT parsing 2014-02-26 14:48:10 -05:00
b1cbbf1963 Merge pull request #14 from ShadowNinja/nickgen
Generate a new nickname when it is in use or erroneous and check the...
2013-10-07 20:27:41 -07:00
5ab24e9ad1 Generate a new nickname when it is in use or erroneous and check the
provided nickname for validity
2013-10-07 16:15:27 -04:00
be620c428e Merge pull request #12 from ShadowNinja/master
Track own nick changes
2013-08-22 05:49:26 -07:00
8a2e47a326 Track own nick changes 2013-08-05 18:33:33 -04:00
bc79606de0 Merge pull request #9 from ShadowNinja/master
A few changes...
2013-06-26 19:36:17 -07:00
d443e2eeeb Track user access changing and enable multi-prefix
This also changes the format of user.access.
2013-06-25 22:29:53 -04:00
ac2a9d03fc Send mode options to the OnModeChange hook 2013-06-25 21:55:43 -04:00
9206f01b88 Add OnSend hook 2013-06-25 21:55:43 -04:00
ddb788883e Interpret format codes passed to meta:send() literally if there are no format arguments 2013-06-25 21:55:43 -04:00
1d0480adba Add PreRegister hook
This is useful for CAP commands and SASL.
2013-06-25 21:55:24 -04:00
ad53b2aeb1 Merge pull request #5 from gandro/master
Use server-assigned nickname
2011-11-07 23:09:57 -08:00
c181583f39 Accept server-assigned nickname 2011-11-07 20:15:18 +01:00
e3b566407e Added irc.set module wrapping select() for IRC connections 2011-04-24 08:25:07 +09:00
4c1e2248f8 Ignore empty lines 2011-04-24 08:24:14 +09:00
d1c0b2d271 Fixed bug in setMode where assert was missing 2011-02-11 15:12:48 +09:00
32d9a8b774 Moved handlers into irc.handlers module (also added updated irc.luadoc, forgot that last commit) 2010-07-21 09:52:02 +09:00
07f50242f4 Renamed hooks to conform with other hook names: OnUserModeIs -> OnUserMode, OnChannelmodeIs -> OnChannelMode 2010-07-21 09:45:37 +09:00
c4d7278c4b Merge branch 'master' of git://github.com/jsimmons/LuaIRC 2010-07-21 09:39:50 +09:00
4f12f28684 reworded readme 2010-07-21 09:39:38 +09:00
d6b4872384 According to RFC, NICK should be sent before USER (yes this is a real issue) 2010-07-21 01:13:20 +10:00
ca767c8b42 Cleaning up getline function 2010-07-21 01:12:31 +10:00
d3c6ab849b Fixing wrong method call 2010-07-21 01:11:29 +10:00
1d8509a4f8 Merge remote branch 'jacop/master' 2010-07-20 13:51:18 +10:00
04dbe436f3 Adding OnModeChange hook 2010-07-20 13:35:25 +10:00
98ccd99f4d Fixing On(Channel/User)ModeIs arguments 2010-07-20 13:29:33 +10:00
da7c1c9a20 Fixed typo in readme 2010-07-19 19:52:27 +09:00
7 changed files with 357 additions and 160 deletions

View File

@ -14,9 +14,5 @@ Dependencies
Documentation Documentation
------------- -------------
Documentation can be automatically generated from the doc/irc.luadoc file, pre-generated documentation can be found in the gh-branch. Documentation can be automatically generated by passing irc.luadoc (in doc/) to [LuaDoc](http://luadoc.luaforge.net/), or pre-generated documentation can be found in the 'gh-pages' branch, which can also be browsed [online](http://jakobovrum.github.com/LuaIRC/doc/modules/irc.html).
You can also browse it [online](http://jakobovrum.github.com/LuaIRC/doc/modules/irc.html).
Documentation is generated by [LuaDoc](http://luadoc.luaforge.net/)

View File

@ -1,11 +1,18 @@
local table = table local table = table
local assert = assert
local select = select
module "irc" module "irc"
local meta = _META local meta = _META
function meta:send(fmt, ...) function meta:send(msg, ...)
local bytes, err = self.socket:send(fmt:format(...) .. "\r\n") if select("#", ...) > 0 then
msg = msg:format(...)
end
self:invoke("OnSend", msg)
local bytes, err = self.socket:send(msg .. "\r\n")
if not bytes and err ~= "timeout" and err ~= "wantwrite" then if not bytes and err ~= "timeout" and err ~= "wantwrite" then
self:invoke("OnDisconnect", err, true) self:invoke("OnDisconnect", err, true)

View File

@ -71,9 +71,9 @@ function irc:whois(nick)
function irc:topic(channel) function irc:topic(channel)
--- Send a raw line of IRC to the server. --- Send a raw line of IRC to the server.
-- @param fmt Line to be sent, excluding newline characters. -- @param msg Line to be sent, excluding newline characters.
-- @param ... Format parameters for <code>fmt</code>, with <code>string.format</code> semantics. -- @param ... Format parameters for <code>msg</code>, with <code>string.format</code> semantics. [optional]
function irc:send(fmt, ...) function irc:send(msg, ...)
--- Send a message to a channel or user. --- Send a message to a channel or user.
-- @param target Nick or channel to send to. -- @param target Nick or channel to send to.
@ -125,7 +125,9 @@ function irc:shutdown()
--- List of hooks you can use with irc:hook. The parameter list describes the parameters passed to the callback function. --- List of hooks you can use with irc:hook. The parameter list describes the parameters passed to the callback function.
-- <ul> -- <ul>
-- <li><code>PreRegister(connection)</code>Useful for CAP commands and SASL.</li>
-- <li><code>OnRaw(line) - (any non false/nil return value assumes line handled and will not be further processed)</code></li> -- <li><code>OnRaw(line) - (any non false/nil return value assumes line handled and will not be further processed)</code></li>
-- <li><code>OnSend(line)</code></li>
-- <li><code>OnDisconnect(message, errorOccurred)</code></li> -- <li><code>OnDisconnect(message, errorOccurred)</code></li>
-- <li><code>OnChat(user, channel, message)</code></li> -- <li><code>OnChat(user, channel, message)</code></li>
-- <li><code>OnNotice(user, channel, message)</code></li> -- <li><code>OnNotice(user, channel, message)</code></li>
@ -137,8 +139,10 @@ function irc:shutdown()
-- <li><code>OnTopic(channel, topic)</code></li> -- <li><code>OnTopic(channel, topic)</code></li>
-- <li><code>OnTopicInfo(channel, creator, timeCreated)</code></li> -- <li><code>OnTopicInfo(channel, creator, timeCreated)</code></li>
-- <li><code>OnKick(channel, nick, kicker, reason)</code>* (kicker is a <code>user</code> table)</li> -- <li><code>OnKick(channel, nick, kicker, reason)</code>* (kicker is a <code>user</code> table)</li>
-- <li><code>OnUserModeIs(modes)</code></li> -- <li><code>OnUserMode(modes)</code></li>
-- <li><code>OnChannelModeIs(user, channel, modes)</code></li> -- <li><code>OnChannelMode(user, channel, modes)</code></li>
-- <li><code>OnModeChange(user, target, modes, ...)</code>* ('...' contains mode options such as banmasks)</li>
-- <li><code>DoX(user, ...)</code>'X' is any IRC command or numeric with the first letter capitalized (eg, DoPing and Do001)</li>
-- </ul> -- </ul>
-- * Event also invoked for yourself. -- * Event also invoked for yourself.
-- <20> Channel passed only when user tracking is enabled -- <20> Channel passed only when user tracking is enabled
@ -151,7 +155,7 @@ function irc:shutdown()
-- <li><code>username</code> - User username.</li> -- <li><code>username</code> - User username.</li>
-- <li><code>host</code> - User hostname.</li> -- <li><code>host</code> - User hostname.</li>
-- <li><code>realname</code> - User real name.</li> -- <li><code>realname</code> - User real name.</li>
-- <li><code>access</code> - User access, available in channel-oriented callbacks. Can be '+', '@', and others, depending on the server.</li> -- <li><code>access</code> - User access, available in channel-oriented callbacks. A table containing boolean fields for each access mode that the server supports. Eg: 'o', and 'v'.</li>
-- </ul> -- </ul>
-- Apart from <code>nick</code>, fields may be missing. To fill them in, enable user tracking and use irc:whois. -- Apart from <code>nick</code>, fields may be missing. To fill them in, enable user tracking and use irc:whois.
-- @name User -- @name User

186
handlers.lua Normal file
View File

@ -0,0 +1,186 @@
local pairs = pairs
local error = error
local tonumber = tonumber
local table = table
module "irc"
handlers = {}
handlers["PING"] = function(o, user, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o, user, me)
o.authed = true
o.nick = me
end
handlers["PRIVMSG"] = function(o, user, channel, message)
o:invoke("OnChat", user, channel, message)
end
handlers["NOTICE"] = function(o, user, channel, message)
o:invoke("OnNotice", user, channel, message)
end
handlers["JOIN"] = function(o, user, channel)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
o.channels[channel].users[user.nick] = user
end
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, user, channel, reason)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, user, msg)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, user, newnick)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
if user.nick == o.nick then
o.nick = newnick
end
end
local function needNewNick(o, user, target, badnick)
local newnick = o.nickGenerator(badnick)
o:send("NICK %s", newnick)
end
-- ERR_ERRONEUSNICKNAME (Misspelt but remains for historical reasons)
handlers["432"] = needNewNick
-- ERR_NICKNAMEINUSE
handlers["433"] = needNewNick
-- RPL_ISUPPORT
handlers["005"] = function(o, prefix, nick, ...)
local list = {...}
local listlen = #list
-- Skip last parameter (info)
for i = 1, listlen - 1 do
local item = list[i]
local pos = item:find("=")
if pos then
o.supports[item:sub(1, pos - 1)] = item:sub(pos + 1)
else
o.supports[item] = true
end
end
end
--NAMES list
handlers["353"] = function(o, user, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(o, nick)
users[name] = {access = access}
end
end
end
--end of NAMES
handlers["366"] = function(o, user, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, user, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, user, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, user, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, user, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, user, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, user, reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, user, user, modes)
o:invoke("OnUserMode", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, user, user, channel, modes)
o:invoke("OnChannelMode", channel, modes)
end
handlers["MODE"] = function(o, user, target, modes, ...)
if o.track_users and target ~= o.nick then
local add = true
local optList = {...}
updatePrefixModes(o)
for c in modes:gmatch(".") do
if c == "+" then add = true
elseif c == "-" then add = false
elseif o.modeprefix[c] then
local nick = table.remove(optList, 1)
local access = o.channels[target].users[nick].access
access[o.modeprefix[c]] = add
if c == "o" then access.op = add
elseif c == "v" then access.voice = add
end
end
end
end
o:invoke("OnModeChange", user, target, modes, ...)
end
handlers["ERROR"] = function(o, user, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end

168
init.lua
View File

@ -19,25 +19,29 @@ _META = meta
require "irc.util" require "irc.util"
require "irc.asyncoperations" require "irc.asyncoperations"
require "irc.handlers"
local meta_preconnect = {} local meta_preconnect = {}
function meta_preconnect.__index(o, k) function meta_preconnect.__index(o, k)
local v = rawget(meta_preconnect, k) local v = rawget(meta_preconnect, k)
if not v and meta[k] then if not v and meta[k] then
error("field '"..k.."' is not accessible before connecting", 2) error(("field '%s' is not accessible before connecting"):format(k), 2)
end end
return v return v
end end
function new(user) function new(data)
local o = { local o = {
nick = assert(user.nick, "Field 'nick' is required"); nick = assert(data.nick, "Field 'nick' is required");
username = user.username or "lua"; username = data.username or "lua";
realname = user.realname or "Lua owns"; realname = data.realname or "Lua owns";
nickGenerator = data.nickGenerator or defaultNickGenerator;
hooks = {}; hooks = {};
track_users = true; track_users = true;
supports = {};
} }
assert(checkNick(o.nick), "Erroneous nickname passed to irc.new")
return setmetatable(o, meta_preconnect) return setmetatable(o, meta_preconnect)
end end
@ -116,12 +120,17 @@ function meta_preconnect:connect(_host, _port)
self.socket = s self.socket = s
setmetatable(self, meta) setmetatable(self, meta)
self:send("CAP REQ multi-prefix")
self:invoke("PreRegister", self)
self:send("CAP END")
if password then if password then
self:send("PASS %s", password) self:send("PASS %s", password)
end end
self:send("USER %s 0 * :%s", self.username, self.realname)
self:send("NICK %s", self.nick) self:send("NICK %s", self.nick)
self:send("USER %s 0 * :%s", self.username, self.realname)
self.channels = {} self.channels = {}
@ -149,21 +158,19 @@ end
local function getline(self, errlevel) local function getline(self, errlevel)
local line, err = self.socket:receive("*l") local line, err = self.socket:receive("*l")
if line then if not line and err ~= "timeout" and err ~= "wantread" then
return line
end
if err ~= "timeout" and err ~= "wantread" then
self:invoke("OnDisconnect", err, true) self:invoke("OnDisconnect", err, true)
self:close() self:shutdown()
error(err, errlevel) error(err, errlevel)
end end
return line
end end
function meta:think() function meta:think()
while true do while true do
local line = getline(self, 3) local line = getline(self, 3)
if line then if line and #line > 0 then
if not self:invoke("OnRaw", line) then if not self:invoke("OnRaw", line) then
self:handle(parse(line)) self:handle(parse(line))
end end
@ -173,142 +180,15 @@ function meta:think()
end end
end end
local handlers = {} local handlers = handlers
handlers["PING"] = function(o, prefix, query)
o:send("PONG :%s", query)
end
handlers["001"] = function(o)
o.authed = true
end
handlers["PRIVMSG"] = function(o, prefix, channel, message)
o:invoke("OnChat", parsePrefix(prefix), channel, message)
end
handlers["NOTICE"] = function(o, prefix, channel, message)
o:invoke("OnNotice", parsePrefix(prefix), channel, message)
end
handlers["JOIN"] = function(o, prefix, channel)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = {users = {}}
else
o.channels[channel].users[user.nick] = user
end
end
o:invoke("OnJoin", user, channel)
end
handlers["PART"] = function(o, prefix, channel, reason)
local user = parsePrefix(prefix)
if o.track_users then
if user.nick == o.nick then
o.channels[channel] = nil
else
o.channels[channel].users[user.nick] = nil
end
end
o:invoke("OnPart", user, channel, reason)
end
handlers["QUIT"] = function(o, prefix, msg)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
v.users[user.nick] = nil
end
end
o:invoke("OnQuit", user, msg)
end
handlers["NICK"] = function(o, prefix, newnick)
local user = parsePrefix(prefix)
if o.track_users then
for channel, v in pairs(o.channels) do
local users = v.users
local oldinfo = users[user.nick]
if oldinfo then
users[newnick] = oldinfo
users[user.nick] = nil
o:invoke("NickChange", user, newnick, channel)
end
end
else
o:invoke("NickChange", user, newnick)
end
end
--NAMES list
handlers["353"] = function(o, prefix, me, chanType, channel, names)
if o.track_users then
o.channels[channel] = o.channels[channel] or {users = {}, type = chanType}
local users = o.channels[channel].users
for nick in names:gmatch("(%S+)") do
local access, name = parseNick(nick)
users[name] = {type = access}
end
end
end
--end of NAMES
handlers["366"] = function(o, prefix, me, channel, msg)
if o.track_users then
o:invoke("NameList", channel, msg)
end
end
--no topic
handlers["331"] = function(o, prefix, me, channel)
o:invoke("OnTopic", channel, nil)
end
--new topic
handlers["TOPIC"] = function(o, prefix, channel, topic)
o:invoke("OnTopic", channel, topic)
end
handlers["332"] = function(o, prefix, me, channel, topic)
o:invoke("OnTopic", channel, topic)
end
--topic creation info
handlers["333"] = function(o, prefix, me, channel, nick, time)
o:invoke("OnTopicInfo", channel, nick, tonumber(time))
end
handlers["KICK"] = function(o, prefix, channel, kicked, reason)
o:invoke("OnKick", channel, kicked, parsePrefix(prefix), reason)
end
--RPL_UMODEIS
--To answer a query about a client's own mode, RPL_UMODEIS is sent back
handlers["221"] = function(o, prefix, modes)
o:invoke("OnUserModeIs", modes)
end
--RPL_CHANNELMODEIS
--The result from common irc servers differs from that defined by the rfc
handlers["324"] = function(o, prefix, user, channel, modes)
o:invoke("OnChannelModeIs", user, channel, modes)
end
handlers["ERROR"] = function(o, prefix, message)
o:invoke("OnDisconnect", message, true)
o:shutdown()
error(message, 3)
end
function meta:handle(prefix, cmd, params) function meta:handle(prefix, cmd, params)
local user = parsePrefix(prefix)
local handler = handlers[cmd] local handler = handlers[cmd]
if handler then if handler then
return handler(self, prefix, unpack(params)) handler(self, user, unpack(params))
end end
self:invoke("Do"..capitalize(cmd), user, unpack(params))
end end
local whoisHandlers = { local whoisHandlers = {

56
set.lua Normal file
View File

@ -0,0 +1,56 @@
local select = require "socket".select
local setmetatable = setmetatable
local insert = table.insert
local remove = table.remove
local ipairs = ipairs
local error = error
module "irc.set"
local set = {}
set.__index = set
function new(t)
t.connections = {}
t.sockets = {}
return setmetatable(t, set)
end
function set:add(connection)
local socket = connection.socket
insert(self.sockets, socket)
self.connections[socket] = connection
insert(self.connections, connection)
end
function set:remove(connection)
local socket = connection.socket
self.connections[socket] = nil
for k, s in ipairs(self.sockets) do
if socket == s then
remove(self.sockets, k)
remove(self.connections, k)
break
end
end
end
function set:select()
local read, write, err = select(self.sockets, nil, self.timeout)
if read then
for k, socket in ipairs(read) do
read[k] = self.connections[socket]
end
end
return read, err
end
-- Select - but if it times out, it returns all connections.
function set:poll()
local read, err = self:select()
return err == "timeout" and self.connections or read
end

View File

@ -1,9 +1,12 @@
local setmetatable = setmetatable local setmetatable = setmetatable
local sub = string.sub
local byte = string.byte
local char = string.char local char = string.char
local table = table local table = table
local assert = assert local assert = assert
local tostring = tostring local tostring = tostring
local type = type local type = type
local random = math.random
module "irc" module "irc"
@ -47,18 +50,53 @@ function parse(line)
return prefix, cmd, params return prefix, cmd, params
end end
function parseNick(nick) function parseNick(conn, nick)
return nick:match("^([%+@]?)(.+)$") local access = {}
updatePrefixModes(conn)
local namestart = 1
for i = 1, #nick - 1 do
local c = nick:sub(i, i)
if conn.prefixmode[c] then
access[conn.prefixmode[c]] = true
else
namestart = i
break
end
end
access.op = access.o
access.voice = access.v
local name = nick:sub(namestart)
return access, name
end end
function parsePrefix(prefix) function parsePrefix(prefix)
local user = {} local user = {}
if prefix then if prefix then
user.access, user.nick, user.username, user.host = prefix:match("^([%+@]?)(.+)!(.+)@(.+)$") user.nick, user.username, user.host = prefix:match("^(.+)!(.+)@(.+)$")
end end
return user return user
end end
function updatePrefixModes(conn)
if conn.prefixmode and conn.modeprefix then
return
end
conn.prefixmode = {}
conn.modeprefix = {}
if conn.supports.PREFIX then
local modes, prefixes = conn.supports.PREFIX:match("%(([^%)]*)%)(.*)")
for i = 1, #modes do
conn.prefixmode[prefixes:sub(i, i)] = modes:sub(i, i)
conn.modeprefix[ modes:sub(i, i)] = prefixes:sub(i, i)
end
else
conn.prefixmode['@'] = 'o'
conn.prefixmode['+'] = 'v'
conn.modeprefix['o'] = '@'
conn.modeprefix['v'] = '+'
end
end
--mIRC markup scheme (de-facto standard) --mIRC markup scheme (de-facto standard)
color = { color = {
black = 1, black = 1,
@ -94,3 +132,33 @@ local underlineByte = char(31)
function underline(text) function underline(text)
return underlineByte..text..underlineByte return underlineByte..text..underlineByte
end end
function checkNick(nick)
return nick:find("^[a-zA-Z_%-%[|%]%^{|}`][a-zA-Z0-9_%-%[|%]%^{|}`]*$") ~= nil
end
function defaultNickGenerator(nick)
-- LuaBot -> LuaCot -> LuaCou -> ...
-- We change a random charachter rather than appending to the
-- nickname as otherwise the new nick could exceed the ircd's
-- maximum nickname length.
local randindex = random(1, #nick)
local randchar = sub(nick, randindex, randindex)
local b = byte(randchar)
b = b + 1
if b < 65 or b > 125 then
b = 65
end
-- Get the halves before and after the changed character
local first = sub(nick, 1, randindex - 1)
local last = sub(nick, randindex + 1, #nick)
nick = first..char(b)..last -- Insert the new charachter
return nick
end
function capitalize(text)
-- Converts first character to upercase and the rest to lowercase.
-- "PING" -> "Ping" | "hello" -> "Hello" | "123" -> "123"
return text:sub(1, 1):upper()..text:sub(2):lower()
end