засунь всё внутрь toggle только важное снаружи ну короче разберёшься
repeat task.wait() until game:IsLoaded()

--------------------------------------------------------------------------------
-- Load Rayfield
--------------------------------------------------------------------------------
local Rayfield = loadstring(game:HttpGet("https://sirius.menu/rayfield"))()

--------------------------------------------------------------------------------
-- Create Main Window
--------------------------------------------------------------------------------
local Window = Rayfield:CreateWindow({
    Name = "Prime Hub JJI",
    LoadingTitle = "Prime Hub",
    LoadingSubtitle = "Loading...",
    Theme = "Default",
    ConfigurationSaving = {
        Enabled = true,
        FolderName = "Prime Hub",
        FileName = "JJI"
    },
    Discord = {
        Enabled = true,
        Invite = "primeh",
        RememberJoins = true
    },
})

--------------------------------------------------------------------------------
-- Main Tab
--------------------------------------------------------------------------------
local MainTab = Window:CreateTab("Main", "activity")

--------------------------------------------------------------------------------
-- Globals
--------------------------------------------------------------------------------
getgenv().AutoFarm = false

local BOSS_SPAWN_NAME  = "BossSpawn"    -- Убедись, что имя совпадает с твоим
local SAFE_PLACE       = Vector3.new(0, 50, 0)
local FLIP_SPAM_DELAY  = 0.1            -- Задержка между нажатиями Flip
local REPLAY_WAIT      = 26             -- Секунд перед нажатием Replay
local CHEST_NAME_MATCH = "chest"        -- Подстрока для идентификации сундуков (без учёта регистра)

-- Флаг для предотвращения повторного нажатия Replay
local hasReplayed = false

--------------------------------------------------------------------------------
-- Safe Platform
--------------------------------------------------------------------------------
local safePlatform = Instance.new("Part")
safePlatform.Name = "SafePlatform"
safePlatform.Anchored = true
safePlatform.Size = Vector3.new(100,1,100)
safePlatform.Position = SAFE_PLACE
safePlatform.Material = Enum.Material.Neon
safePlatform.BrickColor = BrickColor.new("Bright green")
safePlatform.CanCollide = true
safePlatform.Parent = workspace

--------------------------------------------------------------------------------
-- Press GUI Button with VirtualInputManager
--------------------------------------------------------------------------------
local function pressGuiButton(button)
    local vim = game:GetService("VirtualInputManager")
    local gs  = game:GetService("GuiService")

    vim:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game) -- Открыть курсор геймпада
    task.wait(0.15)
    gs.SelectedObject = button
    task.wait(0.15)

    vim:SendKeyEvent(true, Enum.KeyCode.Return, false, game)    -- Нажать Enter
    task.wait(0.1)
    vim:SendKeyEvent(false, Enum.KeyCode.Return, false, game)   -- Отпустить Enter
    task.wait(0.1)

    vim:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game) -- Закрыть курсор геймпада
end

--------------------------------------------------------------------------------
-- Teleport function
--------------------------------------------------------------------------------
local function teleportTo(pos)
    local plr = game:GetService("Players").LocalPlayer
    if not plr or not plr.Character or not plr.Character:FindFirstChild("HumanoidRootPart") then
        print("Teleport Failed: Player or HumanoidRootPart not found.")
        return
    end
    plr.Character.HumanoidRootPart.CFrame = CFrame.new(pos)
    Rayfield:Notify({
        Title = "Teleport",
        Content = "Teleported to "..tostring(pos),
        Duration = 2
    })
    print("Teleported to:", pos)
end

--------------------------------------------------------------------------------
-- Insta Kill Loop
--------------------------------------------------------------------------------
local function instaKillLoop()
    local plr = game:GetService("Players").LocalPlayer
    while getgenv().AutoFarm do
        local char = plr.Character or plr.CharacterAdded:Wait()
        for _, obj in ipairs(workspace:GetDescendants()) do
            if not getgenv().AutoFarm then break end
            if obj:IsA("Humanoid") and obj.Parent ~= char then
                if obj.Health > 0 then
                    obj.Health = 0
                    Rayfield:Notify({
                        Title = "InstaKill",
                        Content = "Killed "..(obj.Parent and obj.Parent.Name or "Unknown"),
                        Duration = 1
                    })
                    print("Killed:", obj.Parent and obj.Parent.Name or "Unknown")
                end
            end
        end
        task.wait(0.5)
    end
end

