[Standalone] talk with ChatGPT in FiveM chat [SNIPPET]

image (1)

talk with ChatGPT from within FiveM. I will be doing more experiments with this ChatGPT bot within fiveM. but for now, enjoy asking it questions with the prefix !

Preview

Code;
Server-side;

-- Set your OpenAI API Key
local openaiApiKey = "Your-API-KEY-Here"

-- Event handler for chat messages
AddEventHandler('chatMessage', function(source, name, message)
    -- Check if the message starts with !
    if string.sub(message, 1, 1) == "!" then
        -- Remove the "!" character
        local question = string.sub(message, 2)
        
        -- Make the API request
        PerformHttpRequest("https://api.openai.com/v1/engines/davinci-codex/completions", function(errorCode, responseData, resultHeaders)
            -- Check for errors
            if errorCode ~= 200 then
                print("Error: " .. errorCode .. " - " .. responseData)
            else
                -- Parse the response JSON
                local responseJson = json.decode(responseData)
                local answer = responseJson.choices[1].text
                
                -- Format the response message
                local response = "^2" .. question .. "^5[ChatGPT] ^7 " .. answer
                
                -- Output the response in the chat
                TriggerClientEvent('chat:addMessage', -1, { args = { response } })
            end
        end, "POST", json.encode({
            prompt = question .. "\nAnswer:",
            max_tokens = 150,
            n = 1,
            stop = "\n",
            temperature = 0.5
        }), {
            ["Content-Type"] = "application/json",
            ["Authorization"] = "Bearer " .. openaiApiKey
        })
    end
end)

if you make anything from this please don’t paywall it and please credit accordingly.

Code is accessible Yes
Subscription-based No
Lines (approximately) 35
Requirements No
Support No
11 Likes

nicee

2 Likes

put this code inside a server side script (at the bottom) and it will function correctly.

1 Like

Okay thank you it’s working now