Jump to content

Custom Break Handler?


dubai

Recommended Posts

Hi, i'm currently implementing a custom break handler in my scripts. This can be configured in the scriptGUI. all the logic seems to work apart from getting it to log back in?
Can't see anything relevant in the api documentation or I'm not looking in the right places... Any help would be appreciated!

In particular:

Cannot resolve symbol 'LOGIN'

api.getTabs().open(Tab.LOGIN);

Here's might BreakHandler class:

package extraFeatures;

import org.osbot.rs07.api.ui.Tab;
import org.osbot.rs07.script.MethodProvider;

import java.util.Random;

public class BreakHandler {

    private final MethodProvider api;
    private final int minBotTime;
    private final int maxBotTime;
    private final int minBreakTime;
    private final int maxBreakTime;
    private long nextBreakTime;
    private final Random random;

    public BreakHandler(MethodProvider api, int minBotTime, int maxBotTime, int minBreakTime, int maxBreakTime) {
        this.api = api;
        this.minBotTime = minBotTime;
        this.maxBotTime = maxBotTime;
        this.minBreakTime = minBreakTime;
        this.maxBreakTime = maxBreakTime;
        this.random = new Random();
        scheduleNextBreak();
    }

    private void scheduleNextBreak() {
        long botTime = random.nextInt(maxBotTime - minBotTime + 1) + minBotTime;
        nextBreakTime = System.currentTimeMillis() + botTime * 60000L;
    }

    public boolean shouldTakeBreak() {
        return System.currentTimeMillis() >= nextBreakTime;
    }

    public void takeBreak() throws InterruptedException {
        long breakTime = random.nextInt(maxBreakTime - minBreakTime + 1) + minBreakTime;
        api.log("Taking a break for " + breakTime + " minutes.");
        api.getTabs().open(Tab.LOGOUT);
        MethodProvider.sleep(breakTime * 60000L);
        api.log("Break over, logging back in.");
        api.getTabs().open(Tab.LOGIN);                /// THIS LINE NEEDS TO CHANGE?
        scheduleNextBreak();
    }
}
Edited by dubai
Link to comment
Share on other sites

  • 7 months later...
2 hours ago, CrystalChris said:

Did you solve this dubai?

I did! Here's a snippet from one of my custom break managers if you're interested:
 

Spoiler
package utils;

import org.osbot.rs07.script.RandomEvent;
import org.osbot.rs07.script.RandomSolver;

/**
 * Breaker overrides OSBot’s built‐in random solver for breaks.
 * It is registered as the BREAK_MANAGER event.
 *
 * When activated, it logs that a break is starting, sleeps for the given break duration,
 * then logs that the break is over and returns 0 so that OSBot’s normal login process resumes.
 */
public class Breaker extends RandomSolver {
    // Duration of the break in milliseconds.
    private final long breakDuration;

    /**
     * Constructs a Breaker with the specified break duration.
     *
     * @param breakDuration the break duration in milliseconds.
     */
    public Breaker(long breakDuration) {
        super(RandomEvent.BREAK_MANAGER);
        this.breakDuration = breakDuration;
    }

    @Override
    public boolean shouldActivate() {
        // Always activate when this solver is set.
        return true;
    }

    @Override
    public int onLoop() throws InterruptedException {
        log("Custom Breaker activated: taking a break for " + (breakDuration / 60000) + " minutes.");
        try {
            Thread.sleep(breakDuration);
        } catch (InterruptedException e) {
            log("Breaker was interrupted. Exiting Breaker gracefully.");
            return 0;
        }
        log("Break ended. Exiting custom Breaker.");
        return 0;
    }

}

 

Spoiler
package utils;

import common.Areas;
import gui.tabs.BreaksTab;
import gui.tabs.BreaksTab.BreakCycle;
import gui.MainGUI;
import main.Main;
import org.osbot.rs07.event.RandomExecutor;

import java.util.Timer;
import java.util.TimerTask;

/**
 * BreakManager reads the user-defined break cycle from your Breaks tab and monitors run time.
 * When the configured run time is reached, it first attempts to bring the player to a safe bank area
 * (using the dynamic bank settings from either the MossGiantsTab or BryophytaTab),
 * then overrides OSBot’s random solver with a custom Breaker which sleeps for the configured break duration.
 * Once the Breaker completes, OSBot’s normal login logic resumes.
 */
