Kepler. Documentation · Scripts 508 functions available right now Français

Driving the workers

A script can switch the bot's automations on and off, and ask which one is running. This is the only family that acts on the bot itself rather than on the game.

What these functions really do

They reproduce the click in the interface, not an in-memory start. The setting is saved, it survives a restart of the bot, and the tool exclusivity rule applies exactly as if you had ticked the box yourself.

That difference matters. A toggle that lived only in memory would be undone at the next launch, with nothing to say so: your script would have switched farming on, and you would find the account idle the next day without understanding why.

The Start… and Stop… functions return an error, nil when the change happened. The IsRunning… ones return a boolean.

The error is a Kepler addition: the reference tool returns nothing. A copied script calls these as statements and reads no return, so nothing breaks; a script written for Kepler, on the other hand, can check.

For the reads, false means "I could not read" as much as "the worker is not running". The failure goes to the log, never silently.

Switching on and off

FunctionReturns
StartBrain() / StopBrain()1: an errorBrain. Build queues and research.
StartScanner() / StopScanner()1: an errorThe scanner. System sweeps.
StartHunter() / StopHunter()1: an errorThe hunter. Target tracking.
StartSleepMode() / StopSleepMode()1: an errorSleep mode. See the warning below.
StartFarmingBot() / StopFarmingBot()1: an errorFarming. StartFarmingBot() gives the farmer a session when it has none.
StartFarmSession(session)1: an errorStarts one named session, like the ▶ on its row.
StartExpeditionsBot() / StopExpeditionsBot()1: an errorExpeditions.
StartColonizerBot() / StopColonizerBot()1: an errorThe colonizer.
StartDiscoveryBot() / StopDiscoveryBot()1: an errorDiscovery.
StartDefenderBot() / StopDefenderBot()1: an errorThe defender.
err = StopFarmingBot()
if err != nil { LogError("farming:", err) }
StartExpeditionsBot()
StartBrain()
StopBrain()
StartScanner()
StopScanner()
StartHunter()
StopHunter()
StartColonizerBot()
StopColonizerBot()
StartDiscoveryBot()
StopDiscoveryBot()
StartDefenderBot()
StopDefenderBot()
StopExpeditionsBot()

A worker may refuse to start, and it says why

Test the error. It does not merely say "that did not work": it says what is missing, and that is most often a setting.

err = StartWorker("timer")
if err != nil {
	LogWarn("the timer will not start:", err)
	// enter a Discord webhook or tick Telegram, here or in the bot
	// settings: without a channel, the monitoring would warn nobody
}

Measured by running this script on a real account: the timer requires an alert channel, the Colonizer a starting point, and so on. A script that ignored that return would believe it had switched on a worker that never started.

An unknown worker name is refused too, and named: unknown worker "cephalopode".

Running a pass right away

FunctionReturns
RunWorkerNow(name)1: an errorRuns a pass of the worker without waiting for it to wake up: the Brain's « Check now », the defense's « Check for attacks », the scanner's « Scan the universe now ».

It is the page's button, with its refusals. A switched-off Brain refuses, because a Brain pass builds; a sweep already running, here or on another bot of the same universe, refuses too. Any other switched-off worker runs once, with its page's settings. While you play in the built-in browser, the pass waits for you to finish. The names are those of StartWorker.

err = RunWorkerNow("brain")
if err != nil {
	LogWarn("no Brain pass:", err)
}
RunWorkerNow("defender")

Asking which one runs

FunctionReturns
IsRunningBrainBot()1: a booleanTrue if Brain is running.
IsRunningFarmingBot()1: a booleanTrue if farming is running.
IsRunningExpeditionsBot()1: a boolean
IsRunningColonizerBot()1: a boolean
IsRunningDiscoveryBot()1: a boolean
IsRunningDefenderBot()1: a boolean
if IsRunningFarmingBot() {
  Print("farming is running")
}
Print(IsRunningBrainBot(), IsRunningExpeditionsBot(), IsRunningColonizerBot())
Print(IsRunningDiscoveryBot(), IsRunningDefenderBot())

There is no IsRunning for the scanner, the hunter or sleep mode: the reference tool gives none, and we do not invent a name no copied script would call. The general form below covers them.

When a worker counts as running

The IsRunning… functions and IsWorkerRunning say whether the worker is running right now, as the workers page does: its loop is going, whether it is in the middle of a pass or waiting for the next one. They return false when:

  • its switch is off and it has finished its pass;
  • the account is stopped, or has not started yet since the bot was launched;
  • sleep mode, vacation mode or PauseBot() have suspended it. The manual mode of the built-in browser too, except the defence, which keeps watch while you play. The switch stays on, and the worker starts again on its own.

Under PauseBot(), the workers page still says "running": the pause closes the session without stopping the loops, which have nothing left to do. These functions answer what the account is really doing, and RunWorkerNow refuses its pass.

They return true for a worker whose last pass failed: it is running, and tries again; its error shows on its page. True as well for a worker that was just switched off and is finishing its pass, and for sleep mode staying up, switch off, long enough to bring a fleet back.

A single pass on a switched-off worker, started by RunWorkerNow or by the button on its page, does not set it running: IsWorkerRunning stays false during the pass, and the page says stopped.

To read the switch itself, the box on the screen, use IsWorkerEnabled(name): true all night long or all through manual mode, as long as the box is ticked. That is the one you need to leave a worker the way you found it:

before = IsWorkerEnabled("expeditions")
StopWorker("expeditions")
// ... the script's work ...
if before { StartWorker("expeditions") }

The general form

Kepler has workers the reference tool does not: repatriation, spying, the phalanx, debris field watching, the timer. These functions take the worker's name and cover them all.

FunctionReturns
StartWorker(name)1: an errorSwitches the named worker on.
StopWorker(name)1: an errorSwitches it off.
IsWorkerRunning(name)1: a booleanSays whether it is running right now. See above.
IsWorkerEnabled(name)1: a booleanSays whether its switch is on.
ListWorkers()1: a listThe names you can switch on here, in English.

The emergency stop

One call silences the bot: the session closes, the workers are suspended, the account's other scripts are paused, and every game call fails for as long as the pause lasts.

This is the safety net for the forgotten script. A loop left running that polls the server no longer sends a single request: its calls fail with "account asleep", so you get errors in your console instead of a ban.

FunctionReturnsWhat it does
PauseBot()1: an errorCuts all communication with the game.
ResumeBot()1: an errorGives it back.
IsBotPaused()1: a booleanSays where things stand.
LogOut()1: an errorAlias of PauseBot, for scripts coming from Ninja.
Logout()1: an errorThe same, with the spelling of Ninja's documentation.
Login()1: an errorAlias of ResumeBot.

The script that calls PauseBot is never paused itself, otherwise it could never call ResumeBot and the account would stay silent.

A paused account is no longer defended. The Defender stops watching, just as during sleep mode. This shelters your account from your own scripts, not from an attacker.

If the script ends without lifting the pause, the "Resume the bot" button in the "Bot paused" banner, at the top of every page of the bot, lifts it too. You are never stuck.

if MyReasons() {
	PauseBot()
	SleepMin(30)
	ResumeBot()
}
for name in ListWorkers() {
  Print(name, "running:", IsWorkerRunning(name), "on:", IsWorkerEnabled(name))
}
err = StartWorker("repatriate")
if err != nil { LogError("repatriation:", err) }
StopWorker("spyer")

The names are lowercase and unaccented: brain, defender, expeditions, sleep, scanner, farmer, colonizer, repatriate, supply, hunter, discovery, spyer, phalanx, militarydebris, colonywatch, timer, scheduledflights, rewards, orion. An unknown name returns an error that names it, rather than doing nothing. orion only switches on in an Orion universe: anywhere else, StartWorker returns the error described on the Orion page. ListWorkers only names it on a universe the bot knows has Orion, so that a loop that stops at the first error does not trip over it; IsWorkerEnabled and IsWorkerRunning answer everywhere.

rewards is the Rewards and boosters page. Like the others, it is suspended during sleep mode: switching it on at night prepares the wake-up, and no request leaves before. It stays outside the tools rule: a tool does not switch it off, and switching it on does not stop the running tool. To keep it quiet during a long piece of work in a script, switch it off before and back on after: StopWorker("rewards"), then StartWorker("rewards").

supply feeds the Brain's planets from banks. It is set up in the Supply tab of the Brain page, and stopping it does not stop the building: the Brain carries on, it simply waits on its own production.

The reverse does not hold: switching the Brain off pauses supply. Nothing is delivered while the Brain is off, and deliveries resume on their own when it is switched back on, from freshly worked-out needs. IsWorkerRunning("supply") answers true during that pause: the worker is running, it waits for the Brain. And a Planning slot that switches supply on while the Brain is off sends nothing.

Repatriate spares a planet that is waiting for a delivery. It no longer does so when supply or the Brain is off, nor when the last check of supply found no bank able to cover the delivery. In those cases nothing is about to leave for that planet, and it must not be left exposed.

colonywatch is not the coloniser. colonizer settles new planets; colonywatch watches for colonies appearing around the players you follow.

Composing a farm session

FunctionReturns
NewFarmSession()1: a builderTo chain, then BuildFarmSession().

The builder is set method by method, then BuildFarmSession() saves the session and makes it active, like the interface's "Start" button. It returns two values: the created session and an error.

It does not switch farming on for you: StartFarmingBot() does that. Keeping the two apart lets you prepare a session without sending it off at once.

What StartFarmingBot() picks to run

It does more than flip the switch: it gives the farmer a session when it has none, in this order.

1. An active session: it just switches farming on. That is the case of a script that has just created one. 2. A paused session: it resumes where it stopped. Any other one would start again from the first system. 3. Whatever waits in the queue, in the order the sessions entered it. 4. Otherwise, the first saved session, in creation order. 5. No session at all: it returns an error and does nothing. A farmer switched on with nothing to run is exactly what this avoids.

StartFarmSession(session) is for when that choice is not what you want: it starts the one you name, like the ▶ on its row in the Farmer tab. The ID comes from BuildFarmSession(), or from GetFarmSessions() for a session set up on the screen.

session, err = f.BuildFarmSession()
StartFarmSession(session.ID)
origin = GetCachedCelestials()[0]
f = NewFarmSession()
f.SetName("night watch")
f.SetOrigin(origin)
f.SetRangeAroundOrigin(30)
f.SetMinimumResourcesToAttack(300000)
f.SetAdditionalCargo(10)
f.SetAttackDelay(2, 5)
f.SetPriorityRatio(1, 1.5, 2)
f.SetUsePathfinders(false)
f.SetIgnoreActivity(true)
f.SetFastAttacking(true)
session, err = f.BuildFarmSession()
if err != nil { LogError("session:", err) }
Print("session", session.ID, "range", session.Range)
StartFarmingBot()

The settings that carry

SetOrigin, SetOriginCoord, SetRange, SetGalaxyRange, SetRangeAroundOrigin, SetName, SetMinimumResourcesToAttack, SetAdditionalCargo, SetMinimumPlayerRank, SetUsePathfinders, SetIgnoreActivity, SetFastAttacking, SetSmallCargosFirst, SetPriorityRatio, SetAttackDelay, SetFarmStrategy, SetMajority, SetRaidsAsReportsArrive, SetBackupCargos, SetDeleteReports.

Every field of the campaign window has its method, and a test in the bot checks it: a setting added to the screen without its own method makes it fail.

A value outside the screen's bounds is refused, never quietly brought back: BuildFarmSession() returns the error, which names the method and the value received, and saves nothing. The bounds:

  • SetAdditionalCargo from 0 to 50, in percent;
  • SetRangeAroundOrigin from 0 to 250 systems;
  • SetAttackDelay(min, max) 2 seconds at least, and a maximum that is not below the minimum;
  • SetProbes from 0 to 100 probes;
  • SetMinimumStorageToIgnore 0 or more for each of the three levels;
  • SetMajority and SetFarmSpeed, further down.

Several deserve a word.

SetRange(galaxy, systemFrom, systemTo) keeps your bounds, inclusive, and the galaxy you ask for. It approximated for a long time - half the width of the interval became a radius around the origin - then it kept the systems but refused any galaxy other than the origin's, having no way to sweep elsewhere. The campaign can now cross galaxies, and that refusal is gone.

A galaxy of zero means "all of them". On a wrapping universe, a span that starts after it ends goes past the edge: SetRange(1, 480, 20) covers 480 to 499 then 1 to 20.

