mcbot/cmds/xep.lua
changeset 3 508108deee63
child 4 3e3767ada403
equal deleted inserted replaced
2:c7ac7b6a76e0 3:508108deee63
       
     1 
       
     2 require "libs.shcmd"
       
     3 
       
     4 -- The caching idea is borrowed from MattJ's riddim code,
       
     5 -- and the function parse_xeps() as well.
       
     6 
       
     7 local xeplisturl = "curl http://xmpp.org/extensions/xeps.xml"
       
     8 
       
     9 local xeps = {}
       
    10 
       
    11 -- parse_xep() from Matthew Wild (aka MattJ)
       
    12 local function parse_xeps(t)
       
    13 if not t or t == "" then return nil end
       
    14 local currxep = {}
       
    15     for b in string.gmatch(t,"<xep>(.-)</xep>") do
       
    16         for k,v in string.gmatch(b,"<(%w+)>(.-)</%1>") do
       
    17             currxep[k] = v
       
    18         end
       
    19         xeps[currxep.number] = { }
       
    20         for k, v in pairs(currxep) do xeps[currxep.number][k] = v end
       
    21     end
       
    22     return true
       
    23 end
       
    24 
       
    25 local function fetch_xeps ()
       
    26     local now = os.time()
       
    27     if os.difftime(now, xeps_updated_at) < 43200 then return end
       
    28     -- Let's get some fresh data
       
    29     local xepdata = shcmd(xeplisturl)
       
    30     xeps_updated_at = now
       
    31     parse_xeps(xepdata)
       
    32 end
       
    33 
       
    34 -- Logics comes from MattJ's riddim bot
       
    35 local function lookup_xep (xepnum)
       
    36     -- Check that xepnum is a valid number
       
    37     xepnum = tonumber(xepnum)
       
    38     if not xepnum or xepnum <= 0 or xepnum > 9999 then return nil, "What XEP?" end
       
    39     xepnum = tostring(xepnum)
       
    40     -- Download XEP list
       
    41     fetch_xeps()
       
    42     -- Expand to full 4 char number
       
    43     xepnum = string.rep("0", 4-xepnum:len())..xepnum
       
    44     xep = xeps[tostring(xepnum)]
       
    45     if not xep then return nil,"Sorry, XEP-"..xepnum.." not found" end
       
    46     return "XEP-"..xep.number.." is \""..xep.name.."\"\n"..
       
    47            -- xep.type..", "..xep.status..", last updated "..xep.updated.."\n"..
       
    48            "URL: <http://xmpp.org/extensions/xep-"..xep.number..".html>"
       
    49 end
       
    50 
       
    51 mcbot_register_command("xep", lookup_xep)