public class BreakManager {

    private Main script;
    private MainGUI gui;
    private Timer timer;
    private long nextBreakTimeMillis;
    private BreakCycle currentCycle;
    
    /**
     * Constructs a BreakManager.
     *
     * @param script the Main script instance.
     * @param gui    the MainGUI instance.
     */
    public BreakManager(Main script, MainGUI gui) {
        this.script = script;
        this.gui = gui;
    }
    
    /**
     * Starts the break manager. Reads the break cycle from the Breaks tab and schedules a timer task
     * to check every second if it’s time to take a break.
     */
    public void start() {
        BreaksTab breaksTab = gui.getBreaksTab();
        if (breaksTab == null || !breaksTab.isBreaksEnabled()) {
            script.log("BreakManager: Custom breaks not enabled; exiting start.");
            return;
        }
        
        currentCycle = breaksTab.getPrimaryBreakCycle();
        if (currentCycle == null) {
            script.log("BreakManager: No break cycle defined. Custom breaks are disabled.");
            return;
        }
        
        int runTimeMinutes = getRandomBetween(currentCycle.getRunTimeMin(), currentCycle.getRunTimeMax());
        nextBreakTimeMillis = System.currentTimeMillis() + runTimeMinutes * 60 * 1000;
        script.log("BreakManager: Next break scheduled in " + runTimeMinutes + " minutes.");

        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                checkBreakTime();
            }
        }, 1000, 1000);
    }

    
    /**
     * Checks whether it’s time for a break. If so, the method:
     * <ol>
     *     <li>Dynamically determines the bank area and teleport method based on the active mode
     *         (Bryophyta or Moss Giants).</li>
     *     <li>If the player is not already in the bank area, attempts to pick up the cannon (if needed)
     *         and then uses the teleport/walk settings to return to the bank.</li>
     *     <li>Waits until the player is safely in the bank before starting the break.</li>
     *     <li>Overrides OSBot’s random events with the Breaker for the configured break duration.</li>
     *     <li>Clears the override after the break and schedules the next break.</li>
     * </ol>
     */
    private void checkBreakTime() {
        if (System.currentTimeMillis() >= nextBreakTimeMillis) {
            timer.cancel();
            script.log("BreakManager: Run time is over. Initiating break sequence.");

            // === DYNAMIC BANK SETTINGS ===
            String bankAreaName = "";
            String tpMethod = "";
            // Prefer Bryophyta settings if killing Bryophyta; otherwise use Moss Giants settings.
            if (script.killBryophyta && script.getBryophytaTab() != null) {
                bankAreaName = script.getBryophytaTab().getSelectedBankAreaName();
                tpMethod = script.getBryophytaTab().getSelectedTeleportToBank();
            } else if (script.killMossGiants && script.getMossGiantsTab() != null) {
                bankAreaName = script.getMossGiantsTab().getSelectedBankAreaName();
                tpMethod = script.getMossGiantsTab().getSelectedTeleportToBank();
            }
            
            if (bankAreaName == null || bankAreaName.isEmpty()) {
                script.log("BreakManager: No bank area defined in the active tab. Cannot proceed with break.");
            } else {
                // TELEPORT/WALK TO BANK BEFORE BREAK
                if (!script.isInBankArea()) {
                    script.log("BreakManager: Not in bank area (" + bankAreaName + "). Attempting to return to bank before break.");
                    try {
                        script.pickupCannonIfExists();
                    } catch (InterruptedException e) {
                        script.log("BreakManager: Interrupted during cannon pickup: " + e.getMessage());
                    }
                    
                    boolean walkOnly = false;
                    if (script.killBryophyta && script.getBryophytaTab() != null) {
                        walkOnly = script.getBryophytaTab().isWalkOnlyToBank();
                    } else if (script.killMossGiants && script.getMossGiantsTab() != null) {
                        walkOnly = script.getMossGiantsTab().isWalkOnlyToBank();
                    }
                    
                    if (!walkOnly) {
                        boolean teleported = false;
                        try {
                            teleported = script.getTeleportHandler().teleportToBankByMethod(tpMethod);
                        } catch (InterruptedException e) {
                            script.log("BreakManager: Teleportation interrupted: " + e.getMessage());
                        }
                        if (!teleported) {
                            script.log("BreakManager: Teleport failed. Walking to bank...");
                            try {
                                if (!script.getWalker().walkTo(Areas.getBankAreaByName(bankAreaName))) {
                                    script.log("BreakManager: Failed to walk to bank area.");
                                }
                            } catch (InterruptedException e) {
                                script.log("BreakManager: Interrupted while walking to bank: " + e.getMessage());
                            }
                        }
                    } else {
                        try {
                            if (!script.getWalker().walkTo(Areas.getBankAreaByName(bankAreaName))) {
                                script.log("BreakManager: Failed to walk to bank area.");
                            }
                        } catch (InterruptedException e) {
                            script.log("BreakManager: Interrupted while walking to bank: " + e.getMessage());
                        }
                    }
                    
                    int attempts = 0;
                    while (!script.isInBankArea() && attempts < 60) {
                        script.log("BreakManager: Waiting to arrive in bank area. Attempt " + attempts);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            break;
                        }
                        attempts++;
                    }
                }
                // === END BANK RETURN LOGIC ===
                
                // === BREAK SEQUENCE ===
                int breakMinutes = getRandomBetween(currentCycle.getBreakTimeMin(), currentCycle.getBreakTimeMax());
                long breakMillis = breakMinutes * 60 * 1000;
                Breaker breaker = new Breaker(breakMillis);
                
                // Override OSBot’s random events with our custom Breaker.
                if (script.getBot() != null) {
                    breaker.exchangeContext(script.getBot());
                    RandomExecutor randomExecutor = script.getBot().getRandomExecutor();
                    if (randomExecutor != null) {
                        try {
                            randomExecutor.overrideOSBotRandom(breaker);
                            script.log("BreakManager: Overrode OSBot random events with custom Breaker.");
                        } catch (Exception e) {
                            script.log("BreakManager: Exception during overrideOSBotRandom(breaker): " + e.getMessage());
                        }
                    } else {
                        script.log("BreakManager: RandomExecutor is null; cannot override random events.");
                    }
                } else {
                    script.log("BreakManager: Bot instance is null; cannot exchange context.");
                }
                
                try {
                    Thread.sleep(breakMillis + 5000);
                } catch (InterruptedException e) {
                    script.log("BreakManager: Break sleep interrupted: " + e.getMessage());
                }
                
                // Clear the custom override so that normal login events resume.
                if (script.getBot() != null) {
                    RandomExecutor randomExecutor = script.getBot().getRandomExecutor();
                    if (randomExecutor != null) {
                        try {
                            randomExecutor.overrideOSBotRandom(null);
                            script.log("BreakManager: Cleared custom Breaker override; resuming normal login events.");
                        } catch (Exception e) {
                            script.log("BreakManager: Exception while clearing override: " + e.getMessage());
                        }
                    } else {
                        script.log("BreakManager: RandomExecutor is null when trying to clear override.");
                    }
                } else {
                    script.log("BreakManager: Bot instance is null when trying to clear override.");
                }
                
                int nextRunTimeMinutes = getRandomBetween(currentCycle.getRunTimeMin(), currentCycle.getRunTimeMax());
                nextBreakTimeMillis = System.currentTimeMillis() + nextRunTimeMinutes * 60 * 1000;
                script.log("BreakManager: Break complete. Next break scheduled in " + nextRunTimeMinutes + " minutes.");
                
                // Restart the timer task for subsequent breaks.
                timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
                    @Override
                    public void run() {
                        checkBreakTime();
                    }
                }, 1000, 1000);
            }
        }
    }

    /**
     * Returns a random integer between min and max (inclusive).
     */
    private int getRandomBetween(int min, int max) {
        return min + (int)(Math.random() * ((max - min) + 1));
    }
    
    /**
     * Returns the remaining time until the next break (in milliseconds).
     */
    public long getTimeUntilBreak() {
        return nextBreakTimeMillis - System.currentTimeMillis();
    }
    
    /**
     * Stops the break manager.
     */
    public void stop() {
        if (timer != null) {
            timer.cancel();
        }
    }
}

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...