SetGalaxyRange(from, to) is a Kepler extra, with no equivalent in the reference tool, which only bounds one galaxy at a time. SetGalaxyRange(1, 4) together with SetRange(0, 200, 350) sweeps systems 200 to 350 of galaxies 1 to 4. Zero means "all of them" on either side - and with no system bounds, those are WHOLE galaxies: four of them are close to two thousand systems, and a campaign spends days there.

SetRangeAroundOrigin(range) is still there for whoever prefers a radius. It puts the campaign back in automatic mode and clears all four bounds: the last call wins, either way.

SetOriginCoord(galaxy, system, position, type) does not need the session. SetOrigin has to resolve a celestial, so it waits for the connection; this one names the coordinate directly. The type is "planet" or "moon", any other word is refused rather than guessed.

SetMinimumPlayerRank does not mean what it looks like. Rank 1 is the best player: "up to 5000" therefore keeps the top five thousand and drops the rest. Zero takes them all.

SetFarmStrategy(name) picks the wave strategy, like the "Strategy" menu of the campaign window, with the same words as SetExpeditionsStrategy:

  • "all" waits for every raid to come home before the next wave. That is the default;
  • "majority" sends the next wave once a share of the raids is back, without waiting for the farthest ones: see SetMajority;
  • "never" sends again at the first free slot, "Never wait (risky)".

Case and spaces do not matter. Any other word is refused: BuildFarmSession() returns the error, naming the three expected words, and saves nothing. "majorite", the key the bot's configuration shows, is not one of them.

SetMajority(threshold, wait) sets the two fields of "Wait for most raids", in the screen's units. The threshold is the share of the wave's raids, in percent, whose return sends the next wave: from 0 to 100, and 0 means half, like the field left empty. The wait is the longest time, in minutes, the wave gives the raids coming home just after the threshold, so they leave with it: from 0 to 240, and 0 leaves as soon as the threshold is reached. A value out of these bounds is refused rather than quietly clamped.

It does not pick the strategy. Without SetFarmStrategy("majority"), both values are kept in the session but not used, as on the screen when you switch to another strategy.

SetRaidsAsReportsArrive(true) ticks "Raid as soon as the first reports arrive": each target is raided as soon as its report comes in, while the spying goes on. Unticked, the default, the session probes its whole zone, ranks the targets, then raids from the richest to the poorest. Faster, but the first targets reported are raided before the best ones. The bot always keeps free slots for its probes, and probe raiding itself waits for the spying to end.

SetFastAttacking does not mean what it means in Ninja. There, the "Fast attacking" box sends the raids as soon as the espionage reports come in, while the spying goes on. In Kepler, SetFastAttacking(true) picks the "Never wait (risky)" strategy, and false "Wait for every raid to come back": that is SetFarmStrategy("never") or SetFarmStrategy("all"), minus the majority. It stays for copied scripts, and SetFarmStrategy is the complete way. Ninja's behaviour is set with SetRaidsAsReportsArrive(true): a script brought over from Ninja writes it instead of SetFastAttacking(true), or on top of it if it also wants the strategy.

f = NewFarmSession()
f.SetName("majority as reports arrive")
f.SetOriginCoord(1, 120, 8, "planet")
f.SetRangeAroundOrigin(30)
f.SetFarmStrategy("majority")
f.SetMajority(60, 10)            // 60 percent back, then 10 minutes at most
f.SetRaidsAsReportsArrive(true)
session, err = f.BuildFarmSession()
if err != nil { LogError("session:", err) }

SetBackupCargos(second, third) sets the "Second type" and "Third type" of the window. When the first ship runs short on a departure, the second carries what is left to raid, then the third; a raid never mixes two types. The first one is set as before, with SetUsePathfinders and SetSmallCargosFirst, otherwise the large cargo.

Pass the constants LARGECARGO, SMALLCARGO or PATHFINDER, or 0 for "None": that type never leaves. Any other ship is refused at BuildFarmSession(). Without the call, the fallback from before this setting: large then small cargo, or the other way round, behind the pathfinder. A third with no second takes second place, and a type already taken higher up is skipped. With nothing else set, SetBackupCargos(PATHFINDER, 0) therefore leaves with large cargos, then pathfinders, and never small cargos.

Probes raid alone: with SetEspionageProbeRaids(true), these two types only matter on a universe that refuses probe raiding.

SetDeleteReports(espionage, combat) sets the screen's two boxes separately, "Delete espionage reports" and "Delete combat reports". SetDeleteReports(true, false) deletes your probes' reports and keeps the combat reports, for OGLight for instance. SetDeleteCombatReports ticks or unticks both together; of the two, the last one called wins.

The settings that came from Ninja

SetProbes, SetFarmSpeed, SetMinimumDefensesToIgnore, SetAttackPlayersWithDefenses, SetMinimumStorageToIgnore, SetEspionageProbeRaids, SetDeleteCombatReports.

They all have a control in the campaign window since 18/09/2026. These functions remain the way a script reaches the same fields: a script and a click set the very same thing, and the window carries over what it does not show rather than wiping it.

Each one still defaults to what the bot did before it existed, so a session set up by hand behaves exactly as before.

SetProbes(n) sets the probes per espionage, both on the sweep and on the re-spy before firing, from 0 to 100. Without it, or at zero, the count set in your OGame account.

SetFarmSpeed(speed) sets the raid speed, with the percentage constants: SetFarmSpeed(FIFTY_PERCENT). Without it, full speed. A value out of bounds is refused rather than quietly clamped.

SetMinimumDefensesToIgnore(n) accepts a target whose seen defence is strictly below n. The name comes from Ninja and reads the other way round: it is the defence at which the target starts being ignored. With 1 you therefore get Kepler's default rule, which accepts no defence at all.

SetAttackPlayersWithDefenses(false) closes that threshold again, whatever the order of the calls. Set to true it does nothing: the threshold decides.

SetDeleteCombatReports(true) moves each raid's combat report to the bin, once its loot has been counted, and at the end the reports its probes brought back: both of the screen's boxes at once. To delete only one of the two kinds, SetDeleteReports.

The game's mailbox locks up entirely when too many messages pile up — inbox and bin together — and nothing can be done in it any more. A session produces one report per raid: without this setting, a farm running for nights ends up blocking its own player's mailbox.

Four conditions before anything is deleted, and none is decorative: the report must carry the ID of the fleet we sent, that ID must not be zero, the report must have a number of its own, and its target must be the one we aimed at. A report of an attack suffered is therefore out of reach.

The game's action moves to the bin and does not destroy, so Kepler does both: the deletion, then the purge of that tab's bin. Deleting without purging would only fill the other half of the counter that jams the message system.

SetMinimumStorageToIgnore(metal, crystal, deut) skips targets whose storage buildings are too small: below these levels, the position is not attacked. The name comes from Ninja and reads that way round - the minimum below which you ignore. SetMinimumStorageToIgnore(4, 0, 0) asks for a metal storage of level 4 at least and says nothing about the other two. Zero asks for nothing, and a negative level is refused: it used to pass for a zero, and the campaign attacked everything.

A planet with small storage cannot build anything up: you empty it once, and coming back no longer pays.

This setting costs requests. Storage levels are not in the message list, only in each report's detail: asking for them is one request per retained target where the session makes one for all of them. Nothing is read while the three values are zero, and only targets that passed every other filter are opened.

A target you have not seen is skipped. A report taken with too few probes does not show the buildings: it does not say the storage is small, it says you did not look hard enough. Same rule as for defence.

SetEspionageProbeRaids(true) has espionage probes carry the loot instead of cargo ships.

They are the fastest ship in the game and cost only crystal, but each carries only five units: probe raiding is a matter of numbers. On loot a neighbour also wants, speed is what decides, and losing probes costs nothing next to a cargo.

The universe has the last word. Where probe raiding is disabled, a probe's hold is zero: Kepler asks the game and falls back to cargo ships, rather than letting a session set this way never take off.

What spying needs stays home. The session sets aside what its spying keeps in the air at once - so many probes per target, times the smaller of its number of targets and its slots - and raids only with the surplus. Without that reserve, the next round would have nothing left to look with and would attack on stale reports.

Probes, and nothing else. A probe carries so little that a big haul takes hundreds of thousands of them: a few raids are enough to have them all in the air. The departure then has no hold left, and the session waits for them to come back - it never falls back to cargo ships. Only a universe that forbids probe raiding sends it out with cargo ships.

Two refusals never loosen. A fleet sitting on the target always refuses: it shoots back, and it is worth more than defence. And a report that could not establish the figure, for want of probes, always refuses too: it does not say the planet is empty, it says you did not look hard enough.

Starting from the nearest celestial

SetAttackFromNearestPlanet(true) and SetAttackFromNearestMoon(true) do the same thing here, and saying so beats pretending there are two settings: the reference tool separates planet and moon, Kepler takes whichever of the two is best placed and puts the moon ahead of its planet at equal distance. It carries the same fleet without announcing anything to the neighbourhood, and what leaves it does not leave the planet bare. SetStartFromNearest(true) is the Kepler name for the same thing.

Either one turns it on, and false only turns it off if nothing else asked for it: a script writing SetAttackFromNearestPlanet(true) then SetAttackFromNearestMoon(false) clearly wants the mode.

PROBES AND RAIDS LEAVE FROM THE SAME PLACE, never one without the other. A "from nearest" that only moved the probes would be exactly the flaw we hold against other tools.

A galaxy where the account owns nothing is skipped. The calculation refuses to cross a galaxy: a flight that does gets noticed, and the game charges hours for it. The session writes it to the log rather than sweeping into the void. That is what makes SetGalaxyRange usable: without it, a four-galaxy span from a fixed origin would send probes on half-hour flights each way.

SetOrigin becomes optional. On an automatic span, the range then applies around each of the account's celestials, and overlapping zones are swept only once.

The settings with no equivalent

One of Ninja's settings does not exist in Kepler's session. It is accepted and does nothing, so a copied script does not stop, and BuildFarmSession() names it in the bot's log as well as in the Ignored field of what it returns.

SetIgnoreSleepMode. It will not leave that list: punching an exception through sleep would reopen the part that has cost the most defects.

Print("ignored:", len(session.Ignored))

One session at a time, the rest queued

Farming runs only one: two would fight over slots and probes. But BuildFarmSession() no longer refuses when a session is running - it queues the new one, and returns its id as usual.

And it says so, through two fields of the returned session: Queued is true while it waits, QueueRank gives its place starting at 1. Without them the two cases looked exactly alike, and a script had no way to tell that its session was waiting instead of running.

session, err = f.BuildFarmSession()
if session.Queued {
    LogInfo("waiting its turn, place", session.QueueRank)
}

So a script can build thirteen in a row: the first becomes active, the other twelve wait their turn in the order you created them. When a session finishes, farming picks up the next one on its own. The Farmer tab shows them as "queued - 3 of 12".

Three things worth knowing:

  • StopFarmingBot() keeps the queue: it puts the active session back to rest, and whatever was waiting is still waiting. The next StartFarmingBot() picks it up in order. Abandoning clears it, and the log says how many sessions were waiting: AbortAllFarmingSessions(), which also removes every session, whereas the screen's "Stop everything" button keeps them: that one is StopAllFarmSessions(). A row's ■ only stops that session: if it is the running one, the next one in the queue takes over. That is StopFarmSession, see Stopping, queueing, editing or deleting a campaign;
  • pausing keeps it: a suspended session resumes where it was, and what followed it still follows it;
  • if the Planning also drives farming, its programme comes first: a range's queue empties before the scripts' one.

A row's ▶ button still refuses a second session: it launches the one you pointed at, and queueing it would be a surprise. That is what the + button next to it is for: + to wait its turn, ▶ to leave right away.

The screen's queue and the scripts' queue are the same one. The twelve sessions a script queues show up in the "Queue" panel at the bottom of the Farmer tab: you see the running order, you can take one out - the session is not deleted - and start the first one with a click. A session deleted while it was waiting is skipped quietly: the turn goes to the next one.

Setting up and running the Spyer

The Spyer sweeps an area of the galaxy and spies on whatever matches its criteria, without attacking anything. Everything its page offers has its function: the settings of the "Save" button, the campaigns, and the buttons on their rows.

The settings

