Module:PriceServer: Difference between revisions

From The Blockheads Wiki
No edit summary
No edit summary
Line 2: Line 2:


local function fetchPrices()
local function fetchPrices()
local http = require('requests')
local apiUrl = "http://priceserver.theblockheads.net/get_prices.php"
local apiUrl = "http://priceserver.theblockheads.net/get_prices.php"
local response, code = http.get(apiUrl)
local response, code = http.get(apiUrl)

Revision as of 12:49, 29 October 2024

Documentation for this module may be created at Module:PriceServer/doc

local Prices = {}

local function fetchPrices()
	local apiUrl = "http://priceserver.theblockheads.net/get_prices.php"
	local response, code = http.get(apiUrl)
	
	if code ~= 200 then
		return nil, "Error retrieving prices " .. tostring(code)
	end
	
	-- Parse the response
	local json = require('json')
	return json.decode(response)
end

function Prices.getPrice(id)
    local pricesData, err = fetchPrices()

    if err then
        return err
    end

    if pricesData then
        for _, item in ipairs(pricesData) do
            if item.id == id then
                return string.format("%.2f", tonumber(item.price)) -- Round to two decimal places
            end
        end
    end

    return "Item not found."
end

return Prices