Hi fellow scripters, I wanted some help with my script as it’s not working; but also not printing out any errors too even with debug print statements added.
This code is for a small little project I’m making, whenever the player types in /code
before anything, and then enters a few lines of code; that code will be executed on the server.
Script in ServerScriptService
:
loadstring("warn('Hello!')")()
local runCodeEvent = game:GetService("ReplicatedStorage").RunCodeEvent
local safeEnvironment = {
print = print,
math = math,
string = string,
table = table,
Instance = Instance,
workspace = workspace,
game = game, -- things like game:GetService i restricted some tho
Vector3 = Vector3,
CFrame = CFrame,
Color3 = Color3,
WaitForChild = function(instance, name)
return instance:WaitForChild(name)
end,
FindFirstChild = function(instance, name)
return instance:FindFirstChild(name)
end,
FindFirstChildOfClass = function(instance, className)
return instance:FindFirstChildOfClass(className)
end,
FindFirstChildWhichIsA = function(instance, className)
return instance:FindFirstChildWhichIsA(className)
end,
Clone = function(instance)
return instance:Clone()
end,
Destroy = function(instance)
return instance:Destroy()
end,
InstanceNew = function(className)
return Instance.new(className)
end
}
-- so that players cant abuse some functions
local forbiddenPatterns = {
"game.Players",
":Kick",
"game:Shutdown",
"require",
"while true do", -- this prevents infinite loops
"for i = 1,", -- blocks potentially harmful loops
"game:GetService(\"Chat\")",
":Chat",
":SetCore",
"Player.Chatted",
":Kick(",
"Player:Kick(",
}
local function containsForbiddenCode(code)
for _, pattern in ipairs(forbiddenPatterns) do
if string.find(code, pattern) then
return true
end
end
return false
end
-- handles the code execution
runCodeEvent.OnServerEvent:Connect(function(player, code)
-- safety check
if containsForbiddenCode(code) then
player:Kick("You tried to run unsafe code.")
return
end
-- tries to run the code
local success, result = pcall(function()
-- compile the code into a function
local func = loadstring(code) -- this is where it tries to run the code, but cant and doesnt give any errors either
if func then
setfenv(func, safeEnvironment)
return func()
else
return "Invalid code."
end
end)
if success then
print("Code ran successfully:", result)
else
print("Error executing code:", result)
end
end)
LocalScript in StarterPlayerScripts
:
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local runCodeEvent = ReplicatedStorage:WaitForChild("RunCodeEvent")
Players.LocalPlayer.Chatted:Connect(function(message)
-- check if the message starts with /code
if message:sub(1, 5) == "/code" then
local code = message:sub(7) -- gets the code after '/code '
-- sendd the code to the server
runCodeEvent:FireServer(code)
end
end)