FunctionReturns
GetSpySettings()1: the settingsEvery setting below, in one go.
SetSpyTargets(targets)1: an error"all", "planets" or "moons": the "Targets" menu.
SetSpyPlayers(players)1: an error"all", "active", "inactive", "hunter" or "list": the "Players" menu.
SetSpyPlayerList(names)1: an errorThe text box of the "List" choice: a list of player names, written as in the highscore.
SetSpyRoute(route)1: an error"systems" or "players": the "Route" menu, system by system or player by player.
SetSpyStrongPlayers(yes)1: an error"Spy on stronger players too".
SetSpySkipHomeworlds(yes)1: an error"Skip home planets"; their moon is still spied on.
SetSpyActivityStar(yes)1: an errorThe "Active players only" box: the red star, under 16 min.
SetSpyActivityTimer(yes)1: an errorThe "Timer players only" box: 16 to 59 min.
SetSpyActivityNone(yes)1: an errorThe "Players with no activity" box: nothing shown, over an hour.
SetSpyProbeDelay(min, max)1: an errorDelay between two probes, in milliseconds.
SetSpySystemDelay(min, max)1: an errorDelay between two systems, in milliseconds.
SetSpyPlayerDelay(min, max)1: an errorDelay between two players, when the campaign goes player by player, in milliseconds.
SetSpyMaxSlots(n)1: an errorThe Spyer's slot cap, from 0 (no cap) to 100.
SetSpyCheckInterval(min, max)1: an errorWait between two passes of the worker, in seconds.

Each Set… is saved like the page's "Save" button: the setting applies at once and survives a restart of the bot. The slot cap is the one on the "Spyer" row of the Settings; the interval has no field on screen.

A value out of bounds is refused, never quietly brought back: an unknown name, a delay under 200 ms, a minimum larger than its maximum, an interval under 120 seconds, more than 100 slots. The error says what is expected, and nothing changes.

The three activity boxes add up. Each one adds its category of targets, from what the galaxy shows on the targeted planet or moon: timer and no activity spy on everyone except the active ones. No box, or all three: every target.

"active" and "inactive" in SetSpyPlayers are about something else: the status the game gives the player, the i and I of the galaxy. The activity shown on the planet is what the three boxes are for.

The player-by-player route reads the galaxy less. With "systems", the default, the campaign reads the galaxy of every system in its zone. With "players", it first keeps the players of its zone who pass its filters according to the bot's map (status, vacation, strength, ranking, spared players), then reads only the systems where the Scanner has seen them, one player after another, with the delay between two players. Over a whole universe of 4,491 systems, thirty-six players kept need a few hundred. The view of each visited system still decides what is sent: the activity, the moon and the vacation of the moment. A player the Scanner has never seen is not probed. "hunter" always goes player by player, whatever the route.

The List is your own players. SetSpyPlayers("list") picks "List" in the menu and SetSpyPlayerList(names) writes its text box, as on screen: two gestures, two functions. The campaign spies on them like the Hunter list, player by player, where the Scanner has seen them, inside its zone; a name the map does not know is written to the log and is not probed. Case and surrounding spaces do not matter, a duplicate is dropped. This list does not feed the Hunter list. An empty list empties it; a campaign started on an empty list stops at once, and the log says so.

SetSpyPlayers("list")
err = SetSpyPlayerList(["Alpha", "Beta"])
if err != nil { LogError("list:", err) }
Print(GetSpySettings().PlayerList)

The page also opens on a list from its address: #/bot/1/spyer?players=Alpha,Beta picks "List" and fills the box, without saving or sending anything. "Save" keeps it; the probes only leave when a campaign is started.

GetSpySettings() returns Targets, Players, PlayerList, Route, StrongPlayers, SkipHomeworlds, ActivityStar, ActivityTimer, ActivityNone, ProbeDelayMin, ProbeDelayMax, SystemDelayMin, SystemDelayMax, PlayerDelayMin, PlayerDelayMax, MaxSlots, CheckIntervalMin and CheckIntervalMax.

// the timers and the players with no activity, not the active ones
SetSpyActivityStar(false)
SetSpyActivityTimer(true)
err = SetSpyActivityNone(true)
if err != nil { LogError("espionage:", err) }
r = GetSpySettings()
Print(r.ActivityStar, r.ActivityTimer, r.ActivityNone)
SetSpyTargets("planets")
SetSpyPlayers("inactive")
SetSpyRoute("players")
SetSpyStrongPlayers(false)
SetSpySkipHomeworlds(true)
SetSpyProbeDelay(300, 450)
SetSpySystemDelay(300, 500)
SetSpyPlayerDelay(2000, 5000)
SetSpyMaxSlots(4)
err = SetSpyCheckInterval(900, 1800)
if err != nil { LogError("espionage:", err) }

The campaigns

FunctionReturns
NewSpySession()1: a builderA new campaign, to chain and then BuildSpySession().
EditSpySession(campaign)1: a builderThe "Edit" button: the saved campaign, to rework.
GetSpySessions()1: a listThe table of campaigns.
StartSpySession(campaign)1: an error"Start", or resuming the paused campaign.
PauseSpySession()1: an error"Pause": the progress is kept.
ResumeSpySession()1: an error"Resume": the paused campaign carries on from the system it reached.
StopSpySession()1: an error"Stop": the progress is thrown away.
RemoveSpySession(campaign)1: an error"Delete"; the chosen campaign stops with it.

campaign is the ID, the ID field of what BuildSpySession() and GetSpySessions() return.

BuildSpySession() saves, it does not start: it is the editor's "Confirm" button. It returns two values, the campaign and an error, and the campaign is never nil, even on failure. StartSpySession(campaign.ID) then starts it, like the "Start" button on its row.

s = NewSpySession()
s.SetName("neighbourhood")
s.SetRadiusAroundPlanets(30)
campaign, err = s.BuildSpySession()
if err != nil { LogError("campaign:", err) }
err = StartSpySession(campaign.ID)
if err != nil { LogError("start:", err) }

Two ways to define an area, like the editor's two tabs, and they exclude each other.

  • The manual campaign. SetOrigin(celestial) or SetOriginCoord(galaxy, system, position, type) for a fixed start, which spies every galaxy of its area as far as its probes' fuel tank reaches: a system whose trip burns more deuterium than that tank is left out, and the log says so; SetStartFromNearest(true) to leave from the best-placed celestial, recomputed at each system - the default for a new campaign. SetGalaxyRange(min, max) and SetSystemRange(min, max) for the area.
  • The automatic campaign. SetRadiusAroundPlanets(radius), 1 to 499 systems around each planet; AddPlanet(planet) ticks one of the account's planets, ClearPlanets() unticks them all. Without AddPlanet, every planet, colonies to come included. The probes always leave from the nearest.

SetName(name) and SetRankRange(min, max), the overall ranking, apply to both. Zero and zero mean "no limit", and zero on one side leaves that side open.

The filters set next to the overall ranking apply to both as well:

  • SetAlliances(tags) only probes these alliances, a list of tags; case does not matter, and an empty list takes them all again. A player with no alliance belongs to none.
  • SetMilitaryRange(min, max, unit), SetOffensiveRange(min, max, unit) and SetDefensiveRange(min, max, unit) bound the military ranking, its fleet and its defence. The unit is "rank" (1 is first) or "points". The fleet and the defence are split like OffensivePoints() and DefensivePoints(), from the public ranking the bot reads again every hour, and their ranks are counted on those points. As soon as a band is set, a player missing from the ranking is left out: probing someone you cannot place risks the very probe the band was meant to prevent. Until the ranking could be read, the campaign waits and the log says so.
  • SetIncludeOwnAllianceAndFriends(yes) is the "Also spy on my alliance and my friends" box. Unticked, the default, the members of your alliance and your friends are left out; ticked, they are probed if they pass the other filters.
// the small military players of two alliances, without your own
s = NewSpySession()
s.SetName("easy targets")
s.SetAlliances(["FLZ", "ABC"])
s.SetMilitaryRange(0, 50000, "points")
s.SetDefensiveRange(200, 0, "rank")
s.SetIncludeOwnAllianceAndFriends(false)
campaign, err = s.BuildSpySession()
Print(campaign.Alliances, campaign.MilitaryMax, campaign.MilitaryBy, err)

A script that calls both families is refused: letting one quietly wipe the other would spy on another area than the one it wrote. Also refused, and BuildSpySession() says so: a negative number, a minimum larger than its maximum, a radius outside 1 to 499, a coordinate outside the sky, a planet that is not the account's, a manual campaign with no start.

// a manual campaign from a moon, galaxies 1 to 3
origin = GetCachedMoons()[0]
s = NewSpySession()
s.SetName("galaxies 1 to 3")
s.SetOrigin(origin)
s.SetGalaxyRange(1, 3)
s.SetRankRange(1, 500)
campaign, err = s.BuildSpySession()
Print(campaign.ID, campaign.Reused, err)

An identical campaign is not doubled. If the table already holds one with the same settings, BuildSpySession() returns that one, with Reused set to true: a script run when the bot starts does not fill the table with twins at every restart.

One chosen campaign at a time. StartSpySession refuses while another one is chosen, running or paused: the page's "Start" button would replace it and throw its progress away, a script stops it first with StopSpySession(). For the same reason, the chosen campaign cannot be edited.

for c in GetSpySessions() {
	if c.Paused {
		ResumeSpySession()
	}
}
e = EditSpySession(campaign.ID)
e.SetRadiusAroundPlanets(40)
campaign, err = e.BuildSpySession()
PauseSpySession()
StopSpySession()
RemoveSpySession(campaign.ID)

GetSpySessions() returns, for each campaign: ID, Name, Auto, Radius, Planets, StartFromNearest, Origin, RankMin, RankMax, GalaxyMin, GalaxyMax, SystemMin, SystemMax, the filters Alliances, MilitaryMin, MilitaryMax, MilitaryBy, OffensiveMin, OffensiveMax, OffensiveBy, DefensiveMin, DefensiveMax, DefensiveBy ("rank" or "points") and IncludeOwnAllianceAndFriends, and Running or Paused for the chosen campaign.

StopWorker("spyer") amounts to a pause and StartWorker("spyer") to resuming it: the switch keeps the chosen campaign. With no chosen campaign, the Spyer switched on turns itself off at once, having no area. A campaign that reaches the end of its area switches it off by itself.

The expeditions strategy

FunctionReturns
GetExpeditionsStrategy()1: a string"majority", "all" or "never".
SetExpeditionsStrategy(name)1: an errorChanges it, setting saved.

This is the "Strategy" menu of the expeditions in the panel: "majority" waits for most of the expedition slots to be back before the next wave, "all" waits for every one of them, "never" does not wait. The setting is saved like the menu and applies from the next wave.

Any other name is refused, and the error lists the three. A misspelt name quietly turned into "majority" would let the script believe it got what it asked for.

The rest of the Expeditions page, sheets included, is read and written with GetExpeditionsConfigs and SetExpeditionsConfigs: see Worker settings.

if GetExpeditionsStrategy() != "all" {
	err = SetExpeditionsStrategy("all")
	if err != nil { LogError("strategy:", err) }
}

The fleet slot reserve

FunctionReturns
GetFleetSlotsReserved()1: an integerHow many slots are kept free.
SetFleetSlotsReserved(n)1: an errorChanges that number, setting saved.

This figure is what leaves the Defender room to dodge. A dodge is a fleet send: with no free slot it does not happen, and the attack lands on a full planet. Everything that flies in Kepler respects that reserve — the night fleet save, scheduled flights, the counter-probe, the Lifeform Expedition. Your script is the only thing that can eat into it without noticing.

slots = GetSlots()
kept = GetFleetSlotsReserved()
if slots.Total - slots.InUse <= kept {
	LogInfo("leaving room for the Defender")
	return
}

SetFleetSlotsReserved saves the setting, like the field in the panel: it survives a restart. Zero is accepted — it means "I handle my own dodging" — a negative number is refused.

Each worker's cap, the other column of Settings > Fleet slots, is the MaxSlots field of its settings, and SetMaxSlotsFor caps the sends of your own scripts: see Worker settings.

Sparing players, positions, alliances

The farmer only raids inactive players, which already covers the neighbour you get along with: someone who plays is never attacked. What remains is what the bot cannot guess — the inactive member of your own alliance, the friend who stopped playing, the position you got burned on once.

This list lives in the database, belongs to the account rather than to a campaign: it therefore applies to every bot on that account, and it survives a stop as well as a restart.

It is set in the account's Settings, "Spared players" tab, or from scripts. The functions below read and write the same list as the screen.