--------------------------------------------------------------------------------
-- Flip Loop
--------------------------------------------------------------------------------
local function autoFlip()
    local plr = game:GetService("Players").LocalPlayer
    local VirtualInputManager = game:GetService("VirtualInputManager")
    local GuiService = game:GetService("GuiService")

    while getgenv().AutoFarm do
        if plr and plr.PlayerGui:FindFirstChild("Loot") and plr.PlayerGui.Loot.Enabled then
            VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
            print("BackSlash pressed to open GUI cursor.")
            task.wait(0.2)

            local targetElement = plr.PlayerGui.Loot.Frame:FindFirstChild("Flip")
            if targetElement and targetElement:IsA("GuiObject") then
                GuiService.SelectedObject = targetElement
                print("Flip button selected.")

                while plr.PlayerGui.Loot.Enabled and getgenv().AutoFarm do
                    VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.Return, false, game)
                    task.wait(0.1)
                    VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.Return, false, game)
                    print("Flip pressed.")
                    task.wait(0.1) -- Задержка между нажатиями
                end
            else
                Rayfield:Notify({
                    Title = "Flip Not Found",
                    Content = "Couldn't find the 'Flip' GuiButton",
                    Duration = 2
                })
                print("Flip GuiButton not found in Frame.")
            end

            VirtualInputManager:SendKeyEvent(true, Enum.KeyCode.BackSlash, false, game)
            task.wait(0.1)
            VirtualInputManager:SendKeyEvent(false, Enum.KeyCode.BackSlash, false, game)
            print("BackSlash released to close GUI cursor.")
        end
        task.wait(0.1)
    end
end

--------------------------------------------------------------------------------
-- Directly Open Chests via ProximityPrompt
--------------------------------------------------------------------------------
local function openChest(chestModel)
    local prompt = chestModel:FindFirstChildOfClass("ProximityPrompt")
    if not prompt then
        Rayfield:Notify({
            Title = "Chest",
            Content = "No ProximityPrompt found in: "..chestModel.Name,
            Duration = 2
        })
        print("No ProximityPrompt found in:", chestModel.Name)
        return
    end

    local basePart = chestModel:FindFirstChild("HumanoidRootPart") 
        or chestModel:FindFirstChildWhichIsA("BasePart")
    if not basePart then
        Rayfield:Notify({
            Title = "Chest",
            Content = "No BasePart found in: "..chestModel.Name,
            Duration = 2
        })
        print("No BasePart found in:", chestModel.Name)
        return
    end

    -- Teleport above the chest
    teleportTo(basePart.Position + Vector3.new(0,3,0))

    local holdTime = 0.1
    if typeof(prompt.HoldDuration) == "number" and prompt.HoldDuration > 0 then
        holdTime = prompt.HoldDuration + 0.1
    end

    Rayfield:Notify({
        Title = "Chest",
        Content = "Opening: "..chestModel.Name.." (holding "..holdTime.."s)",
        Duration = 2
    })
    print("Opening chest:", chestModel.Name, "for", holdTime, "seconds.")

    prompt:InputHoldBegin()
    task.wait(holdTime)
    prompt:InputHoldEnd()
    print("Chest opened:", chestModel.Name)
end

--------------------------------------------------------------------------------
-- Scans 'workspace.Objects.Drops' for Chests
--------------------------------------------------------------------------------
local function processAllChests()
    local objectsFolder = workspace:FindFirstChild("Objects")
    if not objectsFolder then
        print("Objects folder not found.")
        return
    end
    local dropsFolder = objectsFolder:FindFirstChild("Drops")
    if not dropsFolder or not dropsFolder:IsA("Folder") then
        print("Drops folder not found or not a Folder.")
        return
    end

    for _, item in ipairs(dropsFolder:GetDescendants()) do
        if not getgenv().AutoFarm then break end
        if item:IsA("Model") and item.Name:lower():find(CHEST_NAME_MATCH) then
            openChest(item)
        end
    end
end

--------------------------------------------------------------------------------
-- Globals
--------------------------------------------------------------------------------
getgenv().AutoFarm = false
getgenv().WebhookEnabled = false

--------------------------------------------------------------------------------
-- Independent Chest Loop
--------------------------------------------------------------------------------
-- Эта петля будет запускаться отдельно и открывать сундуки независимо от Replay
--------------------------------------------------------------------------------
local function chestLoop()
    while getgenv().AutoFarm do
        processAllChests()
        task.wait(2) -- Как часто проверять новые сундуки
    end
end

