API

Introduction

You can write your own custom scripts on top of PrimeBot. Most of the time all you’ll really need is basic Java knowledge. The process is really simple:

  1. Import the “primebot.jar” library to your project.
  2. Write your code.
  3. Build an artifact without dependencies.
  4. Place your script into PrimeBot’s local scripts folder.


The library and local scripts folder can be found in the following directory: 
C:/Users/USERNAME/primebot/

Please keep in mind that we’re not going to provide support for your personal scripts or help you maintain them.

Table of Contents

Requirements

Your PrimeBot account must have an active premium bot subscription, or the script building tool license. You must also install Java 17. Basic understanding of OCR and some OpenCV knowledge is recommended.

Tools

You can find our development tools in the program in the “Script Building” tab. Simply run an emulator that is tied to one of your PrimeBot instances and wait until the bot connects to it. Select the emulator in the dropbox and press the “Open Development Tools” button.

The tools should cover most things but if something is missing you can always write your own custom script/tool.

Script Structure

Your project must have a class that extends AbstractScript that class must also have a ScriptManifest annotation. This is the main class of your script. Your script must also have a class that implements Config. The config class is used to process script settings.

				
					@ScriptManifest(
		game = {Game.LAST_SHELTER_SURVIVAL},
		name = "Demo Script",
		version = 0.0,
		timeoutMinutes = 10,
		author = "Author Name",
		description = "Demo script without nodes"
)
public class DemoScript extends AbstractScript {
	private final DemoConfig CONFIG = new DemoConfig();
	public DemoScript(Device device) {
		super(device);
	}
	@Override
	public void onStart() {
		//called before script starts
	}
	@Override
	public void onStop() {
		//called on script stop
	}
	@Override
	public int loop() {
		//main script loop
		return 0;
	}
	@Override
	public Config getConfig() {
		return CONFIG;
	}
}

				
			
				
					public class DemoConfig implements Config {
}
				
			

Config Class

Every script must have a class that implements Config. PrimeBot will automatically convert certain objects and primitives to UI components.

ConfigItem Annotation

The ConfigItem annotation targets field variables, most elements are self explaining and are being used to save and display settings. Except for int[] defaultNumberModel and String[] defaultStringModel, these are being used to initialize the NumberPickPanel and StringPickPanel.

ConfigItem Type Convertation Table

Object or PrimitiveUI ComponentGet selected values
intJSpinnerprimitive int value
booleanJCheckBoxprimitive boolean
ArrayList(String)JComboBox(String)ArrayList#get(0)
NumberPickPanelNumberPickPanelNumberPickPanel#getSelectedValues
StringPickPanelStringPickPanelStringPickPanel#getSelectedValues
StringOrderPickPanelStringOrderPickPanelStringOrderPickPanel#getSelected
StringJLabelHTML string
StringInputFieldJTextFieldStringInputField#getText
StringOrderCheckboxPickPanelStringOrderCheckboxPickPanelStringOrderCheckboxPickPanel#getSelected

API Introduction

Capturing Image

The bot will automatically take a screenshot and cache it on every loop. Most methods will automatically use that cached image when called, usually these methods are overloaded and you can pass another image if you wish. To access the cached image call APIContext#getLastScreenshot(). You can also update the cached image by calling APIContext#updateScreenshotCache(). The image gets updated when you call the dynamic sleep method sleepUntil(Condition, int timeout).

AbstractScript

The AbstractScript extends APIContext<Device> which contains all the methods you’ll need. You will find ways to interact with the emulator, work with images and also method providers that contain specific game related methods. Game specific methods can be initialized separately for easier access. An example of Last Shelter Survival methods is LSSMethodProvider. The game related classes should be pretty self explaining for someone who plays the game.

ScriptNode

If your script has multiple tasks you can use ScriptNode this will change the way the script manager works. Instead of calling AbstractScript#loop it will take a node approach. The bot will go through all the nodes that have been added to the AbstractScript until it has none left that should be executed. Adding nodes can be done by calling AbstractScript#addNode.

When using ScriptNode AbstractScript#loop should return a negative value.

Executor

An Executor can be added to AbstractScript and it will take priority over the main loop until it no longer should be executed or gets removed. PrimeBot provides some pre coded executors that will make your life much easier. For example you won’t have to write all the code to handle speedups on Last Shelter Survival, all you have to do is initialize LSSSpeedupSolver and add the executor to AbstractScript by calling AbstractScript#addExecutor. The executor will have priority over your script and will be executed once it hits a condition that tells it that it’s no longer needed, the control will then return to the script.