FunctionReturns
IgnorePlayer(player)1: an errorSpares a player. Name or id.
IgnorePlanet(coord)1: an errorSpares a position, moon included.
IgnoreAlliance(tag)1: an errorSpares every known member of an alliance.
UnignorePlayer(player)1: an errorRemoves it from the list.
UnignorePlanet(coord)1: an error
UnignoreAlliance(tag)1: an error
IsPlayerIgnored(player)1: a booleanWhether it is on the list.
IsPlanetIgnored(coord)1: a boolean
IsAllianceIgnored(tag)1: a boolean
GetIgnored()2: the list and an errorThe whole list, all three kinds together.
IgnorePlayer("Xylo")          // by name, as on screen
IgnorePlayer(4242)            // or by id
IgnorePlanet("1:42:8")        // the planet AND its moon
IgnoreAlliance("SLD")         // every member the Scanner has seen

if IsPlayerIgnored("Xylo") {
	Print("left alone")
}

list, err = GetIgnored()
for e in list {
	// e.Kind is "player", "planet" or "alliance".
	// e.Key holds the id, coordinate or tag; e.Label is what to display.
	Printf("%s : %s", e.Kind, e.Label)
}

What the farmer does with it, and when

Two filters, not one. The first drops the position while reading the galaxy, before a single probe. The second drops the report when picking targets to attack — and that one matters most: a campaign resumed in its attack phase never re-reads the galaxy, and the reports it works from are those of the whole inbox, including any left there by another tool.

The log says spared target when this happens. The other reasons for skipping a position are silent.

What honours the list, and what deliberately does not

What honours it: the farmer, in the galaxy *and* when picking its attacks; the spyer, because probing leaves a trace exactly as attacking does; and FindInactivePlanetWithMinimumTravelTime, the only one of the four searches that names a player.

What does not, deliberately: the Galaxy screen, where you must still see whom you spare, and the night fleet save — where you park a fleet has nothing to do with whom you raid.

The hunter's spy button warns in the log, and sends anyway.

The hunter's button is a deliberate act on players you named by hand: refusing the send in silence would take back a choice you have just made. The contradiction is reported, not arbitrated.

Nor is this list the Defender whitelist, which says the opposite: "those I do not defend myself against". Sparing an alliance of two hundred members must never stop you dodging their attacks.

Two signatures differ from the reference documentation

It takes an int64 everywhere. We cannot follow it on two points, and those two functions refuse a number rather than accepting it silently:

  • IgnorePlanet expects a coordinate, not a planet id. The game does give that id when reading the galaxy, but the readings only keep the coordinate: an id would be stored and would never catch anything.
  • IgnoreAlliance expects the tag, not an alliance id. v13 gives no alliance id in galaxy data at all.

A tag is compared without case or spaces. It can change overnight, where a player id never does: that is the limit of the notion, not a shortcoming here.

A player absent from the readings is refused

As with the watch list: IgnorePlayer resolves the name from the Scanner's readings and refuses what it cannot find there. Storing an entry that would never match anyone would make the script believe it spares someone.

An alliance, on the other hand, can be added before the Scanner has been past: its members are recognised as the readings come in.

The farmer's blacklist

What the farmer no longer spies on or attacks. It does not play the same part as the spared list: that one protects friends, and also applies to spying; the blacklist sets aside targets that no longer produce, and only applies to the farmer.

A position enters it on its own once three reports in a row show exactly the same resources, below the campaign's minimum loot: the planet no longer produces, its storage is full but small. A report that changes or is worth a raid resets its count, and takes it off the list if it got there on its own. Such an entry only holds for the player who owned the planet: taken over by someone else, it is spied on again, and only set aside after three identical reports under the new owner. It only sets aside the planet, not its moon. A position added by hand sets aside both, and never leaves the list on its own.

It is shown and managed in the "Blacklist" tab of the Farmer page, or from scripts. Additions and removals take effect from the farmer's next pass.

FunctionReturns
GetFarmBlacklist()2: the list and an errorThe whole list, players and positions together.
AddToFarmBlacklist(target)1: an errorA player, by name or id, or a position.
RemoveFromFarmBlacklist(target)1: an errorRemoving what is not there is not an error; a name nothing knows is one.
ClearFarmBlacklist()1: an errorEmpties it, automatic entries included.
AddToFarmBlacklist("1:42:8")      // by hand: the planet AND its moon
AddToFarmBlacklist("Xylo")        // a player, by name
AddToFarmBlacklist(4242)          // or by id

entries, err = GetFarmBlacklist()
for e in entries {
	// e.Kind is "player" or "planet", as with GetIgnored;
	// e.Source is "auto" or "manual".
	// e.Key holds the id or the coordinate; e.Label is for display.
	if e.Source == "auto" {
		RemoveFromFarmBlacklist(e.Key)   // give back only the automatic entries
	}
}

ClearFarmBlacklist()

A position is named without its type: "M:1:42:8" and "1:42:8" are the same entry. A player missing from the Scanner's readings is refused when added, but can always be removed: by id, by the name shown in the list, or by e.Key as GetFarmBlacklist returns it.

Removing a position, or clearing the list, also resets its count of identical spy reports: it only comes back after three new identical reports, not the first one.

Composing a watch list

StartHunter() switches the watch on. It does not say who to watch: that list lives in the database and changes as the game goes. Switching the hunter on over an empty list surveys nothing.

FunctionReturns
GetHunterTargets()2: the list and an errorThe players under watch.
AddHunterTarget(player)1: an errorPuts a player under watch.
RemoveHunterTarget(player)1: an errorRemoves them, history included.
PauseHunterTarget(player, paused)1: an errorSuspends them without losing their history.
GetHunterHistory(player, n)2: the series and an errorThe player's activity readings, newest first.
AddHunterTarget("Xylo")          // by name, as on screen
AddHunterTarget(4242)            // or by id
StartHunter()

targets, err = GetHunterTargets()
for c in targets {
	Printf("%s: %d positions, activity %d", c.PlayerName, c.Positions, c.Activity)
}

The name works as well as the id. The reference tool takes only the id; the name is what you read on screen, and so what a script writes most often. Both forms lead to the same target: the bot resolves the name from its galaxy readings, once, on adding — because a player can rename themselves, their id cannot.

Adding the same player twice does not duplicate them. The list is kept by id.

A player absent from the readings is refused

err = AddHunterTarget(999999)
// player no. 999999 not found in the readings:
// has the Scanner been past them yet?

This is our second departure from the reference tool, which accepts any id. The watch works on known positions: on each pass it surveys the celestials the Scanner has seen. A target with no known position would therefore never return anything, and your script would believe it was watching someone.

The refusal tells you what to do: let the Scanner cover the player's area, then call AddHunterTarget again.

What a target carries

Field
PlayerID, PlayerName, Alliance, RankWho they are.
PositionsHow many celestials are known to be theirs.
ActivityThe last survey of all their positions: 15 when one is active right now, otherwise the shortest timer found, 0 when there is nothing anywhere.
PausedThe watch is suspended.
NotifyTimerAn alert is armed on their return.
LastCheck, AddedAtUnix dates, 0 if never surveyed.

Reading a target's history

GetHunterTargets only returns the last survey, summed up. The full series, position by position, is read with GetHunterHistory: one line per position and per pass, newest first. n caps the number of lines: 500 when it is 0, never more than 5000.

series, err = GetHunterHistory("Xylo", 200)
if err != nil {
	Print("history unreadable: ", err)
} else {
	for s in series {
		if s.Activity == 15 {
			Printf("online at %d on %d:%d:%d", s.Seen, s.Galaxy, s.System, s.Position)
		}
	}
}
Field
Galaxy, System, Position, IsMoonThe surveyed position.
Activity0 nothing, 15 online right now, 16 to 59 the minutes since the last activity.
SeenThe Unix date of the survey.

The database keeps thirty days of surveys per target. Only those of the bot running the script are read, even when another of your bots watches the same player.

Suspend rather than remove

RemoveHunterTarget also erases the player's activity history, which is the whole point of a long-standing watch. PauseHunterTarget(player, true) stops the surveys and keeps the series: that is what you want while a target is on holiday.

Two traps

Sleep mode is not a worker like the others. StartSleepMode() does not put the account to sleep there and then: it switches the worker on, and that worker then follows the schedule set in the panel. If the mode is not automatic and no manual sleep is set, nothing at all will happen.

When the sleep window does open, however, the session closes. Your script keeps running, but its game calls fail with "account asleep" until wake-up, and Defender no longer watches anything. A script that switches sleep on therefore finds itself without the game later, at an hour it did not choose.

Switching a tool on switches the rest off. The phalanx, debris field watching and the other tools are exclusive: the bot runs only one, and switching one on switches the ordinary workers off. That is the interface's rule, and it applies here too. A StartWorker("phalanx") can therefore stop your farming without you asking for it.

One script driving others

FunctionReturns
GetScripts()1: a list of namesEvery script on the account.
GetRunningScripts()1: a list of namesThose running right now.
IsScriptRunning(name)1: a booleanIs that one running.
IsPausedScript(name)1: a booleanIs that one paused.
StartScript(name, [params])1: an errorStarts it and returns at once. The table of parameters is optional.
ScriptParams()1: a tableThe parameters of the current run, empty when there are none.
StopScript(name)1: an errorStops it.
PauseScript(name)1: an errorSuspends it.
ResumeScript(name)1: an errorResumes it where it was.
IsScriptRunAtStart(name)1: a booleanIs its "run at startup" box ticked.
SetScriptRunAtStart(name, on)1: an errorTicks it (true) or unticks it (false).
IsScriptRemoteStart(name)1: a booleanIs its "remote start" box ticked.
SetScriptRemoteStart(name, on)1: an errorTicks or unticks it.
IsRemoteStartEnabled()1: a booleanIs remote start switched on in My account.

What this is for. A script runs end to end in a single thread: what it does, it does in sequence. An account that wants a night watch, a farm and a daily report therefore has three scripts — and something has to decide which one runs when. That is the job of a conductor script: it does not act on the game, it turns the others on and off.

// The conductor: the watch at night, the report in the morning.
CronExec("@22h00", func() {
	StartScript("night-watch")
})
CronExec("@08h00", func() {
	StopScript("night-watch")
	StartScript("report")
})

The .ank suffix is optional. StartScript("watch") and StartScript("watch.ank") name the same script: storage adds the suffix by itself, and demanding it would fail half the calls on a script that is right there.

StartScript returns at once, it does not wait for the started script to finish. And the started script does not die with the one that started it: once away, the two are independent.

Three refusals worth knowing.

  • A script does not restart itself: that means nothing.
  • A script does not pause itself. It would be a permanent block: nobody is left running to resume it, and the account keeps a frozen script that looks alive.
  • A script may stop itself, and that is a clean exit. The gesture does not block: it cancels, and the script stops at the next statement. Exit() does the same thing under another name.

"Paused" is not "stopped". A paused script is absent from GetRunningScripts, but starting it again would send it back to its first line. IsPausedScript exists for that distinction: read it before choosing between StartScript and ResumeScript.

Passing parameters to a script

What a script needs to know no longer has to be written in its text or in !global.ank. Whoever starts it hands it over at the start, in a table:

// The starter: this week's report, short version.
err = StartScript("report", {"days": 7, "mode": "short"})
if err != nil {
	Print("report not started: ", err)
}
// In report.ank: what its start handed over.
p = ScriptParams()
days = 1
if p["days"] != nil {
	days = p["days"]
}
Print("report over ", days, " days, mode ", p["mode"])

The table belongs to that run alone. ScriptParams() returns a fresh copy on every call: changing it changes nothing for the next call, nor for anyone else. Two runs started one after the other each read their own. PutShared followed by StartScript did not guarantee that: a second start that came before the first had read its key overwrote it.

Empty when nothing was passed. A script started from the panel, when the bot starts, or by StartScript(name) alone reads an empty table, never the one of whoever started it. A !global.ank function that calls ScriptParams() reads the table of the script calling it.

The types stay the ones you wrote. Numbers, texts, booleans, lists and nested tables arrive the way JsonDecode would return them: 7 stays an integer, and p["id"] == 33628068 is true. An engine object, a celestial or a coordinate, arrives as a table of its fields: pass its ID instead, or its coordinates as text. A table that contains itself is refused, like anything that is not a table.

Starting a script from outside

Outside the bot and the game, nothing reached a script. To obey a command that came from elsewhere, it had to poll in a loop. An address now starts it, with its parameters, from a Discord command, a web page or any tool that can make an HTTP request:

curl -X POST \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{"days": 7, "mode": "short"}' \
  https://your-bot/api/instances/2/scripts/report/start

The script reads the body through ScriptParams(), exactly like a table passed to StartScript. An empty body starts it without parameters, and …/report/stop stops it.

Nothing is open until you open it, and it takes three steps:

1. The key, in My account: "Generate a key and turn on", on the "Start scripts from outside" card (Remote access tab on a Windows PC, Account tab elsewhere). It is a key of its own, not the status key. "New key" makes the old one unusable, "Switch off" closes everything. 2. The script's "remote start" box, next to "run at startup", then Save. Only ticked scripts answer; it is unticked on every new or imported script. 3. The address: wherever your panel answers, on the PC, on the Cloud or through the Remote access link. The number after /instances/ is the bot's number, the one in the panel's addresses (#/bot/2/…), never its ID.

What the address answers, in short JSON:

  • 200: the script started, {"ok":true,"script":"report.ank","status":"running"}. After /stop, "status":"stopped".
  • 404: switched off, key missing or wrong, unknown bot, script missing, reserved (!global.ank and its neighbours) or not ticked. Always the same answer: the key cannot be used to list your scripts.
  • 409: the script is already running, or it is paused, and "status" says which. Stop or resume it first.
  • 400: the body is not a JSON object; 413: it is over sixteen kilobytes.
  • 429: more than thirty requests a minute, ten at once. The Retry-After header says how many seconds to wait.

Every start and every stop is written to the bot's log, with the address it came from, never the key nor the parameters. Ticking or unticking the box is written there too, with who did it.

Keep the key out of your scripts. No function reads it: IsRemoteStartEnabled() only says that it exists. A script copied from elsewhere therefore cannot leak it, as long as you do not write it in there yourself.

A Discord command

Discord does not reach your bot by itself: you need a small Discord bot of your own that receives the command and calls the address. In Python, with discord.py and aiohttp:

import os
import aiohttp
import discord
from discord import app_commands

ADDRESS = "https://your-bot/api/instances/2/scripts/report/start"
KEY = os.environ["KEPLER_KEY"]

client = discord.Client(intents=discord.Intents.default())
commands = app_commands.CommandTree(client)

@commands.command(name="report", description="Starts the bot's report")
async def report(interaction: discord.Interaction, days: int = 7, mode: str = "short"):
    async with aiohttp.ClientSession() as http:
        async with http.post(ADDRESS, json={"days": days, "mode": mode},
                             headers={"Authorization": "Bearer " + KEY}) as answer:
            await interaction.response.send_message(f"{answer.status} {await answer.text()}")

@client.event
async def on_ready():
    await commands.sync()

client.run(os.environ["DISCORD_TOKEN"])

/report days:30 then starts report.ank with {"days": 30, "mode": "short"}. Set in Discord who may type the command: whoever can type it starts the script.

Driving the other bots of the installation

A script sees the other bots of its Kepler, and can drive them: start them, stop them, start their scripts. Those of the same installation, and only those: your Kepler at home, or your instance on the Cloud. Nothing here reaches another Kepler, not even yours on another machine.

ValueHolds
BotIDan integerThe number of the script's bot, the one in the panel addresses (#/bot/2/...).
FunctionReturns
BotsCount()1: an integerThe number of bots in the installation, those beyond the licence included.
OwnBots()1: a list of botsAll of them, the script's own included, in the order of the home page.
AllBots()1: a list of botsThe same list: Kepler does not share bots between installations.
GetBotByID(number)1: a bot, or nilThe bot with that number, nil when there is none.
StartRemoteScript(address, number, key, script)1: an errorStarts a script of that bot. The address and the key stay empty.
StopRemoteScript(address, number, key, script)1: an errorStops it.

A bot returned by these functions is used like this:

FormReturns
b.GetID()1: an integerIts number.
b.GetName()1: a stringIts display name, set in its Settings.
b.GetUniverse(), b.GetLang()1: a stringIts universe and its server language, known even when it is stopped.
b.GetServerNumber()1: an integerIts server number, s152-en giving 152. Zero until it is connected.
b.GetPlayerName(), b.GetPlayerID()1: a string, an integerIts player; the last one read when it is stopped, like its card.
b.GetState()1: a stringstopped, connecting, running, sleeping, maintenance, error, or paused after PauseBot.
b.IsActive()1: a booleanWill it start again at Kepler's next launch.
b.Start()1: an errorThe Start button, with its guards. A bot stopped from the panel ("active" box unchecked) is not restarted by a script: start it from the panel. A bot that a script stopped with Stop() can be restarted by a script, until the player starts or stops it from the panel.
b.Stop()nothingThe Stop button.
b.StartScript(name, [params])1: an errorStarts one of its scripts, with an optional table.
b.StopScript(name), b.PauseScript(name), b.ResumeScript(name)1: an errorStops, suspends or resumes it.
b.IsScriptRunning(name), b.IsPausedScript(name)1: a booleanIs it running, is it paused.
b.SetScriptRunAtStart(name, on)1: an errorIts "run at startup" box.
// The conductor: every stopped bot starts again and starts its watch.
for b in OwnBots() {
	if b.GetID() == BotID {
		continue
	}
	if b.GetState() == "stopped" {
		err = b.Start()
		if err != nil {
			Print(b, " does not start: ", err)
			continue
		}
	}
	b.StartScript("night-watch", {"from": BotID})
}

A bot is named by its number, never by its identifier. A bot's identifier carries its account's e-mail address, and a script copied from elsewhere could send it out. A script sees of another bot its number, its name, its universe, its language, its state, its "active" box, its server and its player: nothing of its settings, its passwords or its proxy. Print(b) writes Bot 2 (Zenith). The number never changes, and the number of a deleted bot is never given again: an object kept too long answers "no bot #2 in this installation", never on behalf of another one.

Start has the button's guards. A bot beyond your licence, a Kepler whose update is overdue, or on the Cloud an exit address that is no longer in your lot, do not start, and the error says why, word for word like the screen. A bot already started answers "instance already started". Like the buttons, Start ticks its "active" box and Stop unticks it: Kepler's next launch follows what the script decided.

Stopping the script's own bot also stops the script, like the button: its scripts stop with it. Otherwise the script's own bot is a bot like the others, with the refusals of StartScript: a script neither restarts nor suspends itself through GetBotByID(BotID).

StartRemoteScript and StopRemoteScript carry Ninja's names, where they call another server with a key. Here, the address and the key stay empty, and the gesture is that of GetBotByID(number).StartScript(script): an address or a key is refused, rather than letting you believe another Kepler was reached, and so that your remote start key is never written into a script. The started script does not need its "remote start" box: that box only counts for the outside.

Three of Ninja's methods are missing from the object: GetServerID, the identifier in its database, which Kepler does not have; DeleteScript, which no script does on its own bot either; Publish, for lack of messaging between bots: PutShared and GetShared already share values between all the bots of the installation.

Every gesture is written to the log of the script's bot, with the number of the bot it targets: "bot started by a script", "another bot's script controlled by a script".

Apply to all my bots

The "Apply to all my bots" buttons of the screens, and the copy of the Hunter list. Each one starts from the script's bot.

FunctionReturns
ApplyAddonsToAllBots()1: an error"Apply this choice to all bots" of the browser add-ons: this bot's choice becomes everyone's.
CopyNotificationsToAllBots()1: an errorThis bot's Notifications channels, webhooks and token included, set on all the others.
SetFarmProbesEverywhere(probes)1: an errorThe number of espionage probes of every farm campaign of every bot.
CopyHunterTargets(number)1: an errorThis bot's Hunter list, copied to the bot with that number.
SetFarmProbesEverywhere(6)
err = CopyHunterTargets(2)
if err != nil {
	Print("list not copied: ", err)
}
  • Secrets do not go through the script. CopyNotificationsToAllBots copies the webhooks and the Telegram token inside the configuration, and no function reads them.
  • A bot that refuses the probes does not stop the others, like on the screen: the error names those that refused, by name and number, when another of their settings no longer passes validation. A negative number is refused, above one hundred it is brought back to one hundred.
  • The Hunter list only goes to a bot of the same universe: elsewhere, a player identifier names somebody else. Players already followed there keep their settings; the suspension and the return alert follow, the history does not.

The installation-wide settings

The four settings of Settings > General that apply to every bot. Each one is saved through the screen's path, with its bounds.

FunctionReturns
GetBotLanguage()1: a stringThe language of the interface and of the notifications, fr or en for instance. GetLang gives the game server's.
SetBotLanguage(code)1: an errorChanges it for the whole installation.
GetStartBotsOnLaunch()1: a booleanDoes Kepler start the active bots when it opens.
SetStartBotsOnLaunch(on)1: an errorTicks or unticks it, without starting anything right away.
GetSameEmailBotsDelay()2: the low and the highThe gap, in seconds, between the actions of two bots of the same e-mail address.
SetSameEmailBotsDelay(low, high)1: an errorFrom 0 to 30 seconds, the high never below the low.
GetManualModeTimeout()1: an integerThe minutes after which the bot takes the built-in browser back.
SetManualModeTimeout(minutes)1: an errorFrom 1 to 120 minutes. A session in progress keeps the delay it started with.
low, high = GetSameEmailBotsDelay()      // TWO targets
Printf("current gap: %d to %d s", low, high)
err = SetSameEmailBotsDelay(3, 8)
if err != nil {
	Print(err)
}

What stays closed to scripts. What handles a secret or the whole installation has no function: importing and exporting bots, the licence key, the update, the OGame password and two-factor authentication, proxies with credentials, creating and deleting a bot, replacing the exit address.

Knowing what the farm is doing

FunctionReturns
IsFarmSessionOngoing()1: a booleanIs a campaign working right now.
IsPausedFarmingBot()1: a booleanIs a campaign paused.
FarmingBotSessionsCount()1: an integerHow many campaigns are running.
GetFarmSessions()1: a listThe saved campaigns, those from the screen included, with their state and settings.
PauseFarmingBot()1: an errorSuspends the running campaign.
ResumeFarmingBot()1: an errorResumes it where it stopped.
AbortAllFarmingSessions()1: an errorStops everything and removes every campaign, the running one and those from the Farmer tab included.

A paused campaign makes IsFarmSessionOngoing return false: it is not working. The distinction matters — a script waiting for a campaign to end before starting something else would otherwise wait forever in front of a campaign nobody will resume.

A difference from Ninja, better read here than in game. The reference tool runs several campaigns at once; Kepler runs one at a time, because two would fight over slots and probes and nobody could tell which one emptied what. FarmingBotSessionsCount is therefore zero or one, never more: a copied script comparing it to three will never get its match.

Listing the campaigns

GetFarmSessions() returns every saved campaign, those from the Farmer tab as well as your scripts' ones, in creation order. That is what gives StartFarmSession the ID of a campaign set up on the screen, which no BuildFarmSession() ever returned.

for s in GetFarmSessions() {
    if s.Name == "night" && s.State == "idle" {
        StartFarmSession(s.ID)
    }
}

Each campaign carries:

  • ID, Name, CreatedAt;
  • State: "active" for the one the farmer runs, or will run as soon as StartFarmingBot() is called if it is off, "paused", "queued" for one waiting its turn, at the place QueueRank gives (counted as on the screen), and "idle" for one at rest. IsFarmSessionOngoing() tells whether farming is really working;
  • the zone, under the names BuildFarmSession() already returns: Origin, StartFromNearest, Range, ManualRange, SystemFrom, SystemTo, GalaxyFrom, GalaxyTo;
  • the wave: Strategy ("all", "majority" or "never", the words of SetFarmStrategy), MajorityThreshold, MajorityWaitMinutes, RaidsAsReportsArrive, AttackDelayMin, AttackDelayMax;
  • the targets: MinimumResourcesToAttack, MinimumDefensesToIgnore, MinimumMetalStorage, MinimumCrystalStorage, MinimumDeuteriumTank, MinimumPlayerRank, IgnoreActivity, MetalRatio, CrystalRatio, DeuteriumRatio;
  • the ships: NbProbes, PctCargo, FarmSpeed (0.5 to 10, like the constants of SetFarmSpeed), UsePathfinders, SmallCargosFirst, EspionageProbeRaids, SecondCargo and ThirdCargo (0 for "None");
  • the mailbox: DeleteEspionageReports, DeleteCombatReports.