--------------------------------------------------------------------------------
-- Auto Replay Loop (26s Wait, then Replay)
--------------------------------------------------------------------------------
-- Эта петля только ждёт ReadyScreen, ждёт 26 секунд и нажимает Replay
--------------------------------------------------------------------------------
local function autoReplayLoop()
    local plr = game:GetService("Players").LocalPlayer
    local pg = plr:FindFirstChild("PlayerGui")
    if not pg then 
        print("PlayerGui not found.")
        return 
    end

    while getgenv().AutoFarm do
        local rs = pg:FindFirstChild("ReadyScreen")
        if rs and rs:IsA("ScreenGui") and rs.Enabled then
            if not hasReplayed then
                Rayfield:Notify({
                    Title = "Replay Timer",
                    Content = "ReadyScreen detected. Will press Replay in "..REPLAY_WAIT.."s",
                    Duration = 3
                })
                print("ReadyScreen detected. Waiting "..REPLAY_WAIT.." seconds before Replay.")
                task.wait(REPLAY_WAIT)

                if getgenv().AutoFarm and rs.Enabled then
                    local frm = rs:FindFirstChild("Frame")
                    if frm then
                        local replayBtn = frm:FindFirstChild("Replay")
                        if replayBtn and replayBtn:IsA("GuiButton") then
                            Rayfield:Notify({
                                Title = "Replay",
                                Content = "Pressing Replay now...",
                                Duration = 2
                            })
                            pressGuiButton(replayBtn)
                            print("Replay button pressed.")
                            hasReplayed = true -- Устанавливаем флаг после нажатия Replay
                        else
                            Rayfield:Notify({
                                Title = "Replay Error",
                                Content = "Replay button not found or not a GuiButton",
                                Duration = 2
                            })
                            print("Replay GuiButton not found in Frame.")
                        end
                    else
                        print("Frame not found in ReadyScreen.")
                    end
                end
            end
        else
            hasReplayed = false -- Сбрасываем флаг, когда ReadyScreen не активен
        end
        task.wait(1)
    end
end

--------------------------------------------------------------------------------
-- Boss Teleport
--------------------------------------------------------------------------------
local function teleportToBoss()
    local spawns = workspace:FindFirstChild("Objects")
    if spawns and spawns:FindFirstChild("Spawns") then
        local bossSpawn = spawns.Spawns:FindFirstChild(BOSS_SPAWN_NAME)
        if bossSpawn and bossSpawn:IsA("BasePart") then
            teleportTo(bossSpawn.Position + Vector3.new(0,5,0))
        else
            Rayfield:Notify({
                Title = "Boss Error",
                Content = "Boss spawn not found or not a BasePart. Check BOSS_SPAWN_NAME.",
                Duration = 3
            })
            print("Boss spawn not found or not a BasePart.")
        end
    else
        Rayfield:Notify({
            Title = "Boss Error",
            Content = "Objects/Spawns folder not found. Check your structure.",
            Duration = 3
        })
        print("Objects/Spawns folder not found.")
    end
end

--------------------------------------------------------------------------------
-- Main Automation Function
--------------------------------------------------------------------------------
local function mainAutomation()
    Rayfield:Notify({
        Title = "AutoFarm",
        Content = "Starting up all loops...",
        Duration = 2
    })
    print("Starting AutoFarm automation.")

    task.spawn(instaKillLoop)    -- Убивает всё
    task.spawn(autoFlip)         -- Непрерывно нажимает Flip
    task.spawn(autoReplayLoop)   -- Ждёт 26 секунд после завершения, затем нажимает Replay
    task.spawn(chestLoop)        -- Непрерывно сканирует и открывает сундуки

    teleportToBoss()

    while getgenv().AutoFarm do
        -- Дополнительная логика, если нужно
        task.wait(1)
    end
end

--------------------------------------------------------------------------------
-- UI Toggle
--------------------------------------------------------------------------------
MainTab:CreateToggle({
    Name = "AutoFarm",
    CurrentValue = false,
    Flag = "Autofarm",
    Callback = function(state)
        getgenv().AutoFarm = state
        if state then
            Rayfield:Notify({
                Title = "AutoFarm",
                Content = "Enabled",
                Duration = 2
            })
            print("AutoFarm Enabled.")
            task.spawn(mainAutomation)
        else
            Rayfield:Notify({
                Title = "AutoFarm",
                Content = "Disabled",
                Duration = 2
            })
            print("AutoFarm Disabled.")
        end
    end
})