evasivedocs
CS2 scriptingLua 5.4.9 · 25 guides · 292 API entries
Examples

HTTP status

Asks a web address for a JSON status every 30 seconds and shows the answer on screen. Point it at your own server, a game server's status page or any public JSON API.

Needs: Allow internet connections.

Lua
-- @name HTTP status
-- @description Polls a JSON endpoint every 30 s. Needs "Allow internet connections".
local URL = "https://example.com/status.json"   -- any public http(s) URL
local text = "waiting"
local next_at = 0

events.on("tick", function()
    if not http or time.now() < next_at then return end   -- http is nil without the permission
    next_at = time.now() + 30
    local id, err = http.get(URL, function(res)          -- the callback runs on a later frame
        if res.error or res.status ~= 200 then
            text = "failed: " .. (res.error or tostring(res.status))
            return
        end
        local data, perr = json.decode(res.body)
        if type(data) ~= "table" then
            text = "bad JSON: " .. tostring(perr)
            return
        end
        text = "status: " .. tostring(data.status)
    end)
    if not id then text = "not sent: " .. err end
end)

events.on("paint", function()
    draw.text(20, 40, http and text or "turn on Allow internet connections", color(255, 255, 255), {shadow = true})
end)

How it works

  • tick runs 64 times a second, but next_at lets a request through only every 30 seconds.
  • http.get returns at once with a request id. The function you pass runs on a later frame, when the answer is in.
  • The callback checks res.error first, then the status code, then whether the body is valid JSON. Only then does it read data.status.
  • If the request could not be sent at all, for example because 4 are already running, http.get gives nil and a reason.

Try this

  • Change URL to your endpoint and read the fields it really has.
  • Show how old the answer is: keep time.now() from the callback and draw the seconds since.