Ninja's names are kept wherever they mean the same thing, AttackFromNearestPlanet and AttackFromNearestMoon included. Two are left out on purpose: FastAttacking, which does not mean the same thing there and here (see SetFastAttacking), and the RangeGalaxy, RangeFrom, RangeTo span, which a single galaxy cannot express. The ID is a text, the one StartFarmSession expects.

A campaign whose backup types were never set shows the fallback it uses, like the campaign window that opens pre-filled with it.

It asks the game nothing and goes through during manual mode. A paused campaign only reads "paused" while the bot is running: the pause lives in its memory, as for IsPausedFarmingBot().

Stopping, queueing, editing or deleting a campaign

The buttons on a row of the Farmer tab, its "⏹ Stop everything", and the farmer's slot cap. Its pace is set by a settings pair, GetFarmingBotConfigs and SetFarmingBotConfigs: see Farmer (pace).

FunctionReturns
StopFarmSession(campaign)1: an errorThe ■: stops that campaign, "" for the running one; the next one in the queue takes over.
QueueFarmSession(campaign)1: an errorThe +: puts it behind the ones waiting their turn.
EditFarmSession(campaign)1: a builderThe ✎: the saved campaign, to edit then BuildFarmSession().
DeleteFarmSession(campaign)1: an errorThe ✕: removes it from the list.
GetFarmMaxSlots()1: an integerThe farmer's slot cap, 0 for MAX.
SetFarmMaxSlots(n)1: an errorChanges it, from 0 (MAX, no cap) to 100.
StopAllFarmSessions()1: an errorThe "⏹ Stop everything": stops every campaign and empties the queue; they stay in the list.

campaign is the ID, the ID field of what BuildFarmSession() and GetFarmSessions() return; spaces around it do not count. These functions do exactly what the buttons do, by the same path, and refuse what they refuse. One refusal more: an ID the account does not have returns unknown campaign. The screen cannot point at a campaign it does not show; a script can, and silence would read as "done". None of them asks the game anything: they go through during manual mode.

Stopping a campaign is not turning the farmer off. Five neighbouring gestures:

  • StopFarmSession(""), or the ID of the running one, is "■ Stop the running campaign": its pass is cut, its progress erased - started again, it will begin at the first system - and the next one in the queue leaves at once. With nothing next, the farmer turns off. Its raids already in flight are not recalled: they come back;
  • StopFarmSession(campaign) on a campaign that is not running, paused or queued, erases its progress and takes it out of the queue; the running one carries on. It is also the way to take a campaign out of the queue;
  • StopFarmingBot() turns the farmer off: the active campaign goes back to rest, nothing takes over, and the queue is kept for the next StartFarmingBot();
  • PauseFarmingBot() suspends and keeps the progress;
  • StopAllFarmSessions() is "⏹ Stop everything": the farmer turns off, the queue empties and every campaign's progress is erased, but they all stay in the list, ready to start again from the first system. The log says how many were abandoned. AbortAllFarmingSessions() also removes them.

With no campaign running, StopFarmSession("") turns off a farmer left on to count the previous campaign's last wave, like the button; if nothing is on either, it returns no campaign to stop.

QueueFarmSession(campaign) puts a saved campaign behind the ones waiting, like the + on its row: it will leave when the previous one has finished, or at the next StartFarmingBot() if the farmer is off. A campaign already queued keeps its place, with no duplicate; a paused campaign may join. The running one is refused, this campaign is already running: it does not wait behind itself. Its place then reads in GetFarmSessions(), State at "queued" and QueueRank, and in the tab's "Queue" panel.

EditFarmSession(campaign) returns a builder filled with the saved campaign: the methods of NewFarmSession() edit it, and BuildFarmSession() saves it in its place instead of creating one, without starting or stopping it - it keeps its state, running, paused, queued or at rest. It returns the campaign as saved, with the same ID, and an error.

  • Only what the script calls changes, like the "Edit campaign" window, which only writes what was changed in it: a setting made on the screen between EditFarmSession and BuildFarmSession stays.
  • The same refusals as when creating: a value out of bounds, an unknown strategy, a campaign with no origin that does not start from the nearest. Nothing changes then.
  • The running one can be edited too, as on the screen: a threshold or a minimum loot apply from the next system or attack. The zone - origin, range, span, start from the nearest - keeps its starting value until the next launch.
  • SetOrigin does not leave start-from-nearest on a campaign that has it: SetStartFromNearest(false) does.
  • An empty or unknown ID still returns a builder, never nil; BuildFarmSession() then gives the refusal.

DeleteFarmSession(campaign) is the ✕: the campaign leaves the list, and nothing else moves. The running one is not stopped by it: as on the screen, its pass finishes with what it holds, and the farmer has no campaign at its next wake-up. For the next one in the queue to leave at once, StopFarmSession first. A campaign deleted while it was waiting is skipped from the queue quietly, and its raids stay in the loot history.

GetFarmMaxSlots() and SetFarmMaxSlots(n) read and change the cap on the "Farmer" row of Settings > Fleet slots: 0, MAX, sets no cap - the farmer goes as far as the general reserve allows -, otherwise 1 to 100. The setting is saved like the menu, applies at once and survives a restart. Outside 0 to 100, refused rather than quietly brought back.

// at night: more slots for the farmer, and the "night" campaign takes over
SetFarmMaxSlots(8)
for s in GetFarmSessions() {
    if s.Name == "night" && s.State == "idle" {
        e = EditFarmSession(s.ID)
        e.SetMinimumResourcesToAttack(500000)
        night, err = e.BuildFarmSession()
        if err != nil { LogError("edit:", err) }
        err = QueueFarmSession(night.ID)
        if err != nil { LogError("queue:", err) }
    }
}
err = StopFarmSession("")   // the running one stops, "night" leaves
if err != nil { LogError("stop:", err) }

Repatriating right now

FunctionReturns
RepatriateNow()1: an errorRuns a repatriation pass without waiting.

The worker sleeps between passes. A script that has just emptied a planet wants the resources to leave now, not at the next wake-up.

It sets nothing: destinations, thresholds and ships stay as configured in the panel. It only moves the clock forward. The worker must be on — triggering a worker that is off would do nothing, and the error says so.

Gathering everything in one place

FunctionReturns
RepatriateSetAllDestinations(celestial)1: an errorThat celestial receives, all the others feed it.

Read the name to the end: "All". The given celestial becomes the destination, and all the others become origins. The previous list of origins is REPLACED, not added to: a colony you had set aside — while building there — comes back in.

The other destinations are wiped. The settings page accepts several, and each celestial repatriates to the nearest one; this call leaves exactly one, yours. That is what the name promises, but an account with three banks has only one left after the call.

It launches nothing: RepatriateNow triggers a pass.

RepatriateSetAllDestinations("1:64:8")
RepatriateNow()

The Brain queue

FunctionReturns
ClearAllConstructionQueues()1: an errorEmpties the queue of every celestial in Queue mode.
AddItemToQueue(celestial, what, number)1: an errorAdds a line at the end of a celestial's queue.

Both write the queue that Brain reads, exactly like the Brain page does: they start nothing in the game. Brain does the building afterwards, on its pass, if it is switched on (StartBrain()).

A Kepler line is a level to reach, not an action. In the reference tool, AddItemToQueue(c, SOLARPLANT, 0) means "one more level". Here the new line aims at the next level after what is already built, under construction or already asked for in the queue, so two calls in a row do ask for two levels, and a solar plant whose level 11 is being built gets the line "solar plant 12". The current level and the construction in progress are read from the game at call time, two or three requests.

  • Building, research, lifeform: the number is ignored, except -1.
  • Ship, defense: the number is a quantity, at least one. AddItemToQueue(c, BOMBER, 0) returns an error.
  • -1, tearing down, is not supported and returns an error that says so: the queue cannot go down a level. TearDown tears down right away.
  • A lifeform item that does not belong to the celestial's species is refused: its page does not show it, so its level cannot be read.
  • What the Brain page does not offer is refused: the crawler, a mine or a research on a moon, a lifeform item on a moon. The line would be dead.
  • A ship reserved for another class is refused: the Reaper outside the General class, the Pathfinder outside the Discoverer class. The game would not build it.

A celestial that is off with an empty queue switches to Queue mode: a line in a queue nobody reads would do nothing. A celestial off that keeps a queue is refused, with nothing touched: switching it back on would also build its old lines. A celestial in AI mode is refused too: switching it to Queue would throw its plan away. Either way, that is your call to make on the page.

ClearAllConstructionQueues only empties celestials in Queue mode. The queue kept by a celestial in AI mode or switched off stays as it is, just like with the page's "Empty all queues" button.

During the built-in browser's manual mode, ClearAllConstructionQueues goes through at once: it only touches the bot's queue and asks nothing of the game. AddItemToQueue, on the other hand, waits for the mode to end, since it may have to read the celestial's level in the game.

ClearAllConstructionQueues()
c = GetCachedCelestial("1:2:3")
err = AddItemToQueue(c.GetID(), METALMINE, 0)
if err != nil { LogError("queue:", err) }
AddItemToQueue(c.GetID(), METALMINE, 0)  // one more level again
AddItemToQueue(c.GetID(), BOMBER, 5)

Finishing deliveries before the Planning switch-off

FunctionReturns
GetSupplyFinishDeliveries()1: a booleanWhether « Finish deliveries in flight before the Planning switches Brain off » is ticked.
SetSupplyFinishDeliveries(on)1: an errorTicks or unticks it, like on the Brain page, Supply panel.

A delivery that would land after Brain is switched off does not leave, ticked or not. When the Planning is about to switch Brain off, supply compares the delivery's landing, plus two minutes and twenty seconds for Brain to see it and start its construction, with the real switch-off time, random offset included. Too late, it waits for Brain to be switched back on, and the log says so once per planet: « supply held back: the planning will switch Brain off before it lands ». Without the Planning ticked, nothing changes.

The box covers what is already flying when the edge comes. Ticked, Brain switched off by the Planning keeps running only for the planets that a delivery in flight, or landed and not served yet, will pay for: it waits for the landing, starts what the cargo pays for, then switches off. Two hours at most after the edge, and half an hour at most after the last landing. Meanwhile the page shows Brain off, and supply sends nothing new. Sleep mode, manual mode, pause and stopping the bot cut it; switching Brain off by hand is never covered.

SetSupplyFinishDeliveries touches nothing else: the banks, the fed planets and the cargo types stay those of the page.

if !GetSupplyFinishDeliveries() {
	err = SetSupplyFinishDeliveries(true)
	if err != nil {
		LogWarn("supply box refused: " + err.Error())
	}
}

What the bot is doing with this account

FunctionReturns
IsStarted()1: a booleanIs the bot running for this account.
IsActive()1: a booleanWill it start it again next launch.

The two questions look alike and do not have the same answer. IsActive reads the account's CHECKBOX: an active but stopped account will come back, an inactive one will not. IsStarted reads the live state.

Seen from inside a script, IsStarted is always true — a script does not run on a stopped bot. It is useful after a long wait: the session may have closed in the meantime.

Sleep, and the Defender's interval

FunctionReturns
GetNextSleepTime()1: a time, or nilThe next time it goes to sleep.
GetNextWakeTime()1: a time, or nilThe next time it wakes.
SetDefenderCheckInterval(min, max)1: an errorThe round's interval, in seconds.
SetDefenderCheckOrigin(n)1: an errorWhere the round looks from: 1 a random celestial, 2 the home planet, 3 the last celestial visited, 4 a random moon.
TriggerFleetSave()1: an errorSends the fleet out now, using the sleep-mode settings.

Both times are the ones that will actually happen, random offset included. The bot shifts its bedtime by a few minutes so it does not shut down on the round second every evening; a script trusting the time typed into the panel would get cut off mid-gesture.

end = GetNextSleepTime()
if end != nil && end.Sub(Now()).Minutes() < 10 {
	LogInfo("the account sleeps soon, not starting the campaign")
	return
}

nil means something: sleep is not automatic, or the session is not open. That is why these two return a pointer rather than a date — a zero date would read as year 1, and a script comparing times would see a bedtime already past.

SetDefenderCheckInterval takes TWO bounds, in seconds, and the bot draws at random between them on every round: a fixed interval is recognisable from the other side, which is the whole point of having two. The setting is saved, like the fields in the panel. A bound that is zero or the wrong way round is refused rather than silently corrected.

TriggerFleetSave sends the fleet out now, using the celestials ticked in sleep mode, their destinations and their splitting. It sets nothing: a script that wants to send something else composes its own flight with SendFleet.