Logging

You can access different logging levels by calling Device#log, Device#warn, Device#error, Device#debug.

Limitations

There are some things you should avoid when coding scripts.

  1. Avoid using inner classes and anything that generates inner classes. This includes statements like switch.
  2. Do not initialize configs in your main class constructor. Override the onStart method instead.

Live Script Examples

Mafia City Bot - Account Configuration Script

				
					public class Images {
	public static final String PREFIX = "mc" + File.separator + "config" + File.separator;
	public static final String BUTTON_OPEN_IN_GAME_OPTS = PREFIX + "igopts";
	public static final String BUTTON_OK_CONFIRM_DAY_NIGHT = PREFIX + "ok_day_night";
	public static final String HEADER_DAY_AND_NIGHT_OPTS = PREFIX + "day_night_header";
	public static final String BUTTON_OPEN_DAY_NIGHT_SETTINGS = PREFIX + "btn_day_and_night_settings";
	public static final String CHECKBOX = PREFIX + "checkbox";
	public static final String LABEL_DAY_NIGHT_SETTING = PREFIX + "SETTING_DAY_NIGHT";
}
				
			
				
					@ScriptManifest(
		game = {Game.MAFIA_CITY},
		name = "Account Configuration",
		version = 0.0,
		timeoutMinutes = 15,
		description = "Sets recommended in-game options. <strong>In-game language must be set to English before running the bot</strong>."
)
public class Main extends AbstractScript {
	private ScriptConfig CONFIG = new ScriptConfig();
	private final BRectangle SELECTED_TAB_BOUNDS = new BRectangle(230, 62, 83, 76);
	private final BRectangle RIGHT_MOST_TAB_SCROLL = new BRectangle(494, 90, 31, 32);
	private final BRectangle BUTTON_OK_DAY_NIGHT = new BRectangle(235, 702, 76, 24);
	private final BRectangle BUTTON_RESTART_NOW = new BRectangle(321, 518, 126, 28);
	private final Queue<OptionsTab> TAB_QUEUE = new LinkedList<>();
	private final ArrayList<Setting> CHECKED_SETTINGS_LIST = new ArrayList<>();
	private int attempts = 0, tabOpenAttempts = 0, scrolledTimes = 0;
	private boolean hasSetDayNight;
	private OptionsTab nextTab;
	public Main(Device device) {
		super(device);
	}
	@Override
	public void onStart() {
		final HashSet<OptionsTab> tabs = Arrays.stream(Setting.values()).map(Setting::getTab).collect(Collectors.toCollection(HashSet::new));
		TAB_QUEUE.addAll(tabs);
	}
	@Override
	public void onStop() {
		if (isInGameOptionsOpen()) {
			getKeyboard().pressBack();
			sleepUntil(this::isRestartTipVisible);
		}
		if (isRestartTipVisible()) {
			pressRestart();
		}
		if (CONFIG.cd > 0) {
			putOnCooldown(GameClock.timeIn(Duration.ofHours(CONFIG.cd)));
		}
	}
	@Override
	public int loop() {
		if (nextTab == null) {
			if (TAB_QUEUE.isEmpty()) {
				device.log("Checked all tabs");
				getKeyboard().pressBack();
				if (sleepUntil(this::isRestartTipVisible, 3000)) {
					pressRestart();
				}
				return ExitCodes.COMPLETED;
			}
			nextTab = TAB_QUEUE.poll();
			if (nextTab == null) return 0;
			device.log("Next settings tab " + EnumUtils.toStringFormat(nextTab));
		}
		if (isRestartTipVisible()) {
			pressRestart();
		} else if (isInGameOptionsOpen()) {
			adjustSettings();
		} else if (isSettingsOpen()) {
			return openInGameOptions();
		} else if (mc().getProfile().isOpen()) {
			if (mc().getProfile().openSettings()) {
				return openInGameOptions();
			}
		} else if (isDayNightSettingsOpen()) {
			setDayNight();
		} else if (mc().getViewport().isInTurfOrOnMap()) {
			if (mc().getProfile().open() && mc().getProfile().openSettings()) {
				return openInGameOptions();
			}
		} else if (++attempts < 5) {
			device.log("Unknown interface is open, closing it");
			mc().getViewport().openTurfOrMap(1, 3000);
			return 2000;
		} else {
			device.log("Attempt timeout");
			return ExitCodes.FAILED;
		}
		return 0;
	}
	@Override
	public Config getConfig() {
		return CONFIG;
	}
	private void adjustSettings() {
		final OptionsTab openTab = getTab();
		if (openTab != nextTab) {
			findNextTab();
		} else {
			if (!hasSetDayNight && openTab == OptionsTab.VISUALS) {
				if (openDayAndNightSettings()) {
					setDayNight();
					return;
				}
			}
			final List<Setting> neededSettings = Arrays.stream(Setting.values())
					.filter(setting -> setting.getTab() == nextTab && !CHECKED_SETTINGS_LIST.contains(setting)).
					collect(Collectors.toList());
			final HashMap<BRectangle, Boolean> toggleButtons = getToggleButtons();
			neededSettings.forEach(setting -> {
				final BRectangle label = getOpenCV().getAreaMatch(setting.getTemplate(), 0.7);
				if (label != null) {
					device.log("Found setting " + EnumUtils.toStringFormat(setting) + " making sure it's " + (setting.isMustEnable() ? "enabled" : "disabled"));
					setCheckbox(label, setting.isMustEnable(), toggleButtons);
					CHECKED_SETTINGS_LIST.add(setting);
				}
			});
			if (hasCheckedAllSettingsInTab()) {
				device.log("All required settings have been checked in this tab");
				reset();
				return;
			}
			if (scrolledTimes++ < nextTab.getScrollTimeout()) {
				device.log("Scrolling page down " + scrolledTimes + "/" + nextTab.getScrollTimeout());
				getMouse().drag(DragDirection.SOUTH);
				BPoint dragStart = new BPoint(RNG.nextInt(5, 10), BCanvas.getCenter().getY());
				getMouse().drag(dragStart.getX(), dragStart.getY(), dragStart.getX(), dragStart.getY() + (-300), 25, 100);
				sleep(1000);
			} else {
				device.log("Scroll timeout");
				reset();
			}
		}
	}
	private void setCheckbox(final BRectangle settingsLabel, boolean mustEnable, HashMap<BRectangle, Boolean> toggleButtons) {
		toggleButtons.entrySet().stream()
				.filter(e -> isButtonRelatedToSetting(e.getKey(), settingsLabel))
				.findFirst()
				.ifPresent(e -> {
					if (e.getValue() != mustEnable) {
						device.log("Toggling setting");
						getMouse().click(e.getKey());
						sleep(RNG.nextInt(200, 400));
					}
				});
		sleep(1000);
	}
	private HashMap<BRectangle, Boolean> getToggleButtons() {
		final HashMap<BRectangle, Boolean> map = new HashMap<>();
		getOpenCV().getAreaMatch(Images.CHECKBOX, 0.7, 5).forEach(cb -> {
			if (cb.getX() > 425) {
				map.put(cb, true);
			} else {
				map.put(cb, false);
			}
		});
		return map;
	}
	private boolean isButtonRelatedToSetting(final BRectangle button, final BRectangle settingsLabel) {
		final BRectangle testArea = new BRectangle(0, settingsLabel.getY(), BCanvas.width, settingsLabel.getHeight());
		return testArea.overlaps(button);
	}
	private boolean hasCheckedAllSettingsInTab() {
		if (nextTab == null) {
			device.log("Tab is null - checked all settings in the tab");
			reset();
			return true;
		}
		return Arrays.stream(Setting.values()).filter(setting -> setting.getTab() == nextTab)
				.allMatch(CHECKED_SETTINGS_LIST::contains);
	}
	private void reset() {
		attempts = 0;
		tabOpenAttempts = 0;
		scrolledTimes = 0;
		nextTab = null;
	}
	public void findNextTab() {
		if (nextTab == null) {
			reset();
		}
		if (!device.clickTemplate(nextTab.getTemplate(), 0.7, null, 2000)) {
			if (tabOpenAttempts >= 5) {
				device.log("Tab " + nextTab + " not found");
				reset();
			} else {
				device.log("Scrolling setting tabs");
				getMouse().click(RIGHT_MOST_TAB_SCROLL);
				sleep(1000);
			}
		}
	}
	private boolean isRestartTipVisible() {
		return mc().getTips().isVisible("changes you", "made to the", "will take", "restarting the", "do you want", "restart the", "now?");
	}
	private boolean isDayNightSettingsOpen() {
		return getOpenCV().isTemplateOnScreen(Images.HEADER_DAY_AND_NIGHT_OPTS, 0.7);
	}
	private boolean openDayAndNightSettings() {
		final BRectangle lbl = getOpenCV().getAreaMatch(Images.LABEL_DAY_NIGHT_SETTING, 0.7);
		if (lbl != null) {
			final Optional<BRectangle> btn = getOpenCV().getAreaMatch(Images.BUTTON_OPEN_DAY_NIGHT_SETTINGS, 0.7, 3)
					.stream()
					.filter(b -> isButtonRelatedToSetting(b, lbl))
					.findFirst();
			if (btn.isPresent()) {
				device.log("Opening the day and night settings");
				getMouse().click(btn.get());
				return sleepUntil(this::isDayNightSettingsOpen);
			}
		}
		return false;
	}
	private void setDayNight() {
		device.log("Trying to adjust the day and night settings");
		mc().getSlider().drag(3, false, false);
		clickTemplateOrArea(Images.BUTTON_OK_CONFIRM_DAY_NIGHT, 0.7, BUTTON_OK_DAY_NIGHT,
				"Confirming the day and night time option, pressing ok", this::isInGameOptionsOpen, 5000);
		hasSetDayNight = true;
	}
	private void pressRestart() {
		device.log("Pressing the restart now button");
		getMouse().click(BUTTON_RESTART_NOW);
		sleep(10000);
		updateScreenshotCache();
		if (sleepUntil(() -> mc().getViewport().isInTurfOrOnMap() || mc().getViewport().isPackDealOpen(), 30000)) {
			if (mc().getViewport().isPackDealOpen()) {
				mc().getViewport().openTurfOrMap(1, 3000);
			}
		}
	}
	private int openInGameOptions() {
		if (!device.clickTemplate(Images.BUTTON_OPEN_IN_GAME_OPTS, 0.7, this::isInGameOptionsOpen, 5000) && ++attempts >= 5) {
			device.log("Timeout opening in game opts");
			return ExitCodes.FAILED;
		}
		return 0;
	}
	private boolean isInGameOptionsOpen() {
		return mc().getMenu().isOpen("game", "options");
	}
	private boolean isSettingsOpen() {
		return mc().getMenu().isOpen("settings");
	}
	private OptionsTab getTab() {
		return Arrays.stream(OptionsTab.values())
				.filter(tab -> getOpenCV().isTemplateOnScreen(tab.getTemplate(), 0.7, SELECTED_TAB_BOUNDS::overlaps))
				.findFirst()
				.orElse(null);
	}
}
				
			
				
					@AllArgsConstructor
