Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- IRC Controlled Turtle Scipt
- Lion4ever, 2014
- http://pastebin.com/sPpkBP9v
- Heavyly base on the CC IRC Client from:
- Matti Vapa, 2014
- https://github.com/mattijv/IRCCC/
- http://pastebin.com/gaSL8HZC
- This program is released under the MIT license.
- ]]--
- --Preventing second instance (but not third):
- if isRunning then
- isRunning = false --leaving no traces
- return false
- end
- isRunning = true
- -- look at the source of the qwebirc webchat login page and take the values
- -- for baseUrl and dynamicBaseUrl for use here
- -- examples for espernet and quakenet
- local baseUrl = "http://webchat.esper.net/"
- local dynamicUrl = ""
- --local baseUrl = "http://webchat.quakenet.org/"
- --local dynamicUrl = "dynamic/leibniz/"
- --------------------------------------------------------------------------------
- --------------------------------------------------------------------------------
- -- JSON4Lua: JSON encoding / decoding support for the Lua language.
- -- json Module.
- -- Author: Craig Mason-Jones
- -- Homepage: http://json.luaforge.net/
- -- Version: 0.9.40
- -- This module is released under the MIT License (MIT).
- -- edited for brevity
- local base = _G
- local decode_scanArray
- local decode_scanComment
- local decode_scanConstant
- local decode_scanNumber
- local decode_scanObject
- local decode_scanString
- local decode_scanWhitespace
- local encodeString
- local isArray
- local isEncodable
- local function encode (v)
- -- Handle nil values
- if v==nil then
- return "null"
- end
- local vtype = base.type(v)
- -- Handle strings
- if vtype=='string' then
- return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
- end
- -- Handle booleans
- if vtype=='number' or vtype=='boolean' then
- return base.tostring(v)
- end
- -- Handle tables
- if vtype=='table' then
- local rval = {}
- -- Consider arrays separately
- local bArray, maxCount = isArray(v)
- if bArray then
- for i = 1,maxCount do
- table.insert(rval, encode(v[i]))
- end
- else -- An object, not an array
- for i,j in base.pairs(v) do
- if isEncodable(i) and isEncodable(j) then
- table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
- end
- end
- end
- if bArray then
- return '[' .. table.concat(rval,',') ..']'
- else
- return '{' .. table.concat(rval,',') .. '}'
- end
- end
- -- Handle null values
- if vtype=='function' and v==null then
- return 'null'
- end
- base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
- end
- local function decode(s, startPos)
- startPos = startPos and startPos or 1
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
- local curChar = string.sub(s,startPos,startPos)
- -- Object
- if curChar=='{' then
- return decode_scanObject(s,startPos)
- end
- -- Array
- if curChar=='[' then
- return decode_scanArray(s,startPos)
- end
- -- Number
- if string.find("+-0123456789.e", curChar, 1, true) then
- return decode_scanNumber(s,startPos)
- end
- -- String
- if curChar==[["]] or curChar==[[']] then
- return decode_scanString(s,startPos)
- end
- if string.sub(s,startPos,startPos+1)=='/*' then
- return decode(s, decode_scanComment(s,startPos))
- end
- -- Otherwise, it must be a constant
- return decode_scanConstant(s,startPos)
- end
- local function null()
- return null -- so json.null() will also return null ;-)
- end
- function decode_scanArray(s,startPos)
- local array = {} -- The return value
- local stringLen = string.len(s)
- base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
- startPos = startPos + 1
- -- Infinite loop for array elements
- repeat
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
- local curChar = string.sub(s,startPos,startPos)
- if (curChar==']') then
- return array, startPos+1
- end
- if (curChar==',') then
- startPos = decode_scanWhitespace(s,startPos+1)
- end
- base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
- object, startPos = decode(s,startPos)
- table.insert(array,object)
- until false
- end
- function decode_scanComment(s, startPos)
- base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
- local endPos = string.find(s,'*/',startPos+2)
- base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
- return endPos+2
- end
- function decode_scanConstant(s, startPos)
- local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
- local constNames = {"true","false","null"}
- for i,k in base.pairs(constNames) do
- --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
- if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
- return consts[k], startPos + string.len(k)
- end
- end
- base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
- end
- function decode_scanNumber(s,startPos)
- local endPos = startPos+1
- local stringLen = string.len(s)
- local acceptableChars = "+-0123456789.e"
- while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
- and endPos<=stringLen
- ) do
- endPos = endPos + 1
- end
- local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
- local stringEval = base.loadstring(stringValue)
- base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
- return stringEval(), endPos
- end
- function decode_scanObject(s,startPos)
- local object = {}
- local stringLen = string.len(s)
- local key, value
- base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
- startPos = startPos + 1
- repeat
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
- local curChar = string.sub(s,startPos,startPos)
- if (curChar=='}') then
- return object,startPos+1
- end
- if (curChar==',') then
- startPos = decode_scanWhitespace(s,startPos+1)
- end
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
- -- Scan the key
- key, startPos = decode(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- startPos = decode_scanWhitespace(s,startPos)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
- startPos = decode_scanWhitespace(s,startPos+1)
- base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
- value, startPos = decode(s,startPos)
- object[key]=value
- until false -- infinite loop while key-value pairs are found
- end
- function decode_scanString(s,startPos)
- base.assert(startPos, 'decode_scanString(..) called without start position')
- local startChar = string.sub(s,startPos,startPos)
- base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
- local escaped = false
- local endPos = startPos + 1
- local bEnded = false
- local stringLen = string.len(s)
- repeat
- local curChar = string.sub(s,endPos,endPos)
- -- Character escaping is only used to escape the string delimiters
- if not escaped then
- if curChar==[[\]] then
- escaped = true
- else
- bEnded = curChar==startChar
- end
- else
- -- If we're escaped, we accept the current character come what may
- escaped = false
- end
- endPos = endPos + 1
- base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
- until bEnded
- local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
- local stringEval = base.loadstring(stringValue)
- base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
- return stringEval(), endPos
- end
- function decode_scanWhitespace(s,startPos)
- local whitespace=" \n\r\t"
- local stringLen = string.len(s)
- while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
- startPos = startPos + 1
- end
- return startPos
- end
- function encodeString(s)
- s = string.gsub(s,'\\','\\\\')
- s = string.gsub(s,'"','\\"')
- s = string.gsub(s,'\n','\\n')
- s = string.gsub(s,'\t','\\t')
- return s
- end
- function isArray(t)
- -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
- -- (with the possible exception of 'n')
- local maxIndex = 0
- for k,v in base.pairs(t) do
- if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
- if (not isEncodable(v)) then return false end -- All array elements must be encodable
- maxIndex = math.max(maxIndex,k)
- else
- if (k=='n') then
- if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
- else -- Else of (k=='n')
- if isEncodable(v) then return false end
- end -- End of (k~='n')
- end -- End of k,v not an indexed pair
- end -- End of loop across all pairs
- return true, maxIndex
- end
- function isEncodable(o)
- local t = base.type(o)
- return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
- end
- --------------------------------------------------------------------------------
- --------------------------------------------------------------------------------
- -- ComputerCraft IRC bot code begins here
- --------------------------------------------------------------------------------
- --------------------------------------------------------------------------------
- local exeTime = 120
- local defaultNick = "cc-turtle-bot"..tostring(math.random(1,1000))
- local nick = defaultNick
- local newNick = ""
- local counter = 0 -- used by the qwebirc protocol for something
- local sessionID = "" -- as is this, although a bit more self evident
- local currentChannel = "#cctesting"
- local quitReason = ""
- local split
- local writeResult
- local send
- local runCode = function(code)
- local result = "Everything went fine"
- local exe = function()
- local func,err = loadstring("return "..code)
- local succ
- if not func then
- func,err = loadstring(code)
- end
- if func then
- succ,err = pcall(func)
- end
- result = (succ and "Success: " or "Failed: ")..tostring(err)
- end
- local timeout = function()
- sleep(exeTime)
- result = "Operation timeout of "..tostring(exeTime).." exceeded!"
- end
- parallel.waitForAny(exe,timeout)
- return result
- end
- local post = function(url,data)
- local cacheAvoidance = "abc"..tostring(math.random(0,10000)) -- not sure if this is needed...
- local resp = http.post(baseUrl..dynamicUrl.."e/"..url,"r="..cacheAvoidance.."&t="..tostring(counter)..data)
- counter = counter + 1
- return resp
- end
- -- better responsiveness with asynchronous methods as we usually let the recv couroutine handle the responses
- local request = function(url,data)
- local cacheAvoidance = "abc"..tostring(math.random(0,10000)) -- not sure if this is needed...
- http.request(baseUrl..dynamicUrl.."e/"..url,"r="..cacheAvoidance.."&t="..tostring(counter)..data)
- counter = counter + 1
- end
- -- these special URLs are used by the webchat server for different methods
- send = function(data)
- return request("p","&s="..sessionID.."&c="..textutils.urlEncode(data))
- end
- local recv = function()
- return post("s","&s="..sessionID)
- end
- local connect = function()
- return post("n","&nick="..nick)
- end
- -- some helper functions
- local pong = function(data)
- return send("PONG :"..data)
- end
- local quit = function(_reason)
- local reason = _reason or ""
- return send("QUIT :"..reason)
- end
- -- lua default string methods suck :/
- split = function(str,sep)
- local sep, fields = sep or ":", {}
- local pattern = string.format("([^%s]+)", sep)
- str:gsub(pattern, function(c) fields[#fields+1] = c end)
- return fields
- end
- -- for debug
- writeResult = function(data,line)
- if not (type(data) == "table") then
- return tostring(data)
- end
- for i,j in pairs(data) do
- if type(j) == "table" then
- line = writeResult(j,line.."(").."), "
- else
- line = line..tostring(j)..", "
- end
- end
- return line:sub(1,-3)
- end
- local lastSwitch = 0
- local handleResponse = function(data)
- for i = 1, #data do
- local id = type(data) =="table" and type(data[i]) =="table" and data[i][2] or sessionID
- if id == "PING" then
- pong(data[i][4][1])
- elseif id == "PRIVMSG" then
- local senderDetails = data[i][3]
- local sender = senderDetails:sub(1,senderDetails:find("!")-1)
- local channel = data[i][4][1]:lower()
- local msg = data[i][4][2]
- if msg:sub(1,32) == "change channel of turtle bot to " and lastSwitch ~= os.day() then
- local oldChannel = currentChannel
- currentChannel = msg:sub(33,33) == "#" and msg:sub(33) or "#"..msg:sub(33)
- send("JOIN "..currentChannel)
- send("PART "..oldChannel.." [Changing channel to "..currentChannel.."]")
- end
- if msg == "update this minecraft irc bot" then
- send("QUIT Updating")
- shell.run("pastebin get 4KnCPupW .ircbot2")
- if fs.exists(".ircbot2") then
- if fs.exists(".ircbot") then
- fs.delete(".ircbot")
- end
- fs.move(".ircbot2",".ircbot")
- end
- os.reboot()
- else
- local r = runCode(msg)
- send("PRIVMSG "..currentChannel.." :"..tostring(r or "Operation successful"))
- end
- --print("<"..sender.."> "..msg)
- elseif id == "376" then
- send("JOIN "..currentChannel)
- end
- end
- end
- local receive = function()
- local resp = connect()
- if not resp then print(os.version()) return end
- local _data = resp.readAll()
- local data = decode(_data)
- sessionID = data[2]
- resp = recv()
- while resp do
- _data = resp.readAll()
- if #_data > 0 then
- data = decode(_data)
- handleResponse(data)
- end
- resp = recv()
- end
- quitReason = "Disconnected!"
- end
- term.clear()
- term.setCursorPos(1,1)
- receive()
Advertisement
Add Comment
Please, Sign In to add comment