It works even when sleep mode is off, and that is deliberate. Fleet save is configured under sleep mode, but whoever does not use sleep mode is precisely the one the gesture serves most.

It waits until the end. Several celestials splitting their fleets take tens of minutes; the script gets control back once everything has left, which is the only way to write "save the fleet THEN shut everything down". Stopping the script stops the fleet save.

The error is raised only if NOTHING left - closed session, no celestial ticked, a version without fleet save. A partial departure does not raise it: it goes to the log and to a full-screen warning, just as when the button is clicked, because it is the player who can do something about it, not the script. The reference documentation returns nothing at all; a TriggerFleetSave() copied as-is therefore works here too.

err = TriggerFleetSave()
if err != nil {
	LogWarn("nothing left: " + err.Error())
}

The Fleet Save return time

FunctionReturns
GetFleetSaveReturn()1: a structureThe night fleet save's return time: AtWake, WakeFrom, WakeTo, From, To, From2, To2.
SetFleetSaveReturnAtWake(on, from, to)1: an errorTicks or unticks « Return at wake-up » and sets its minutes after waking up.
SetFleetSaveReturnWindow(window, from, to)1: an errorThe clock window of a sleep window, 1 or 2: "08:00", "08:30".

Returning at wake-up means coming back between two delays after the night's wake-up, offset included: SetFleetSaveReturnAtWake(true, 2, 10) brings the fleet back between two and ten minutes after the bot has woken up. These are the two fields of the Sleep mode page, under the box. Minutes go from 0 to 1440, the second larger than the first; unticked, the box keeps its minutes for next time.

The clock window applies when the box is unticked, and to a fleet save with no sleep in progress, TriggerFleetSave included, even ticked: there is no wake-up to aim at then. Window 2 belongs to the schedule's second sleep window; SetFleetSaveReturnWindow(2, "", "") clears it, and it falls back to the first. An end before the start crosses midnight: "23:30" and "00:15" make forty-five minutes.

A window longer than three hours is saved, and reported. The bot takes the cheapest flight that lands in it, often the slowest, and the fleet may come back as late as its end: "15:45" and "13:55" make twenty-two hours and ten minutes. The function returns nil, and a notice goes to the script console and to the bot's log, as on the page. An unreadable time, minutes in the wrong order or a window other than 1 and 2 are refused, and nothing changes.

r = GetFleetSaveReturn()
if !r.AtWake {
	err = SetFleetSaveReturnAtWake(true, 2, 10)
	if err != nil {
		LogWarn("return at wake-up refused: " + err.Error())
	}
}
Print("fleet save without sleep: back between", r.From, "and", r.To)

The Colonizer settings

FunctionReturns
GetColonizerSettings()1: a structureEvery setting of the Colonizer page: Origin, OriginIsHome, Galaxy, SystemFrom, SystemTo, Positions, MinFieldsOn, MinFields, MinTempOn, MinTemp, MaxTempOn, MaxTemp, SystemDelayMin, SystemDelayMax, ArrivalGapMin, ArrivalGapMax, MaxSlots.
SetColonizerOrigin(celestial)1: an errorThe planet the colony ships leave from, or "home" to follow the home planet.
SetColonizerRange(galaxy, from, to)1: an errorThe galaxy and the range of systems to search.
SetColonizerPositions(positions)1: an errorThe positions to colonize in each system: [4, 5, 6].
SetColonizerMinFields(on, fields)1: an errorThe « Minimum fields » box and its number.
SetColonizerMinTemperature(on, t)1: an errorThe « Minimum temperature » box and its value.
SetColonizerMaxTemperature(on, t)1: an errorThe « Maximum temperature » box and its value.
SetColonizerSystemDelay(min, max)1: an errorDelay between two systems, in milliseconds.
SetColonizerArrivalGap(min, max)1: an errorDelay between two arrivals, in seconds.
SetColonizerMaxSlots(n)1: an errorThe Colonizer's slot cap, from 0 (no cap) to 100.

Each function sets one setting of the Colonizer page, as if you had changed it and saved: it applies at once and survives a restart. The switch is still StartColonizerBot and StopColonizerBot, and the slot cap is the Colonizer's one under Settings > Fleet slots.

A box keeps its number. SetColonizerMinFields(false, 200) unticks « Minimum fields » and keeps 200 for the day you tick it again, as on the page. A colony that misses a ticked condition is given up straight away, so the next ship can colonize in turn: two ticked temperatures that contradict each other are therefore refused, since no planet would meet them.

The limits are the page's, and going past them is refused, not brought back: positions from 1 to 15, systems from 1 with the first before the second, a delay between two systems of at least 200 ms, between two arrivals from 30 to 180 s. An empty list of positions is refused while the Colonizer is active. The origin is a planet of the account: a moon, which does not build colony ships, is refused, as is a position that is not yours. With "home", the origin follows the home planet set under Settings > General, and OriginIsHome is true.

s = GetColonizerSettings()
if s.ArrivalGapMax < 90 {
	err = SetColonizerArrivalGap(60, 90)
	if err != nil {
		LogWarn("delay between two arrivals refused: " + err.Error())
	}
}
SetColonizerOrigin("home")
SetColonizerPositions([4, 5, 6, 10, 11, 12])
StartColonizerBot()

Settings as tables: Get…Configs and Set…Configs

FunctionReturns
GetDefenderConfigs(celestial)1: a tableThe settings of the Defence page. With a celestial, its « Evacuation per planet » line.
SetDefenderConfigs(celestial, table)1: an errorSets the given fields. Without a celestial, those of the page: SetDefenderConfigs(table).
GetColonizerConfigs()1: a tableThe Colonizer page.
SetColonizerConfigs(table)1: an errorSets the given fields.
GetDiscoveryConfigs()1: a tableThe Discovery page.
SetDiscoveryConfigs(table)1: an errorSets the given fields.
GetBrainConfigs(celestial)1: a tableThe general settings of the Brain page. With a celestial, its card: mode, queue, targets, boxes.
SetBrainConfigs(celestial, table)1: an errorSets the given fields. Without a celestial, those at the top of the page: SetBrainConfigs(table).
GetSupplyConfigs()1: a tableThe Supply panel of the Brain page.
SetSupplyConfigs(table)1: an errorSets the given fields.
GetSupplyBanks()1: a listThe Supply banks, like GetSupplyConfigs().Banks.
SetSupplyBanks(celestials)1: an errorReplaces them, like SetSupplyConfigs({"Banks": celestials}).
GetScannerConfigs()1: a tableThe Scanner page.
SetScannerConfigs(table)1: an errorSets the given fields.
GetTimerConfigs()1: a tableThe Timer watch page.
SetTimerConfigs(table)1: an errorSets the given fields.
GetColonyWatchConfigs()1: a tableThe New colony detection page.
SetColonyWatchConfigs(table)1: an errorSets the given fields.
GetMilitaryDebrisConfigs()1: a tableThe DF detection page.
SetMilitaryDebrisConfigs(table)1: an errorSets the given fields.
GetHunterConfigs()1: a tableThe Hunter settings: rate and « Espionage on demand ».
SetHunterConfigs(table)1: an errorSets the given fields.
GetFarmingBotConfigs()1: a tableThe "Farmer pace" panel of the Farmer tab, and its slot cap.
SetFarmingBotConfigs(table)1: an errorSets the given fields.

Get returns a worker's whole screen as a table, one field per setting, named as in the tables below. It is the model of Ninja's GetExpeditionsConfigs: read, change a field, hand the table back.

Set only changes the fields you give it, and only when they differ from what is saved. cfg = GetTimerConfigs(), then cfg.MapHours = 2, then SetTimerConfigs(cfg) only touches the galaxy survey, even if the player changed something else on the screen between the two calls. A table written by hand works too: SetTimerConfigs({"MapHours": 2}).

It is the screen's save. The changed fields go in one write, apply at once and survive a restart. The screen's refusals apply too: a tool switched on with no channel at all to warn is refused, with the page's sentence. The switch is not in the table: it stays StartWorker and StopWorker.

Nothing is fixed silently. An unknown field, a wrong type or a value out of bounds gets the whole Set refused: nothing is written, and the error names the field, for example SetTimerConfigs: MapHours is 30, out of its bounds: the screen would save it as 24. The bounds are the ones the bot keeps for the screen; a table gives them for each field. A minimum above its maximum is refused too, as is a value that would move another one: setting IntervalMin above the saved IntervalMax needs both.

The values. A number is an integer, a box is true or false, a choice is an English word. A celestial is written as everywhere else in the API: a planet or a moon of GetCachedPlanets(), a coordinate, "1:2:3" or "M:1:2:3". It must belong to the account, as in the screen's menus; Get returns it as a coordinate, and nil for none. A list is handled as a list (cfg.Banks += p), a resources table is changed in place (cfg.BankReserveMoon.Deuterium = 0), and its missing keys keep their value.

The names are a contract: they will not change. Ninja's are used where they exist (CheckIntervalMin, Origin, SystemFrom). A worker's slot cap, under Settings > Fleet slots, is the MaxSlots field of its table.

cfg = GetHunterConfigs()
Print(cfg)
cfg.CheckIntervalMin = 300
cfg.CheckIntervalMax = 600
err = SetHunterConfigs(cfg)
if err != nil {
	LogWarn("setting refused: " + err.Error())
}

Defence

GetDefenderConfigs(), the Defence page:

FieldTypeBoundsOn screen
CheckIntervalMin, CheckIntervalMaxinteger, seconds10 at least, the first before the secondCheck every … to …
CheckOrigin"random", "moon", "home", "last" or a celestial1 to 4 read as SetDefenderCheckOriginWhere the bot looks from to see whether it is attacked
EvacuationSpeedinteger, %10 to 100, in steps of tenEvacuation speed
DeuteriumToLeaveinteger0 or moreDeuterium left on site
DodgeLeadMin, DodgeLeadMaxinteger, seconds0 or more, the first before the secondHow long before impact to dodge
RecallEnabledbooleanRecall the fleet after the attack
RecallMin, RecallMaxinteger, seconds0 or more, the first before the secondits two numbers
DumpIntoDefencebooleanSpend what could not be saved on defence
NotifyDesktopbooleanDesktop notification
PlaySoundbooleanPlay a sound
NotifySmallFleetsbooleanAlso report small fleets
SmallFleetPercentinteger, %1 to 100A fleet is small below … %
SpyAttackersbooleanProbe the origin of the raid
BuildABMbooleanBuild anti-ballistic missiles
MessagesEnabledbooleanSend a message
Messageslist of stringsthe messages, one per line
Whitelistlist of integersplayer ids, 1 or moreWhitelist

GetDefenderConfigs(celestial), its line of the « Evacuation per planet » table:

FieldTypeBoundsOn screen
Mode"dangerous", "always", "never"Dangerous, Always, Never
Destinationa celestial, or nilof the accountDestination; nil lets the bot choose
Debrisbooleanon a moon onlyDebris field

A celestial missing from the table reads the way the Defender handles it: "dangerous", no destination. A planet's table has no Debris field.

Colonizer

FieldTypeBoundsOn screen
Origina planet, "home" or nilof the account, never a moon; not nil while the Colonizer is onOrigin; "home" follows the home planet
Galaxyinteger1 or moreGalaxy
SystemFrom, SystemTointeger1 or more, the first before the secondSystems … to …
Positionslist of integers1 to 15, sorted without duplicates; not empty while the Colonizer is onPositions
MinFieldsOn, MinFieldsboolean, integer0 or moreMinimum fields
MinTempOn, MinTempboolean, integerMinimum temperature
MaxTempOn, MaxTempboolean, integerboth ticked, the minimum not above the maximumMaximum temperature
SystemDelayMin, SystemDelayMaxinteger, ms200 at least, the first before the secondDelay between two systems
ArrivalGapMin, ArrivalGapMaxinteger, seconds30 to 180, the first before the secondDelay between two arrivals
MaxSlotsinteger0 (no cap) to 100Settings > Fleet slots, Colonizer

These are the fields of GetColonizerSettings, with one difference: an origin that follows the home planet reads "home" here, not OriginIsHome.

Discovery