@Getter
public enum OptionsTab {
	VISUALS(10),
	REMINDERS(2),
	SYSTEM(2),
	SETTINGS(3),
	DISPLAY(2),
	TASK(2),
	INTERFACE(2),
	FX(2);
	private int scrollTimeout;
	public String getTemplate() {
		return Images.PREFIX + this;
	}
}
				
			
				
					public class ScriptConfig implements Config {
	@ConfigItem(
			displayName = "Cooldown - do not return to this task for X hours",
			keyName = "cd",
			tooltip = "The bot won't return to this task for X hours after successfully completing it if the cooldowns are enabled in your bot settings",
			groupName = "Cooldowns",
			isPremium = false
	)
	public int cd = 72;
}
				
			
				
					@AllArgsConstructor
@Getter
public enum Setting {
	DEVELOPMENT_STATUS_REPORT(OptionsTab.SETTINGS, false),
	DAILY_MISSION(OptionsTab.REMINDERS, false),
	RECOMMENDED_TIPS(OptionsTab.REMINDERS, false),
	MANSION_LIKE_NOTICE(OptionsTab.REMINDERS, false),
	MINIMIZED_POPUP(OptionsTab.REMINDERS, false),
	JOB_TIPS(OptionsTab.VISUALS, false),
	WEATHER_EFFECT(OptionsTab.VISUALS, false),
	HOLIDAY_TURF(OptionsTab.VISUALS, false),
	HOLIDAY_MAIN(OptionsTab.VISUALS, false),
	HOLIDAY_WEATHER(OptionsTab.VISUALS, false),
	MAIN_INTERFACE_TAB_DISPLAY(OptionsTab.VISUALS, true),
	NEW_REWARD(OptionsTab.INTERFACE, true),
	CREW_CAMP(OptionsTab.INTERFACE, true),
	BATTLE_REPORT(OptionsTab.INTERFACE, true),
	INVESTMENT_AGENCY(OptionsTab.INTERFACE, true),
	STREET_WAR(OptionsTab.INTERFACE, true);
	private OptionsTab tab;
	private boolean mustEnable;
	public String getTemplate() {
		return Images.PREFIX + this;
	}
}
				
			

West Game - Butchers House Rally Script

Tiles Survive - Mail Script