Internet API

This library wraps functionality of Internet cards. Also see the Internet Component for more low level functionality (such as querying availability of HTTP and TCP functionality).

snippet.lua
local internet = require("internet")  
local handle = internet.open("example.com", 1337)  
local data = handle:read(10)  
handle:write("1234")  
handle:close()  

If you need the HTTP response code, message, and headers, they are retrieved from the internal object, which is stored in the metatable of the returned object.

snippet.lua
-- https://github.com/kikito/inspect.lua/blob/master/inspect.lua
local inspect = require("inspect")
local internet = require("internet")
 
local handle = internet.request("https://www.google.com")
local result = ""
for chunk in handle do result = result..chunk end
-- Print the body of the HTTP response
-- print(result)
 
-- Grab the metatable for the handle. This contains the
-- internal HTTPRequest object.
local mt = getmetatable(handle)
 
-- The response method grabs the information for
-- the HTTP response code, the response message, and the
-- response headers.
local code, message, headers = mt.__index.response()
print("code = "..tostring(code))
print("message = "..tostring(message))
print(inspect(headers))

This is an example of a basic IRC bot that echos back what you say to it, using the sockets in the internet api.

snippet.lua
--this is just a basic split function we'll use to split the messages
function split(data, pat)
	local ret = {}
	for i in string.gmatch(data,pat) do
		table.insert(ret,i)
	end
	return ret
end
--config
local nickname = "myircbot"
local channel = "#mybotchannel"
 
local net = require("internet")
local con = net.open("irc.esper.net",6667) --define server / port here, this will connect to the server
if(con) then
	local line,png,linesplt,msgfrom = ""
	while(true) do
		line = con:read() --read a line from the socket
		print(line)
		linesplt = split(line,"[^:]+")
		if #linesplt >= 2 and string.find(linesplt[2], "No Ident response") ~= nil then
			print("JOIN")
			con:write("USER " .. nickname .. " 0 * :" .. nickname .. "\r\n") --con:write(msg) is used to send messages, con:read() will read a line
			con:write("NICK " .. nickname .. "\r\n") --for IRC, remember to append the \r\n on the end of all messages
			con:write("JOIN :" .. channel .. "\r\n")
		elseif linesplt[1] == "PING" or linesplt[1] == "PING " then
			print("PING")
			png = split(line,"[^:]+")
			con:write("PONG :"..png[#png].."\r\n") --respond to pings so we don't get disconnected
		elseif string.find(linesplt[1], "PRIVMSG #") ~= nil then
			msgfrom = split(linesplt[1],"[^ ]+")
			msgfrom = msgfrom[3]
			con:write("PRIVMSG "..msgfrom.." :"..linesplt[2].."\r\n")
		end
	end
else
	print("Connection failed.")
end

For a more advanced example, check out the IRC Client program available in the latest release of OpenComputers: irc.lua

Contents