FieldTypeBoundsOn screen
StopAtArtifactCapbooleanStop when the artefact cap is reached
SystemDelayMin, SystemDelayMaxinteger, ms200 at least, the first before the secondDelay between two systems
SendDelayMin, SendDelayMaxinteger, ms200 at least, the first before the secondDelay before the system's button
Originslist of celestialsof the account, planets and moons; not empty while Discovery is onStarting points
Radiusinteger, systems0 to 100Radius
Strategy"all", "majority", "never"Strategy: wait for all, for the majority, never wait
ReturnDelayMin, ReturnDelayMaxinteger, seconds0 or more, the first before the secondDelay before sending again after a return
MaxSlotsinteger0 (no cap) to 100Settings > Fleet slots, Discovery

Brain

GetBrainConfigs(), the top of the page:

FieldTypeBoundsOn screen
ResourceCheckMin, ResourceCheckMaxinteger, minutes20 to 240, the first before the secondCheck of a short treasury
PauseAfterBuildinteger, %0 to 5Pause after a build

GetBrainConfigs(celestial), its card. A celestial with no card reads like a new card of the screen: off, empty queue, finished lines removed.

FieldTypeBoundsOn screen
Mode"off", "queue", "ai"Off, Queue, AI; "ai" on a moon is its moon AI
Queuelist of linessee belowthe queue of the Queue mode
StrictOrderbooleannot with AnyOrderSingle queue: one queue at a time
AnyOrderbooleannot with StrictOrderStart whatever can be started
RemoveDonebooleanRemove finished lines from the queue
Targetslist of targetsplanet onlythe targets of the AI mode
Robotics, Nanitesbooleanplanet onlyAllow the robotics factory, the nanite factory
Fusion, Satellitesbooleanplanet onlyFusion reactors, solar satellites
MoonBase, MoonRoboticsinteger1 to 20, moon onlyLunar base, robotics factory aimed at
MoonPhalanxinteger0 to 20, moon onlySensor phalanx aimed at

A Queue line is a table: ID, the item; Level, the level aimed at, or the number for a ship or a defence; Mode, "build" (the default), "reach" (have Level of them, ships and defences) or "energy" (solar satellites of a planet, Level being the cap, 0 for none); Plus, one level above the current one, from 0 to 50, buildings and research; Done, what is already ordered; Auto, a line the bot added as a requirement. A Targets entry carries ID, Level and Done. The given list REPLACES the queue or the targets. An item this celestial's queue cannot handle is refused, as the screen's catalogue does not offer it.

p = GetCachedPlanets()[0]
err = SetBrainConfigs(p, {"Mode": "queue", "Queue": [
	{"ID": METALMINE, "Level": 20},
	{"ID": ROCKETLAUNCHER, "Level": 200, "Mode": "reach"},
]})
if err != nil {
	LogWarn("queue refused: " + err.Error())
}
for l in GetBrainConfigs(p).Queue {
	Print(l.ID, l.Level, l.Mode, l.Done)
}

Supply

FieldTypeBoundsOn screen
Bankslist of celestialsof the accountBanks
Targetslist of celestialsof the accountPlanets and moons to supply
AdvanceHoursinteger, hours1 to 168Advance to deliver
LeadMinutesinteger, minutes5 to 1440Deliver how long before the end
MinDeliveryinteger0 or moreMinimum delivery
BanksPerDeliveryinteger2 to 10Banks per delivery, at most
Cargo"LargeCargo", "SmallCargo", "Pathfinder"Cargo ship
Cargo2, Cargo3the same, or ""different from the first and from each otherSecond and third type
RoundUpbooleanRound deliveries up
FinishDeliveriesbooleanFinish ongoing deliveries before the Planning switches off
BankReservePlanet, BankReserveMoonresources table0 or moreKeep on a planet bank, a moon bank
TargetReservePlanet, TargetReserveMoonresources table0 or moreKeep on a planet destination, a moon destination
MaxSlotsinteger0 (no cap) to 100Settings > Fleet slots, Supply

A resources table carries Metal, Crystal and Deuterium; NewResources(m, c, d) is accepted too.

Scanner

FieldTypeBoundsOn screen
FrequencyHoursinteger, hours1 or moreScan the universe every
DelayMin, DelayMaxinteger, ms200 to 60000, the first before the secondWait between two systems
Froma celestial, or nilof the accountLook from; nil: the active planet

Timer watch

FieldTypeBoundsOn screen
Playerslist of stringsWatched players, one per line
IntervalMin, IntervalMaxinteger, seconds30 at least, the second above the firstBetween two watch rounds
PositionDelayMin, PositionDelayMaxinteger, ms200 at least, the first before the secondBetween two watched positions
ReminderMinutesinteger, minutes0 or more; 0: the first alert onlyInactivity reminder
MapHoursinteger, hours1 to 24Refresh the galaxy every
SystemDelayMin, SystemDelayMaxinteger, ms200 at least, the first before the secondBetween two surveyed systems
GalaxyPauseMin, GalaxyPauseMaxinteger, ms0 or more, the second above the firstPause when moving to the next galaxy
Webhooks, Mentionslist of stringsWhere to warn: Discord webhooks, mentions
TelegrambooleanWhere to warn: Telegram

New colony detection

FieldTypeBoundsOn screen
Coordinateslist of strings"1:69" or "[1:69:8]", readable by the toolWatched coordinates
Radiusinteger, systems0 to 100; 0: the system aloneRadius around each position
NotifyDestroyedbooleanWarn as soon as a planet is destroyed
MaxMilitaryRankinteger1 to 1000Minimum military rank to notify
SystemDelayMin, SystemDelayMaxinteger, ms200 at least, the first before the secondBetween two systems
CyclePauseMin, CyclePauseMaxinteger, minutes1 at least, the second above the firstPause between two full passes
Webhooks, Mentions, TelegramWhere to warn

DF detection

FieldTypeBoundsOn screen
MinPointsLostinteger1 or moreMinimum military points lost
MinDebrisinteger1 or moreMinimum debris field to notify
MaxRankinteger100 to 1000Watched ranking
IntervalMin, IntervalMaxinteger, seconds15 at least, the first before the secondBetween two ranking readings
PageDelayMin, PageDelayMaxinteger, ms200 at least, the second above the firstBetween two ranking pages
PositionDelayMin, PositionDelayMaxinteger, ms200 at least, the second above the firstBetween two checked systems
MapHoursinteger, hours1 to 24Refresh the galaxy every
SystemDelayMin, SystemDelayMaxinteger, ms200 at least, the first before the secondBetween two surveyed systems
Webhooks, Mentions, TelegramWhere to warn

Hunter

FieldTypeBoundsOn screen
CheckIntervalMin, CheckIntervalMaxinteger, seconds60 at least, the first before the secondCheck every (in minutes on screen)
Origina celestial, or nilof the accountStarting planet; nil: the active planet
SpyDelayMin, SpyDelayMaxinteger, ms200 at least, the first before the secondWait between two moves
MaxSlotsinteger0 (no cap) to 100Settings > Fleet slots, Hunter

The list of followed players stays with AddHunterTarget and its neighbours.

Farmer (pace)

FieldTypeBoundsOn screen
SystemDelayMin, SystemDelayMaxinteger, ms300 at least, the first before the secondMoving from one system to the next
SpyDelayMin, SpyDelayMaxinteger, ms300 at least, the first before the secondBetween two espionages
MaxSlotsinteger0 (no cap) to 100Settings > Fleet slots, Farmer; the same as SetFarmMaxSlots

Both paces apply to every campaign. Below 300 ms the screen raises the value without a word; a script is refused. Campaigns stay with NewFarmSession, EditFarmSession and their neighbours.

The Timer watch, player by player

FunctionReturns
GetTimerTargets()1: a listThe watched players, like GetTimerConfigs().Players.
AddTimerTarget(player)1: an errorAdds a player, by name or by id.
RemoveTimerTarget(player)1: an errorRemoves them from the list.
ValueCarries
OnTimerTargetIdleCha channel of changesThe watched players who have just gone « full timer ».

It is the « Watched players » list of the Timer watch page, set the way « Save » sets it. A name the surveys know takes their exact spelling; an unknown name is accepted as on the screen, and the Timer looks for it every round. A player already in the list, ignoring case, does not go in twice; removing one who is not there returns an error, so that a typo shows.

OnTimerTargetIdleCh fires with the « Timer player » alert: when every known position of a player has been read and none is active. Never on an incomplete reading, never for a reminder. The event carries PlayerID, PlayerName, Timer (the shortest counter shown, from 16 to 59, or 0 when no position shows one), Checked (the planets and moons read) and Positions (their known planets and moons). The channel has nothing to carry while the Timer watch is off: it needs a notification channel, its own or the Settings' ones. The Hunter has OnHunterTargetIdleCh, on few targets.

AddTimerTarget("Kcwin")
for {
	e = <-OnTimerTargetIdleCh
	if e.PlayerID == 0 { break }
	LogInfo(e.PlayerName, "is timer, shortest counter:", e.Timer)
}

The messages of the « Send an in-game message » mission

FunctionReturns
GetRewardsMessages()1: a listThe texts the bot draws at random for the Rewards mission « Send an in-game message ».
SetRewardsMessages(messages)1: an errorReplaces the list, one message per element: ["sry for event", "event"]. An empty list brings back the default one.

This is the list of the Rewards and boosters page, Missions tab, one message per line: the function sets it as if you had changed it and saved, it applies at once and survives a restart. At each send, the bot draws one at random. With no list set, it draws among ".", "event", "rewards", "hi" and "Hi", and that is the list GetRewardsMessages returns.

The limits are the page's, and going past them is refused, not cut: twenty messages at most, a hundred characters at most each, one message per element with no line break. Empty elements are ignored, spaces at the edges removed. A refusal changes nothing.

The recipient is not a setting. It is first an inactive player, i or I, that the bot's map has seen in the last seven days, drawn at random; with no inactive known, a player ranked from 201st to 300th, or at the bottom of the highscore in a small universe, an inactive on the page coming before the others. Never yourself nor a member of your alliance, never a player on vacation, banned or an administrator when the map or the highscore says so.

err = SetRewardsMessages(["sry for event", "event", "rewards"])
if err != nil {
	LogWarn("messages refused: " + err.Error())
}
Print(GetRewardsMessages())

Pausing and stopping are not the same thing, and that is what justifies two functions rather than one. PauseFarmingBot keeps the progress: resuming picks up at the system reached. StopFarmingBot erases it: the campaign will start again from the first. On a three-hundred-system campaign, that is a night's work.

if IsFarmSessionOngoing() {
	PauseFarmingBot()          // giving the slots back to the Defender
	SleepMin(30)
	ResumeFarmingBot()         // and back to where we left off
}

ResumeFarmingBot finds which one on its own: only one campaign at a time can be paused. With none paused it returns an error rather than starting whichever it finds - starting it would send it back to the first system, which is exactly what we were avoiding.

AbortAllFarmingSessions is the "start from scratch" gesture, and it works exactly as in Ninja: it removes every campaign, whatever its state - running, paused, queued or finished -, the ones your scripts composed as well as the ones from the Farmer tab. A script that aborts in the evening and composes again in the morning from the celestial where its fleet spent the night no longer finds yesterday's campaigns under the new ones.

AbortAllFarmingSessions()   // in the evening: nothing runs, nothing from yesterday

During the built-in browser's manual mode, AbortAllFarmingSessions goes through at once: it only removes campaigns and asks nothing of the game.

The ones from the Farmer tab go too, even the one running. A Planning that named a removed campaign says so at its next edge, as for a campaign deleted by hand: it keeps the one running if there is one, and otherwise leaves farming off rather than switching it on with nothing to do. The screen's "Stop everything" button removes nothing: that is StopAllFarmSessions().

Raids already in flight are not recalled: they come home normally, and nothing relaunches a removed campaign - not their return, not the queue, not a restart of the bot, not a Kepler tab left open since the day before, whatever its page.

The daily loot history is kept per account, not per campaign: removing a campaign erases nothing from it. The loot of a wave still flying when you abort goes into it like that of waves that are back but not yet counted: the next time farming runs, once its combat reports are in, provided the bot has not restarted in between. It is no longer credited to any campaign, since they are removed. The same goes for "Stop everything", which resets every campaign.

Switched off by hand, farming likewise keeps its wave in flight for its next run. Switched off by the Planning, it counts it the same night: it keeps running without a campaign - nothing leaves, no campaign resumes - until its combat reports are read, or given up as not found, then switches itself off. IsRunningFarmingBot() answers true during that time, and the Planning's next start edge resumes as usual.

Call StartFarmingBot() after composing the day's campaigns: right after the abort there is nothing left to start and it returns an error; and if a campaign was composed in the meantime, on screen for instance, it starts that one and the new ones queue up behind it.