Demo: all bots, planets and logs are made up. You can look at everything, but not save or play. End demo

Script library

267 commands for HIVE scripts (JavaScript) – each with a usage example.
All times are this PC's local time (UTC). Now: --:--:--

Getting started

Basics

Scripts are JavaScript and run per bot right inside HIVE – over the bot's existing game connection. All commands are available globally. Game requests are throttled automatically (at least 0.3 s apart) so the account doesn't stand out.

Stop and pause work at any time, even in the middle of a loop. Game API errors can be caught with try { … } catch (e) { LogError(e.message) }.

Own planets/moons can be given everywhere as an object from GetPlanets(), as an ID, as a name or as a coordinate: "1:16:4" = planet, "1:16:4:3" = moon.

Irreversible or externally visible actions need the word "BESTÄTIGT" as their last argument – without it nothing happens. Signing in, signing out and captchas aren't available to scripts because they would end the running game session. Scripts have no access to files, the network or the PC.

Constants
MISSION.ATTACK, ACS_ATTACK, TRANSPORT, DEPLOY, ACS_DEFEND, SPY, COLONIZE, HARVEST, DESTROY, MISSILE_ATTACK, EXPEDITION, TRADE, DISCOVERY
CELESTIAL.PLANET (1), DEBRIS (2), MOON (3), DEEPSPACE (4)
SHIP.SmallCargo, LargeCargo, LightFighter, HeavyFighter, Cruiser, Battleship, Battlecruiser, Bomber, Destroyer, Deathstar, ColonyShip, Recycler, EspionageProbe, SolarSatellite, Crawler, Reaper, Pathfinder
DEFENCE.RocketLauncher, LightLaser, HeavyLaser, GaussCannon, IonCannon, PlasmaTurret, SmallShieldDome, LargeShieldDome, AntiBallisticMissiles, InterplanetaryMissiles
BUILDING.MetalMine, CrystalMine, DeuteriumSynthesizer, SolarPlant, FusionReactor, MetalStorage, CrystalStorage, DeuteriumTank, RoboticsFactory, Shipyard, ResearchLab, NaniteFactory, Terraformer, SpaceDock, LunarBase, SensorPhalanx, JumpGate, …
RESEARCH.EspionageTechnology, ComputerTechnology, WeaponsTechnology, …, Astrophysics, IntergalacticResearchNetwork, GravitonTechnology
LF_BUILDING.ResidentialSector, BiosphereFarm, …   LF_RESEARCH.IntergalacticEnvoys, HighPerformanceExtractors, …
CHARACTER_CLASS.NONE, COLLECTOR, GENERAL, DISCOVERER   ALLIANCE_CLASS.NONE, WARRIOR, TRADER, RESEARCHER
FEATURE.Defender, Expeditions, AutoFarm, Harvest, SleepMode, Colonize, AutoDiscovery, BrainAutoMine, BrainAutoResearch, BrainAutoRepatriate, BrainAutobuildCargo, …
MESSAGE_TAB.ESPIONAGE (20), COMBAT (21), EXPEDITIONS (22), TRANSPORT (23), OTHER (24)
Statt der Konstanten gehen auch die Zahlen-IDs oder Namen als Text (z. B. "LargeCargo").
Example script: expedition waves
// Example: expedition waves from the home planet
const LARGE_CARGO = 4000

while (true) {
    if (IsSleeping()) { SleepMin(5); continue }

    const home = GetHomeWorld()
    const slots = GetSlots()
    const free = Math.min(slots.ExpTotal - slots.ExpInUse, slots.Total - slots.InUse)

    for (let i = 0; i < free; i++) {
        const system = home.Coordinate.System + RandomInt(-1, 1)
        const target = home.Coordinate.Galaxy + ":" + system + ":16"
        const fleet = SendFleet(home, { LargeCargo: LARGE_CARGO, Pathfinder: 1 }, target, MISSION.EXPEDITION)
        if (!fleet) { LogWarn("No ships left"); break }
        SleepRandSec(2, 5)
    }
    SleepRandSec(300, 600)
}

Basics

Log 5 LogInfo · LogWarn · LogError · LogDebug · Print
LogInfo(...werte)
Writes a line to the script log (right). Several values are joined with spaces, objects are written as JSON.
Returns –
const s = GetSlots()
LogInfo("Fleet slots:", s.InUse, "/", s.Total)
LogWarn(...werte)
Like LogInfo, as a warning (orange) – for things that need attention but aren't errors.
Returns –
if (GetShips(GetHomeWorld()).ColonyShip === 0)
    LogWarn("No colony ship left on the home planet")
LogError(...werte)
Like LogInfo, as an error (red). Typically in a catch block.
Returns –
try {
    SendFleet(home, { LargeCargo: 100 }, "1:16:16", MISSION.EXPEDITION)
} catch (e) {
    LogError("Sending failed:", e.message)
}
LogDebug(...werte)
Like LogInfo, as a detail line (grey) – for intermediate values while developing.
Returns –
const fleets = GetFleets()
LogDebug("Raw data of the first fleet:", fleets[0])
Print(...werte)
Short form of LogInfo.
Returns –
Print("Script", ScriptName, "started")
Waiting & flow 6 Sleep · SleepSec · SleepMin · SleepRandSec · Exit · IsSleeping
Sleep(millisekunden)
Waits the given time in milliseconds. Stop and pause also work while waiting.
Returns –
for (const p of GetPlanets()) {
    LogInfo(p.Name, GetResources(p).Metal)
    Sleep(1500)   // 1.5 s between the requests
}
SleepSec(sekunden)
Waits the given number of seconds.
Returns –
while (IsUnderAttack()) {
    LogWarn("Attack in progress – waiting")
    SleepSec(30)
}
SleepMin(minuten)
Waits the given number of minutes. Ideal as a pause at the end of an endless loop.
Returns –
while (true) {
    BuyOfferOfTheDay()
    SleepMin(60)
}
SleepRandSec(min, max)
Waits a random time between min and max seconds – looks more human than fixed pauses.
Returns –
for (let i = 0; i < 3; i++) {
    SendFleet(home, { LargeCargo: 2000 }, "1:16:16", MISSION.EXPEDITION)
    SleepRandSec(3, 8)
}
Exit()
Ends the script right away (regularly, not an error). OnExit() still runs afterwards.
Returns –
if (IsVacationMode()) {
    LogInfo("Vacation mode active – nothing to do")
    Exit()
}
IsSleeping()
Whether the bot is sleeping according to the sleep plan. Scripts keep running during sleep – decide for yourself with this.
Returns true | false
while (true) {
    if (IsSleeping()) { SleepMin(10); continue }
    // … the actual work …
    SleepMin(5)
}
Script context 4 OnExit · args · ScriptName · _shared
function OnExit() { … }
A function you define yourself: runs once when the script ends – also after “stop” (max. 15 s). For cleaning up.
Returns –
StopModule("Expeditions")      // module off while the script runs

function OnExit() {
    StartModule("Expeditions")  // on again at the end
}
args
Start parameters another script passed via StartScript(name, args); otherwise null.
Returns anything | null
// started with StartScript("Transport", { target: "1:20:8", amount: 500 })
const target = args ? args.target : "1:16:4"
const amount = args ? args.amount : 100
ScriptName / InstanceName
Name of this script or of the bot it runs on.
Returns Text
LogInfo(ScriptName + " runs on " + InstanceName)
Skript „_shared“
Shared code: a script named “_shared” runs automatically before every other script of the same bot. Helper functions and constants several scripts need live in one place this way. Errors in it show up in the log as “error in _shared, line …”.
Returns –
// script “_shared”:
function ToMsu(r) { return r.Metal + r.Crystal * 1.5 + r.Deuterium * 3 }

// any other script of this bot:
LogInfo("MSU: " + FormatNumber(ToMsu(GetResources(GetHomeWorld()))))
Formatting & coordinates 5 FormatNumber · FormatDuration · FormatTime · ParseCoord · FormatCoord
FormatNumber(zahl)
Number in English format with thousands commas (1,366,412).
Returns Text
LogInfo("Metal:", FormatNumber(GetResources(GetHomeWorld()).Metal))   // Metal: 1,366,412
FormatDuration(sekunden)
Formats seconds as "hh:mm:ss" (with days from 24 h).
Returns Text
for (const f of GetFleets())
    LogInfo("Fleet", f.ID, "back in", FormatDuration(f.BackIn || f.ArriveIn))
FormatTime(zeitstempel | isoText, format?)
Timestamp or ISO time as local time (English format: today "HH:mm:ss", otherwise "yyyy-MM-dd HH:mm:ss" – or a format of your own).
Returns Text
const r = LatestReturn(MISSION.EXPEDITION)
LogInfo("Last expedition back at", FormatTime(r.At))
ParseCoord(koordinate)
Splits "g:s:p" or "g:s:p:type" into an object. Without a type: position 16 = deep space, otherwise planet. No game request.
Returns { Galaxy, System, Position, Type }
const c = ParseCoord("2:150:8")
LogInfo("Galaxy", c.Galaxy, "system", c.System)
FormatCoord(koordinate)
Turns a coordinate or celestial object into the text "g:s:p".
Returns Text
const home = GetHomeWorld()
const target = FormatCoord({ Galaxy: home.Coordinate.Galaxy, System: home.Coordinate.System + 1, Position: 16 })
// target = "1:17:16"
Random 3 RandomInt · DailyRandom · DailyRandomTime
RandomInt(min, max)
Random whole number from min to max (both included).
Returns number
const home = GetHomeWorld()
const system = home.Coordinate.System + RandomInt(-2, 2)
const target = home.Coordinate.Galaxy + ":" + system + ":16"
DailyRandom(min, max, salt?)
Random number that stays the same all day and changes daily – ideal for times fixed for the day but different every day. Without salt different per script.
Returns number
// a different offset of 0–15 minutes every day, but fixed for the day
const offset = DailyRandom(0, 900)
SleepUntil(NextTimeAt("06:00") + offset)
DailyRandomTime("von", "bis", salt?)
Random time of day, fixed for the day, inside a window (also across midnight).
Returns "HH:MM:SS"
const wakeUp = DailyRandomTime("06:10", "06:40")
LogInfo("Return today at", wakeUp)
FleetSave(GetHomeWorld(), wakeUp)

Time

Times & timestamps 5 Timestamp · TimeOfDay · NextTimeAt · TimeAt · IsTimeBetween
Timestamp()
Current time as a Unix timestamp in seconds.
Returns number
const start = Timestamp()
// … work …
LogInfo("Took:", FormatDuration(Timestamp() - start))
TimeOfDay()
Current local time as "HH:MM:SS".
Returns Text
LogInfo("It is", TimeOfDay())
NextTimeAt("HH:MM[:SS]")
Timestamp of the next time a time of day comes (today, otherwise tomorrow).
Returns timestamp
const target = NextTimeAt("07:00")
LogInfo("Still", FormatDuration(target - Timestamp()), "until 07:00")
TimeAt("HH:MM[:SS]", tagVersatz?)
Timestamp of a time of day on a given day (0 = today, 1 = tomorrow, -1 = yesterday).
Returns timestamp
const tomorrowMorning = TimeAt("06:30", 1)
LogInfo("Tomorrow 06:30 =", FormatTime(tomorrowMorning))
IsTimeBetween("von", "bis")
Whether the current time is inside the window – also across midnight ("22:00" to "06:00").
Returns true | false
if (IsTimeBetween("01:00", "06:30")) { LogInfo("Night pause"); SleepUntil("06:30") }
Wait until a time 2 SleepUntil · SleepUntilIfToday
SleepUntil("HH:MM[:SS]" | zeitstempel)
Waits until a time of day (next time it comes) or a timestamp. Stop/pause still work.
Returns –
SleepUntil("06:30")
LogInfo("Good morning – bringing the fleet back")
SleepUntilIfToday("HH:MM[:SS]")
Only waits if the time still comes today; otherwise false right away.
Returns true (waited) | false (already past today)
if (SleepUntilIfToday("18:00")) BuyOfferOfTheDay()
else LogInfo("18:00 already past today – skipped")

Account & server

Player & account 7 GetUserInfo · GetUsername · GetUserClass · GetAllianceClass · GetResearch · IsUnderAttack · IsVacationMode
GetUserInfo()
Player data: name, points, rank, honour points, class (CHARACTER_CLASS).
Returns { PlayerID, PlayerName, Points, Rank, Total, HonourPoints, Class }
const me = GetUserInfo()
LogInfo(me.PlayerName, "– rank", me.Rank, "of", me.Total, "–", me.Points, "points")
GetUsername()
Login name of the account – for Gameforge accounts the e-mail address, NOT the player name (GetUserInfo().PlayerName gives that). Careful when logging.
Returns Text
const login = GetUsername()
LogInfo("Login:", login.replace(/^(..).*(@.*)$/, "$1***$2"))   // logged masked
GetUserClass()
Character class as a number (see CHARACTER_CLASS).
Returns 0 | 1 | 2 | 3
if (GetUserClass() === CHARACTER_CLASS.DISCOVERER)
    LogInfo("Discoverer: more expedition yield")
GetAllianceClass()
Alliance class as a number (see ALLIANCE_CLASS).
Returns 0 | 1 | 2 | 3
if (GetAllianceClass() === ALLIANCE_CLASS.TRADER) LogInfo("Trader alliance")
GetResearch()
The account's research levels.
Returns { EnergyTechnology, LaserTechnology, …, Astrophysics, ComputerTechnology, … }
const r = GetResearch()
const maxExpos = Math.floor(Math.sqrt(r.Astrophysics))
LogInfo("Max. expeditions by astrophysics:", maxExpos)
IsUnderAttack()
Whether a hostile attack is on its way right now.
Returns true | false
if (IsUnderAttack() && !IsScriptRunning("Fleetsave")) StartScript("Fleetsave")
IsVacationMode()
Whether vacation mode is active.
Returns true | false
if (IsVacationMode()) Exit()
Officers 2 GetStaff · HasCommander
GetStaff()
Which officers are active (all at once).
Returns { Commander, Admiral, Engineer, Geologist, Technocrat }
const staff = GetStaff()
if (!staff.Admiral) LogWarn("No admiral – one fleet slot less")
HasCommander() / HasAdmiral() / HasEngineer() / HasGeologist() / HasTechnocrat()
Single query per officer.
Returns true | false
if (HasGeologist()) LogInfo("Geologist active: +10 % mine production")
Server & universe 9 GetServerData · GetServerInfo · GetServerTime · GetServerSpeed · GetServerName · GetOgamedIP · GetHiveIP · GetOgamedTasks · GameLogin
GetServerData()
Universe settings: speeds, galaxies/systems, debris factors, donut universe …
Returns { Speed, SpeedFleetWar, SpeedFleetPeaceful, SpeedFleetHolding, Galaxies, Systems, DonutGalaxy, DonutSystem, DebrisFactor, … }
const sd = GetServerData()
LogInfo("Universe", sd.Name, "speed", sd.Speed, "–", sd.Galaxies, "galaxies")
GetServerInfo()
General server info incl. players online.
Returns { Name, Number, Language, PlayerCount, PlayersOnline, Opened, StartDate, … }
const info = GetServerInfo()
LogInfo(info.PlayersOnline, "of", info.PlayerCount, "players online")
GetServerTime()
Current server time as a timestamp.
Returns ISO timestamp (text)
const t = new Date(GetServerTime())
if (t.getHours() >= 1 && t.getHours() < 6) LogInfo("Night time on the server")
GetServerSpeed() / GetServerFleetSpeed()
Economy or fleet speed as a number.
Returns number
LogInfo("Economy x" + GetServerSpeed(), "fleet x" + GetServerFleetSpeed())
GetServerName() / GetServerLanguage() / GetServerUrl() / GetServerVersion()
Single server values as text.
Returns Text
LogInfo(GetServerName(), GetServerLanguage().toUpperCase(), "version", GetServerVersion())
GetOgamedIP()
IP address ogamed uses to reach the internet (important with a proxy).
Returns Text
LogInfo("ogamed goes out via", GetOgamedIP())
GetHiveIP()
Public IP address HIVE itself uses to reach the internet (unlike GetOgamedIP, the IP of the game connection).
Returns Text
LogInfo("HIVE:", GetHiveIP(), "– game:", GetOgamedIP())
GetOgamedTasks()
Queue of the game connection (ogamed): how many requests are waiting by priority. Good for waiting until the bot has nothing left to do before big actions.
Returns { Low, Normal, Important, Critical, Total }
while (GetOgamedTasks().Total > 0) Sleep(500)
LogInfo("ogamed is free")
GameLogin()
Signs in to the game session again (e.g. after GameLogout or when the session expired).
Returns –
try { GetUserInfo() } catch (e) { LogWarn("Session gone – signing in again"); GameLogin() }

Planets & moons

Find celestials 11 GetPlanets · GetMoons · GetCelestials · GetPlanetsLive · GetHomeWorld · GetCelestial · GetPlanetAt · GetMoonAt · NearestOwnMoon · GetEmpire · MaxPlanets
GetPlanets()
Own planets (as of HIVE's last update, no game request – fast).
Returns [ { ID, Name, Type, Coordinate, Coords, Fields, Temperature } ]
for (const p of GetPlanets())
    LogInfo(p.Name, p.Coords, p.Fields.Built + "/" + p.Fields.Total, "fields")
GetMoons()
Own moons (no game request).
Returns [ { ID, Name, Type, Coordinate, Coords, Fields } ]
LogInfo("You have", GetMoons().length, "moons")
GetCelestials()
All own planets and moons (no game request).
Returns [ celestials ]
for (const c of GetCelestials())
    LogInfo(c.Type === "Moon" ? "Moon" : "Planet", c.Name, c.Coords)
GetPlanetsLive() / GetMoonsLive()
Like GetPlanets/GetMoons, but fresh from the server – e.g. right after colonising.
Returns [ celestials ]
const before = GetPlanets().length
SleepMin(1)
if (GetPlanetsLive().length > before) LogInfo("New colony!")
GetHomeWorld()
This bot's homeworld – set in the “Bot settings” tab (planet or moon). Without one (or if the celestial no longer exists) the oldest planet.
Returns celestial { ID, Name, Type, Coords, Coordinate, … } | null
const home = GetHomeWorld()
LogInfo("Home:", home.Name, home.Coords)
GetCelestial(ref)
Finds an own celestial. ref = ID, object from GetPlanets(), name or "1:16:4" (planet) / "1:16:4:3" (moon).
Returns Celestials
const moon = GetCelestial("1:16:4:3")
const colony = GetCelestial("Colony")
GetPlanetAt(koordinate)
Planet at a coordinate (own planet with ID, fields, temperature, moon). null if there is none.
Returns planet | null
const p = GetPlanetAt("1:16:4")
if (p) LogInfo(p.Name, "has", p.Fields.Total, "fields, max.", p.Temperature.Max, "°C")
GetMoonAt(koordinate)
Moon at a coordinate, null if there is none.
Returns moon | null
if (!GetMoonAt(GetHomeWorld().Coords)) LogInfo("The home planet has no moon (yet)")
NearestOwnMoon(ref | koordinate)
Nearest own moon (by OGame distance), without the moon at the start position itself.
Returns moon | null
const moon = NearestOwnMoon(GetHomeWorld())
if (!moon) LogWarn("No moon for a fleet save")
GetEmpire("planets" | "moons")
Empire view: all planets (or moons) with resources, buildings, ships and defence in ONE request – much faster than one by one.
Returns [ { ID, Name, Coords, Coordinate, Fields, Resources, Buildings, Facilities, Ships, Defences } ]
let metal = 0
for (const p of GetEmpire("planets")) metal += p.Resources.Metal
LogInfo("Metal in total:", metal)
MaxPlanets()
Max. number of planets by astrophysics.
Returns number
if (GetPlanets().length < MaxPlanets()) StartModule("Colonize")
Resources & production 7 GetResources · GetResourcesDetails · GetResourceSettings · SetResourceSettings · PlanetProduction · StorageCapacity · ResourceValue
GetResources(ref)
Current resources of a celestial.
Returns { Metal, Crystal, Deuterium, Energy, Food, Population, Darkmatter }
const r = GetResources(GetHomeWorld())
if (r.Energy < 0) LogWarn("Energy shortage on the home planet")
GetResourcesDetails(planet)
Amount, storage capacity and production per hour (planets only).
Returns { Metal: { Available, StorageCapacity, CurrentProduction }, Crystal, Deuterium, Energy, Food, Population }
const d = GetResourcesDetails(GetHomeWorld())
if (d.Metal.Available >= d.Metal.StorageCapacity)
    LogWarn("Metal storage full – mine stalls")
GetResourceSettings(planet)
Production factors of mines/power plants (0 to 1 = 0–100 %).
Returns { MetalMine, CrystalMine, DeuteriumSynthesizer, SolarPlant, FusionReactor, SolarSatellite, Crawler }
const f = GetResourceSettings(GetHomeWorld())
if (f.MetalMine < 1) LogWarn("Metal mine only runs at", f.MetalMine * 100, "%")
SetResourceSettings(planet, { MetalMine, CrystalMine, DeuteriumSynthesizer, SolarPlant, FusionReactor, SolarSatellite, Crawler })
Sets the production factors in percent (0–100 in steps of 10, crawlers up to 150). Values not given stay as they are.
Returns the new settings (like GetResourceSettings)
// fusion reactor off at night, saves deuterium
for (const p of GetPlanets())
    SetResourceSettings(p, { FusionReactor: 0 })
PlanetProduction(planet)
Hourly production by TBot's formula (mines, plasma, class, geologist, crawlers, production factors).
Returns { Metal, Crystal, Deuterium, Food }
const p = PlanetProduction("Home planet")
LogInfo("per day:", FormatNumber(p.Metal * 24), "metal")
StorageCapacity(stufe)
Capacity of a storage of this level.
Returns amount
const b = GetBuildings("Home planet")
LogInfo("Metal storage holds", FormatNumber(StorageCapacity(b.MetalStorage)))
ResourceValue(rohstoffe, kurs?)
Value in metal units (MSU). Rate [metal, crystal, deut], default [3, 2, 1].
Returns number
LogInfo("The home planet is worth", FormatNumber(ResourceValue(GetResources(GetHomeWorld()))), "MSU")
Energy & crawlers 5 EnergyProduction · SolarSatelliteProduction · SolarSatellitesNeeded · OptimalCrawlers · MaxCrawlers
EnergyProduction(gebäude, stufe)
Energy of a solar plant/fusion reactor at this level (with energy technology, class, engineer).
Returns Energy
LogInfo(EnergyProduction(BUILDING.SolarPlant, 30))
SolarSatelliteProduction(planet)
Energy of a solar satellite on this planet (depends on the temperature).
Returns energy per satellite
LogInfo(SolarSatelliteProduction("Home planet"))
SolarSatellitesNeeded(planet, [energie])
How many solar satellites this amount of energy needs (without a value: to cover the current deficit).
Returns amount
const n = SolarSatellitesNeeded("Home planet")
if (n > 0) BuildShips("Home planet", SHIP.SolarSatellite, n)
OptimalCrawlers(planet)
How many crawlers are worthwhile on this planet (TBot calculation).
Returns amount
const missing = OptimalCrawlers("Home planet") - GetShips("Home planet").Crawler
if (missing > 0) BuildShips("Home planet", SHIP.Crawler, missing)
MaxCrawlers(planet)
Max. number of effective crawlers on this planet (8 per mine level, more for collector/geologist).
Returns amount
LogInfo(MaxCrawlers("Home planet"))
Buildings & facilities 6 GetBuildings · GetFacilities · GetTechs · GetConstructions · GetProduction · ShipyardQueueTime
GetBuildings(ref)
Levels of the supply buildings.
Returns { MetalMine, CrystalMine, DeuteriumSynthesizer, SolarPlant, FusionReactor, SolarSatellite, MetalStorage, CrystalStorage, DeuteriumTank }
const b = GetBuildings(GetHomeWorld())
LogInfo("Mines:", b.MetalMine, b.CrystalMine, b.DeuteriumSynthesizer)
GetFacilities(ref)
Levels of the facilities.
Returns { RoboticsFactory, Shipyard, ResearchLab, AllianceDepot, MissileSilo, NaniteFactory, Terraformer, SpaceDock, LunarBase, SensorPhalanx, JumpGate }
if (GetFacilities(GetHomeWorld()).Shipyard < 4) LogWarn("Shipyard too small for Large Cargo")
GetTechs(ref)
Buildings, facilities, ships, defence and research of a celestial in one request.
Returns { supplies, facilities, ships, defenses, researches }
const t = GetTechs(GetHomeWorld())
LogInfo("Shipyard", t.facilities.Shipyard, "– LC:", t.ships.LargeCargo)
GetConstructions(ref)
Running construction and research (countdown in seconds, 0 = nothing).
Returns { BuildingID, BuildingCountdown, ResearchID, ResearchCountdown, LFBuildingID, LFBuildingCountdown, LFResearchID, LFResearchCountdown }
const k = GetConstructions(GetHomeWorld())
if (k.BuildingID === 0) LogInfo("Build queue free")
else LogInfo("Building done in", FormatDuration(k.BuildingCountdown))
GetProduction(ref)
Shipyard/defence queue.
Returns [ { ID, Nbr } ]
if (GetProduction(GetHomeWorld()).length === 0) LogInfo("Shipyard is free")
ShipyardQueueTime(ref)
Remaining time of the shipyard/defence queue in seconds, read from the overview page (1 game request). 0 = shipyard free.
Returns seconds
const rest = ShipyardQueueTime(GetHomeWorld())
LogInfo("Shipyard free in", FormatDuration(rest))
Ships & defence 4 GetShips · GetDefences · MobileShips · ShipsTotal
GetShips(ref)
Ships on the celestial.
Returns { LightFighter, …, SmallCargo, LargeCargo, …, Reaper, Pathfinder }
const s = GetShips(GetHomeWorld())
LogInfo("Large Cargo:", s.LargeCargo, "Pathfinder:", s.Pathfinder)
GetDefences(ref)
Defences on the celestial.
Returns { RocketLauncher, LightLaser, …, AntiBallisticMissiles, InterplanetaryMissiles }
const d = GetDefences(GetHomeWorld())
if (d.RocketLauncher < 100) BuildDefence(GetHomeWorld(), DEFENCE.RocketLauncher, 100 - d.RocketLauncher)
MobileShips(schiffe, reserve?)
Flyable ships (without solar satellites/crawlers) minus a reserve.
Returns { Schiffname: Anzahl }
const send = MobileShips(GetShips(home), { LargeCargo: 50, EspionageProbe: 1 })
SendFleet(home, send, "1:16:4:3", MISSION.DEPLOY)
ShipsTotal(schiffe)
Total number of ships in a ships object.
Returns number
LogInfo("Ships at home:", ShipsTotal(GetShips(GetHomeWorld())))
Items & artefacts 2 GetItems · GetArtifacts
GetItems(ref)
Items/boosters in the inventory (ref, name, rarity, amount).
Returns [ { Ref, Name, Title, Rarity, Amount, AmountFree, AmountBought, Image } ]
for (const i of GetItems(GetHomeWorld()))
    if (i.Amount > 0) LogInfo(i.Name, "×", i.Amount)
GetArtifacts(ref)
Collected artefacts and limit (discovery missions).
Returns { ArtifactsCollected, ArtifactsLimit }
const a = GetArtifacts(GetHomeWorld())
if (a.ArtifactsCollected >= a.ArtifactsLimit) LogWarn("Artefact storage full")

Build & research

Build 6 BuildBuilding · BuildCancelable · BuildShips · BuildDefence · BuildProduction · CancelBuilding
BuildBuilding(ref, id)
Upgrades a building/facility by one level.
Returns –
const home = GetHomeWorld()
if (GetConstructions(home).BuildingID === 0) BuildBuilding(home, BUILDING.MetalMine)
BuildCancelable(ref, id)
Like BuildBuilding, via the cancelable build call (the way HIVE builds itself).
Returns –
BuildCancelable(GetHomeWorld(), BUILDING.CrystalMine)
BuildShips(ref, id, anzahl)
Orders ships in the shipyard.
Returns –
BuildShips(GetHomeWorld(), SHIP.LargeCargo, 100)
BuildDefence(ref, id, anzahl)
Orders defence.
Returns –
BuildDefence(GetHomeWorld(), DEFENCE.RocketLauncher, 200)
BuildProduction(ref, id, anzahl)
Orders ships or defence via the general production order – like BuildShips/BuildDefence, but for both.
Returns –
BuildProduction("Home planet", DEFENCE.RocketLauncher, 100)
BuildProduction("Home planet", SHIP.EspionageProbe, 10)
CancelBuilding(ref)
Cancels the running building construction.
Returns –
if (GetConstructions(home).BuildingID === BUILDING.Terraformer) CancelBuilding(home)
Research 3 BuildResearch · CancelResearch · ResearchTime
BuildResearch(ref, id)
Starts a research on the planet.
Returns –
const home = GetHomeWorld()
if (GetConstructions(home).ResearchID === 0) BuildResearch(home, RESEARCH.Astrophysics)
CancelResearch(ref)
Cancels the running research.
Returns –
CancelResearch(GetHomeWorld())
ResearchTime(forschung, [stufe], [planet])
Research time by TBot's formula incl. intergalactic research network, researcher class and technocrat. Without a level: next level, without a planet: the one with the largest research lab. Loads the facilities of all planets on the first call.
Returns seconds
LogInfo("Astro takes", FormatDuration(ResearchTime(RESEARCH.Astrophysics)))
Costs & requirements 8 GetPrice · PriceRange · CanAfford · MissingResources · MaxBuildable · GetRequirements · BuildTime · GetNextLevel
GetPrice(id, stufeOderAnzahl)
Cost of a building/research (level) or of ships/defence (amount).
Returns { Metal, Crystal, Deuterium, Energy, … }
const cost = GetPrice(SHIP.LargeCargo, 100)
const r = GetResources(GetHomeWorld())
if (r.Metal >= cost.Metal && r.Crystal >= cost.Crystal)
    BuildShips(GetHomeWorld(), SHIP.LargeCargo, 100)
PriceRange(id, vonStufe, bisStufe)
Total cost of several levels of a building/research (lifeforms too) – calculated without a game request.
Returns { Metal, Crystal, Deuterium }
const k = PriceRange(BUILDING.MetalMine, 31, 35)
LogInfo("Metal mine 31–35 costs", FormatNumber(k.Metal), "M", FormatNumber(k.Crystal), "C")
CanAfford(kosten, bestand)
Whether the stock covers the cost.
Returns true | false
if (CanAfford(GetPrice(BUILDING.MetalMine, 31), GetResources(home))) BuildBuilding(home, BUILDING.MetalMine)
MissingResources(kosten, bestand)
What is still missing (0 if there's enough).
Returns { Metal, Crystal, Deuterium }
const missing = MissingResources(GetPrice(RESEARCH.Astrophysics, 10), GetResources(home))
LogInfo("Missing", FormatNumber(missing.Crystal), "crystal")
MaxBuildable(id, rohstoffe)
How many units of a ship/defence these resources can buy.
Returns amount
const res = GetResources("Home planet")
BuildShips("Home planet", SHIP.LargeCargo, MaxBuildable(SHIP.LargeCargo, res))
GetRequirements(id)
Requirements of a building, a research, a ship or a lifeform level.
Returns [ { ID, Name, Level } ]
for (const r of GetRequirements(SHIP.LargeCargo))
    LogInfo("Needs", r.Name, "level", r.Level)
BuildTime(id, stufe, ref)
Build time of a building/research at a level or of ships (the planet's facilities are queried).
Returns seconds
const t = BuildTime(BUILDING.MetalMine, 30, GetHomeWorld())
LogInfo("Metal mine 30 takes", FormatDuration(t))
GetNextLevel(ref, id)
Next level of a building, a research (ref doesn't matter) or a lifeform object – takes running constructions into account like TBot.
Returns level
const n = GetNextLevel("Home planet", BUILDING.MetalMine)
LogInfo("Metal mine", n, "costs", PriceRange(BUILDING.MetalMine, n, n))
Build recommendations (TBot) 7 NextMineToBuild · NextEnergySourceToBuild · NextResearchToBuild · NextLunarFacilityToBuild · NextLifeformBuildingToBuild · NextLifeformResearchToBuild · IsAstrophysicsPositionValid
NextMineToBuild(planet, [maxMetall], [maxKristall], [maxDeut], [startOptimiert])
Which mine TBot's AutoMine would build next (by payback, resource rate and class).
Returns building name or null
const next = NextMineToBuild("Home planet", 40, 35, 30)
if (next) BuildBuilding("Home planet", next)
NextEnergySourceToBuild(planet, [maxSolar], [maxFusion], [satelliten])
Which energy source TBot would build next (solar plant, fusion reactor or solar satellites).
Returns building/ship name or null
LogInfo(NextEnergySourceToBuild("Home planet", 30, 20, true))
NextResearchToBuild([planet])
Which research TBot's AutoResearch would pick next (with its default maximum levels).
Returns research name or null
const r = NextResearchToBuild()
if (r) BuildResearch("Home planet", r)
NextLunarFacilityToBuild(mond, [{ LunarBase, RoboticsFactory, SensorPhalanx, JumpGate, Shipyard }])
Which moon facility TBot would build next, with optional maximum levels (default 8/8/6/1/0).
Returns building name or null
const b = NextLunarFacilityToBuild("1:16:4:3", { SensorPhalanx: 8 })
if (b) BuildBuilding("1:16:4:3", b)
NextLifeformBuildingToBuild(planet, [{ max, preventIfMoreExpensiveThanNextMine, preventTechBuilding }])
Which lifeform building TBot's lifeform AutoMine would build next. max = maximum levels per building, e.g. { ResidentialSector: 40 }.
Returns building name or null
const b = NextLifeformBuildingToBuild("Home planet", { max: { ResidentialSector: 40, BiosphereFarm: 40 } })
if (b) BuildLifeformBuilding("Home planet", b)
NextLifeformResearchToBuild(planet, [höchststufen])
Which lifeform research TBot would pick next (the cheapest unlocked one).
Returns research name or null
const t = NextLifeformResearchToBuild("Home planet")
if (t) BuildLifeformResearch("Home planet", t)
IsAstrophysicsPositionValid(position)
Whether the planet position (1–15) can be colonised with your astrophysics level.
Returns true/false
for (let pos = 1; pos <= 15; pos++) if (!IsAstrophysicsPositionValid(pos)) LogInfo("Position", pos, "still locked")
Payback 5 AmortizationDays · BuildingROI · NextAmortizationDays · AstrophysicsAmortizationDays · PlasmaAmortizationDays
AmortizationDays(planet, gebäude)
After how many days the next level of a mine pays for itself (TBot's days of investment return).
Returns days
for (const m of [BUILDING.MetalMine, BUILDING.CrystalMine, BUILDING.DeuteriumSynthesizer])
    LogInfo(m, AmortizationDays("Home planet", m), "days")
BuildingROI(planet, gebäude)
Return of the next mine level by TBot (higher = more worthwhile).
Returns number
LogInfo(BuildingROI("Home planet", BUILDING.CrystalMine))
NextAmortizationDays(planet)
Payback of the cheapest next mine on this planet.
Returns days
for (const p of GetPlanets()) LogInfo(p.Name, NextAmortizationDays(p), "days")
AstrophysicsAmortizationDays()
Payback of the next astrophysics level incl. a new colony with mines (over all planets; loads all planets).
Returns days
LogInfo("Astro:", AstrophysicsAmortizationDays(), "Plasma:", PlasmaAmortizationDays())
PlasmaAmortizationDays()
Payback of the next plasma technology level over all planets.
Returns days
if (PlasmaAmortizationDays() < NextAmortizationDays("Home planet")) BuildResearch("Home planet", RESEARCH.PlasmaTechnology)
Lifeforms 9 GetLifeformBuildings · GetLifeformResearch · GetLifeformBonuses · BuildLifeformBuilding · BuildLifeformResearch · GetLifeformPrice · LifeformBuildTime · LifeformResearchTime · LifeformPopulation
GetLifeformBuildings(ref)
Levels of the lifeform buildings (names as in LF_BUILDING).
Returns { LifeformType, ResidentialSector, BiosphereFarm, ResearchCentre, … }
const lf = GetLifeformBuildings(GetHomeWorld())
LogInfo("Residential sector level", lf.ResidentialSector)
GetLifeformResearch(ref)
Levels of the lifeform research (names as in LF_RESEARCH).
Returns { IntergalacticEnvoys, HighPerformanceExtractors, … }
const t = GetLifeformResearch(GetHomeWorld())
LogInfo("High-performance extractors level", t.HighPerformanceExtractors)
GetLifeformBonuses()
All lifeform bonuses of the account (production, ships, research …).
Returns large object with bonus fields
LogDebug(GetLifeformBonuses())
BuildLifeformBuilding(ref, id)
Upgrades a lifeform building. id = LF_BUILDING.* or name.
Returns –
BuildLifeformBuilding(GetHomeWorld(), LF_BUILDING.ResidentialSector)
BuildLifeformResearch(ref, id)
Starts a lifeform research. id = LF_RESEARCH.* or name.
Returns –
BuildLifeformResearch(GetHomeWorld(), LF_RESEARCH.HighPerformanceExtractors)
GetLifeformPrice(id, stufe)
Cost of a lifeform building or lifeform research at a level.
Returns { Metal, Crystal, Deuterium, Food, Population, … }
const k = GetLifeformPrice(LF_BUILDING.BiosphereFarm, 10)
LogInfo("Biosphere farm 10 costs", k.Metal, "metal")
LifeformBuildTime(gebäude, stufe, planet)
Build time of a lifeform building by TBot's formula.
Returns seconds
LogInfo(FormatDuration(LifeformBuildTime(LF_BUILDING.ResidentialSector, 20, "Home planet")))
LifeformResearchTime(forschung, stufe, [zeitReduktion])
Duration of a lifeform research by TBot's formula (timeReduction as a fraction, e.g. 0.1 = 10 %).
Returns seconds
LogInfo(FormatDuration(LifeformResearchTime(LF_RESEARCH.IntergalacticEnvoys, 5)))
LifeformPopulation(planet)
Population and food by TBot's lifeform formulas.
Returns { LivingSpace, Satisfied, FoodProduction, FoodConsumption }
const p = LifeformPopulation("Home planet")
if (p.FoodProduction < p.FoodConsumption) LogWarn("Not enough food!")

Fleets

Fleet status 6 GetSlots · GetFleets · RefreshFleets · LatestReturn · WaitForFleets · MaxExpeditions
GetSlots()
Used and total fleet and expedition slots.
Returns { InUse, Total, ExpInUse, ExpTotal }
const s = GetSlots()
const freeExpos = Math.min(s.ExpTotal - s.ExpInUse, s.Total - s.InUse)
LogInfo("Free expedition slots:", freeExpos)
GetFleets()
Own fleets on their way (ArriveIn/BackIn in seconds). Careful: on the way back ArriveIn is -1 and the remaining time is in BackIn – so time until home is always Math.max(f.ArriveIn, f.BackIn ?? -1).
Returns [ { ID, Mission, ReturnFlight, Origin, Destination, Ships, Resources, ArrivalTime, BackTime, ArriveIn, BackIn } ]
const expos = GetFleets().filter(f => f.Mission === MISSION.EXPEDITION)
const latest = Math.max(0, ...expos.map(f => f.BackIn || 0))
LogInfo(expos.length, "expeditions, all back in", FormatDuration(latest))
RefreshFleets()
Reads the fleets again and also updates TBot's own fleet list (the one the modules use).
Returns list of fleets (like GetFleets)
const fleets = RefreshFleets()
LogInfo(fleets.length, "fleets on their way")
LatestReturn(mission?)
When the last own fleet (optionally of one mission only) is back.
Returns { Count, InSeconds, At }
const r = LatestReturn(MISSION.EXPEDITION)
LogInfo(r.Count, "expeditions, the last back at", FormatTime(r.At))
WaitForFleets(mission?, maxSekunden?)
Waits until no fleet (of the mission) is on its way any more – sleeps sensibly long while waiting.
Returns true (all back) | false (time limit)
WaitForFleets(MISSION.EXPEDITION)
LogInfo("All expeditions back – next wave")
MaxExpeditions()
Max. possible expeditions (astrophysics, discoverer class, admiral).
Returns number
const s = GetSlots()
if (s.ExpInUse < MaxExpeditions()) LogInfo("An expedition slot is still free")
Send fleets 6 SendFleet · SendFleet (Rückruf) · SendFleetValidated · DeployAll · CancelFleet · RecallFleetsByMission
SendFleet(start, schiffe, ziel, mission, tempo?, rohstoffe?)
Sends a fleet. start = own celestial, ships = { name: amount }, target = "g:s:p" (position 16 = deep space) or "g:s:p:type", mission = MISSION.*, speed 0.5–10 (10 = 100 %, default 10), resources = { Metal, Crystal, Deuterium }. Returns null if no matching ships are there.
Returns fleet | null
// transport from the home planet to the colony, 50 % speed
const fleet = SendFleet(GetHomeWorld(), { LargeCargo: 200 }, "1:20:8", MISSION.TRANSPORT, 5,
    { Metal: 1000000, Crystal: 500000 })
if (fleet) LogInfo("On its way, arrival in", FormatDuration(fleet.ArriveIn))
SendFleet(…, rohstoffe, { recallIn | recallAt })
SendFleet takes a recall as its 7th argument: recallIn = seconds, recallAt = "HH:MM:SS" or timestamp.
Returns fleet | null
SendFleet(home, ships, "1:16:4:3", MISSION.DEPLOY, 1, {}, { recallAt: "03:15" })
SendFleetValidated(von, schiffe, ziel, mission, [speed], [rohstoffe], [erzwingen])
Sends a fleet via TBot's own fleet planner: checks free slots, sleep time and resources like the bot modules. force=true skips the sleep time check.
Returns { Success, FleetID, Code, Error }
const r = SendFleetValidated("Home planet", { LargeCargo: 50 }, "1:16:4:3", MISSION.TRANSPORT, 10, { Metal: 1000000 })
if (!r.Success) LogWarn("Not sent:", r.Error)
DeployAll(von, ziel, [speed], [behalten])
TBot function (/deploy): all movable ships with all resources deployed to the target. keep = ships that should stay, e.g. { EspionageProbe: 10 }.
Returns { Success, FleetID, Code, Error }
DeployAll("1:16:4", "1:16:4:3", 10, { EspionageProbe: 5 })
CancelFleet(flottenId)
Recalls an own fleet.
Returns –
for (const f of GetFleets())
    if (f.Mission === MISSION.DEPLOY && !f.ReturnFlight) CancelFleet(f.ID)
RecallFleetsByMission(mission)
Recalls all own fleets of a mission that are still on their way out (TBot /recall logic).
Returns number of recalled fleets
const n = RecallFleetsByMission(MISSION.DEPLOY)
LogInfo(n, "deployments recalled")
Fleet save & recall 6 FleetSave · TriggerFleetSave · SwitchFleet · ScheduleRecall · CancelScheduledRecall · GetScheduledRecalls
FleetSave(start, rückkehrUm, optionen?)
Fleet save in one call: all flyable ships + resources fly to the nearest own moon (10 % speed, deploy) and are recalled halfway so they are back at the return time. Checks deuterium first and whether the recall is possible before arrival. options: destination, speed, mission, keep (ships as a reserve), keepDeuterium, resources (false = without resources).
Returns { FleetID, Destination, OneWay, Fuel, RecallAt, ReturnAt, Payload, Ships }
const f = FleetSave(GetHomeWorld(), "06:30", { keep: { EspionageProbe: 1 }, keepDeuterium: 50000 })
LogInfo("Fleet save", f.FleetID, "back at", FormatTime(f.ReturnAt))
Notify("Fleet save until " + FormatTime(f.ReturnAt), "Night save")
TriggerFleetSave(ref, [minDauerSek], [{ mission, waitForFleets, all }])
TBot's own fleet save (Telegram /ghost, /ghostsleep, /ghostsleepall): picks target and speed itself so the fleet is away for at least minDuration. all=true saves all celestials, waitForFleets waits for returning fleets.
Returns –
// send everything away for at least 8 hours before going to sleep
TriggerFleetSave(GetHomeWorld(), 8 * 3600, { all: true, waitForFleets: true })
SwitchFleet(ref, [speed])
TBot function (/switch): moves the fleet between a planet and its moon (in the other direction each time).
Returns true if done
// clear the attacked celestial: fleet to the moon or the planet opposite
for (const a of GetAttacks())
    SwitchFleet(FormatCoord(a.Destination) + ":" + a.Destination.Type, 10)
ScheduleRecall(flottenId, wann)
Schedules the recall of an own fleet (when = seconds, "HH:MM:SS" or timestamp). Keeps going when the script ends and survives bot and HIVE restarts (if the bot isn't logged in at that time, HIVE keeps trying for 15 minutes).
Returns timestamp of the recall
const f = SendFleet(home, { LargeCargo: 10 }, "1:16:16", MISSION.EXPEDITION)
ScheduleRecall(f.ID, 1800)   // recall after 30 minutes
CancelScheduledRecall(flottenId)
Cancels a scheduled recall.
Returns true if one was scheduled
CancelScheduledRecall(f.ID)
GetScheduledRecalls()
All scheduled recalls of this bot.
Returns [ { FleetID, RecallAt, In, ScheduledBy } ]
for (const r of GetScheduledRecalls()) LogInfo("Fleet", r.FleetID, "recall in", FormatDuration(r.In))
Flight planner 5 ScheduleFlight · ScheduleJump · GetScheduledFlights · CancelScheduledFlight · SetScheduledFlightActive
ScheduleFlight(optionen)
Plans a flight in the “Flight planner” tab – it runs there at its time, also after this script has ended and after restarts. options: from (own planet/moon), to (coordinate), ships ("all" or e.g. { LargeCargo: 100, Pathfinder: "all", Cruiser: { allBut: 10 } }), mission, speed (1–10), resources ("all" or e.g. { Deuterium: "all", Metal: 50000 }), at ("HH:MM:SS" or timestamp), mode ("depart" | "arrive" | "return"), repeat ("once" | "daily" | "weekdays" | "hours"), days, everyHours, random ([min, max] seconds), recallAfter / backAfter (seconds after the departure), after (ID of another entry: runs after it – a chain) with trigger ("done" | "arrived" | "returned") and delay (seconds), name, behaviour (the tab's settings, e.g. { slotBusy: "reserve", defenderOff: true }).
Returns ID of the entry
const id = ScheduleFlight({
  from: GetHomeWorld(), to: "1:16:16", mission: MISSION.EXPEDITION,
  ships: { LargeCargo: 300, Pathfinder: 1 }, at: "07:30:00", repeat: "daily",
  random: [0, 600], name: "Morning expedition"
})
LogInfo("Planned:", id)
ScheduleJump(optionen)
Plans a jump gate jump from own moon to own moon (options like ScheduleFlight, without mission/speed/resources). If a gate is still recharging at the planned time, the jump follows as soon as both gates are ready – at most behaviour.jumpMaxDelayMinutes later (default 30).
Returns ID of the entry
const jump = ScheduleJump({ from: "1:100:8:3", to: "2:50:4:3", ships: "all", at: "23:00:00" })
// afterwards: everything from the target moon to its planet
ScheduleFlight({ after: jump, from: "2:50:4:3", to: "2:50:4", mission: MISSION.DEPLOY, ships: "all", resources: "all" })
GetScheduledFlights()
All entries of the flight planner of this bot.
Returns [ { ID, Name, Kind, Active, Repeat, Next, Departure, Running, LastOutcome, LastMessage } ]
for (const f of GetScheduledFlights()) LogInfo(f.Name, f.Active ? FormatTime(f.Next) : "off", f.LastOutcome || "")
CancelScheduledFlight(id)
Deletes an entry of the flight planner (a recall it already scheduled for a sent fleet still happens).
Returns true if it existed
CancelScheduledFlight(id)
SetScheduledFlightActive(id, aktiv)
Switches an entry on or off – like the switch in the tab. Switching on checks it again (a one-off time in the past is refused).
Returns true if done
SetScheduledFlightActive(id, false)   // pause while the attack is on
Repatriation 2 RepatriateNow · CollectDeuterium
RepatriateNow([ohneLimit])
TBot repatriation right now (/collect or /collectall with noLimit=true): sends the resources of all celestials to the target from the repatriation settings.
Returns "success", "stop", "failure" or "delay"
const r = RepatriateNow()
if (r !== "success") LogWarn("Repatriation:", r)
CollectDeuterium(minMenge)
TBot function (/collectdeut): fetches deuterium from all celestials with at least minAmount to the repatriation target.
Returns –
CollectDeuterium(500000)
Flight calculation 11 CalcFlight · FlightTime · FuelConsumption · Distance · ShipSpeed · LowestSpeed · ValidSpeeds · OptimalFarmSpeed · ShipFuelConsumption · ShipFuelCapacity · FleetFuelCapacity
CalcFlight(start, ziel, schiffe, mission?, tempo?)
Plans a flight completely: flight time (one way), deuterium use, distance, cargo space and free cargo after fuel, arrival and return. Takes drives, class, alliance class and lifeform bonuses into account. No game request (except once for the LF bonuses). mission default TRANSPORT, speed default 10.
Returns { FlightTime, Fuel, Distance, Cargo, FreeCargo, ArrivalAt, ReturnAt }
const plan = CalcFlight(GetHomeWorld(), "1:16:16", { LargeCargo: 4000, Pathfinder: 1 }, MISSION.EXPEDITION)
LogInfo("Flight", FormatDuration(plan.FlightTime), "– deut", plan.Fuel, "– back", plan.ReturnAt)
if (GetResources(GetHomeWorld()).Deuterium < plan.Fuel) LogWarn("Not enough deuterium")
FlightTime(start, ziel, schiffe, mission?, tempo?)
Only the flight time (one way) in seconds. start/target = own celestial or coordinate.
Returns seconds
// how long does the whole home fleet need at 10 % to the own moon?
const ships = GetShips(GetHomeWorld())
const oneWay = FlightTime(GetHomeWorld(), "1:16:4:3", ships, MISSION.DEPLOY, 1)
LogInfo("One-way flight at 10 %:", FormatDuration(oneWay))
FuelConsumption(start, ziel, schiffe, mission?, tempo?)
Only the deuterium use for the flight.
Returns Deuterium
const deut = FuelConsumption(GetHomeWorld(), "2:100:8", { LargeCargo: 500 }, MISSION.TRANSPORT, 10)
LogInfo("The transport costs", deut, "deuterium")
Distance(a, b)
OGame distance between two coordinates (donut universe taken into account).
Returns number
let nearest = null
for (const m of GetMoons())
    if (!nearest || Distance(GetHomeWorld(), m) < Distance(GetHomeWorld(), nearest)) nearest = m
LogInfo("Nearest moon:", nearest.Name, nearest.Coords)
ShipSpeed(schiffId)
Speed of a ship type with your drives and bonuses.
Returns number
LogInfo("Pathfinder:", ShipSpeed(SHIP.Pathfinder), "– Large Cargo:", ShipSpeed(SHIP.LargeCargo))
LowestSpeed(schiffe)
Speed of the fleet's slowest ship (with drives, class, lifeform bonuses).
Returns Speed
LogInfo(LowestSpeed({ LargeCargo: 100, Recycler: 10 }))
ValidSpeeds()
The speed steps allowed for your class (general: in steps of 5 %).
Returns list, e.g. [1, 2, …, 10]
LogInfo(ValidSpeeds())
OptimalFarmSpeed(von, ziel, schiffe, beute, [maxSpritAnteil], [maxFlugSek])
Fastest speed at which fuel costs at most maxFuelShare of the loot (default 0.1 = 10 %) and the flight takes no longer than maxFlightSec – TBot's AutoFarm formula.
Returns speed (1–10)
const speed = OptimalFarmSpeed("Home planet", "1:20:8", { LargeCargo: 20 }, { Metal: 400000, Crystal: 200000 }, 0.05, 3600)
SendFleet("Home planet", { LargeCargo: 20 }, "1:20:8", MISSION.ATTACK, speed)
ShipFuelConsumption(schiff)
Base consumption of a ship type (with drives and bonuses).
Returns Deuterium
LogInfo(ShipFuelConsumption(SHIP.Recycler))
ShipFuelCapacity(schiff)
Fuel capacity of a ship (how much fuel it can take along).
Returns Deuterium
LogInfo(ShipFuelCapacity(SHIP.Pathfinder))
FleetFuelCapacity(schiffe)
Fuel capacity of the whole fleet.
Returns Deuterium
LogInfo(FleetFuelCapacity({ LargeCargo: 500 }))
Cargo & loading 6 CargoCapacity · ShipCargo · ShipsNeeded · CargoMix · PackResources · MaxTransportable
CargoCapacity(schiffe)
Total cargo space of a fleet incl. hyperspace technology, class and bonuses.
Returns number
const cap = CargoCapacity(GetShips(GetHomeWorld()))
LogInfo("All ships at home hold", cap, "resources")
ShipCargo(schiffId)
Cargo space of ONE ship of this type (with all bonuses).
Returns number
LogInfo("One Large Cargo holds", ShipCargo(SHIP.LargeCargo))
ShipsNeeded(menge, schiffId)
How many ships are needed for an amount of resources. amount = number or resource object (metal+crystal+deut are added up).
Returns number
const r = GetResources(GetCelestial("Colony"))
const lc = ShipsNeeded(r, SHIP.LargeCargo)
SendFleet(GetCelestial("Colony"), { LargeCargo: lc }, GetHomeWorld().Coords, MISSION.TRANSPORT, 10, r)
CargoMix(benötigterLaderaum, verfügbareSchiffe)
Fewest cargo ships for a cargo amount: Large Cargo first, then Small Cargo.
Returns { LargeCargo, SmallCargo, Capacity, Enough }
const mix = CargoMix(2500000, GetShips(home))
if (mix.Enough) SendFleet(home, { LargeCargo: mix.LargeCargo, SmallCargo: mix.SmallCargo }, target, MISSION.TRANSPORT)
PackResources(rohstoffe, laderaum, reihenfolge?)
Loads a cargo space by priority (default: deuterium, crystal, metal).
Returns { Metal, Crystal, Deuterium }
const r = GetResources(home)
const load = PackResources(r, CargoCapacity({ LargeCargo: 100 }))
SendFleet(home, { LargeCargo: 100 }, "1:20:8", MISSION.TRANSPORT, 10, load)
MaxTransportable(schiffe, rohstoffe, [deutBehalten])
Which resources these ships can take along – by TBot's loading logic: deuterium first (minus deutKeep), then crystal, then metal. For metal first: PackResources.
Returns { Metal, Crystal, Deuterium }
const load = MaxTransportable({ LargeCargo: 100 }, GetResources("Home planet"), 50000)
SendFleet("Home planet", { LargeCargo: 100 }, "1:16:4:3", MISSION.TRANSPORT, 10, load)
Expeditions 7 SendExpedition · SystemsInRange · IdealExpeditionShips · FullExpeditionShips · MilitaryShipForExpedition · GetExpeditionMessages · ExpeditionStats
SendExpedition(von, schiffe, ziel, [speed], [rohstoffe])
Expedition via TBot's fleet planner (with an expedition slot check, like the expeditions module).
Returns { Success, FleetID, Code, Error }
const home = GetHomeWorld()
const r = SendExpedition(home, { LargeCargo: 1500, Pathfinder: 1, EspionageProbe: 1 }, home.Coordinate.Galaxy + ":" + home.Coordinate.System + ":16")
LogInfo(r.Success ? "Expo " + r.FleetID : r.Error)
SystemsInRange(system, anzahl)
Systems by distance: start, +1, −1, +2, −2 … (donut universe taken into account) – e.g. to spread expeditions.
Returns [ number ]
const home = GetHomeWorld()
for (const s of SystemsInRange(home.Coordinate.System, 3))
    SendFleet(home, { LargeCargo: 4000, Pathfinder: 1 }, home.Coordinate.Galaxy + ":" + s + ":16", MISSION.EXPEDITION)
IdealExpeditionShips(verfügbar, hauptschiff, anzahlExpeditionen)
The expedition fleet TBot's expeditions module would put together from the available ships (per expedition).
Returns ships object
const home = GetHomeWorld()
const fleet = IdealExpeditionShips(GetShips(home), SHIP.LargeCargo, 3)
SendExpedition(home, fleet, home.Coordinate.Galaxy + ":" + home.Coordinate.System + ":16")
FullExpeditionShips(verfügbar, hauptschiff, anzahlExpeditionen)
Like IdealExpeditionShips, but the available ships are spread completely over the expeditions.
Returns ships object
LogInfo(FullExpeditionShips(GetShips("Home planet"), SHIP.LargeCargo, 4))
MilitaryShipForExpedition(verfügbar, anzahlExpeditionen)
The strongest combat ship TBot would give every expedition.
Returns ship name or null
LogInfo(MilitaryShipForExpedition(GetShips("Home planet"), 3))
GetExpeditionMessages()
Expedition reports with found resources and ships – the basis for expedition statistics.
Returns [ { ID, Coordinate, Content, Resources, Ships, CreatedAt } ]
let metal = 0, crystal = 0, deut = 0
for (const m of GetExpeditionMessages()) {
    metal += m.Resources.Metal; crystal += m.Resources.Crystal; deut += m.Resources.Deuterium
}
LogInfo("Expeditions brought:", metal, "M", crystal, "C", deut, "D")
ExpeditionStats(stunden?)
Analysis of the expedition reports of the last hours (default 24): count, resources, MSU value, found ships, kinds of finds.
Returns { Hours, Count, Resources, Value, Ships, ByType }
const s = ExpeditionStats(24)
Notify(s.Count + " expeditions, " + FormatNumber(s.Value) + " MSU", "Expeditions today")
Jump gate & phalanx 5 JumpGate · JumpGateCooldown · JumpGateReady · JumpGateInfo · Phalanx
JumpGate(vonMond, zuMond, schiffe)
Jump through the jump gate between two own moons.
Returns { Success, RechargeCountdown, Error }
const r = JumpGate("1:16:4:3", "2:100:8:3", { Battleship: 50 })
if (!r.Success) LogError("Jump failed:", r.Error)
JumpGateCooldown(stufe)
Jump gate recharge time for a level (divided by the war fleet speed).
Returns seconds
LogInfo("Jump gate level 5 recharges in", FormatDuration(JumpGateCooldown(5)))
JumpGateReady(mond)
Remaining time until a jump gate is ready again (remembers jumps via JumpGate()). 0 = ready or unknown.
Returns seconds
const wait = JumpGateReady("1:16:4:3")
if (wait > 0) SleepSec(wait + 5)
JumpGate("1:16:4:3", "2:100:8:3", { Battleship: 50 })
JumpGateInfo(mond)
Reads the jump gate page of an own moon (read only, 1 game request): reachable target moons and the remaining recharge time, also after jumps by TBot or by hand. Remembers the recharge time for JumpGateReady().
Returns { Ready, Cooldown, Destinations: [ { ID, Coords, Name } ] }
const info = JumpGateInfo("1:16:4:3")
if (!info.Ready) SleepSec(info.Cooldown + 5)
const target = info.Destinations.find(d => d.Coords === "2:100:8")
if (target) JumpGate("1:16:4:3", target.ID, { Battleship: 50 })
Phalanx(mond, koordinate)
Sensor phalanx from an own moon on a coordinate (costs deuterium).
Returns [ fleet ]
for (const f of Phalanx("1:16:4:3", "1:18:7"))
    LogInfo("Fleet mission", f.Mission, "arrival in", FormatDuration(f.ArriveIn))
Attacks 3 GetAttacks · IsPlanetUnderAttack · SpyCrash
GetAttacks()
Incoming hostile fleets.
Returns [ { ID, MissionType, Origin, Destination, DestinationName, ArrivalTime, ArriveIn, AttackerName, AttackerID, Missiles, Ships } ]
for (const a of GetAttacks())
    LogWarn(a.AttackerName, "attacks", a.DestinationName, "– arrival in", FormatDuration(a.ArriveIn))
IsPlanetUnderAttack(ref)
Whether exactly THIS planet is attacked (instead of any).
Returns true | false
for (const p of GetPlanets())
    if (IsPlanetUnderAttack(p)) StartScript("Fleetsave", { planet: p.Coords })
SpyCrash(ref, [ziel])
TBot function (/spycrash): sends an espionage probe to its death as an attack to create debris/activity. Without a target TBot finds one.
Returns –
SpyCrash("Home planet")

Galaxy & espionage

Galaxy 1 GetGalaxyInfo
GetGalaxyInfo(galaxie, system)
System view. Planets is ordered by position, empty slots = null.
Returns { Galaxy, System, Planets: [ { Name, Coordinate, Player, Alliance, Debris, Inactive, Vacation, … } | null ], ExpeditionDebris }
const sys = GetGalaxyInfo(1, 16)
for (const p of sys.Planets)
    if (p && p.Inactive) LogInfo("Inactive:", p.Player.Name, FormatCoord(p.Coordinate))
Galaxy cache 5 ScanSystem · GetCachedSystem · FindPlayer · GalaxyCacheInfo · ClearGalaxyCache
ScanSystem(galaxie, system)
Reads a system (one game request) and stores it permanently in the galaxy cache.
Returns { Galaxy, System, Planets: [ { Position, Name, Player, Alliance, HasMoon, Inactive, Vacation, Debris, … } ] }
for (const s of SystemsInRange(GetHomeWorld().Coordinate.System, 20)) {
    ScanSystem(1, s)
    SleepRandSec(2, 5)
}
GetCachedSystem(galaxie, system, maxAlterMin?)
System from the cache (no game request); null if not scanned or older than maxAgeMin.
Returns { ScannedAt, Info } | null
const c = GetCachedSystem(1, 17, 60) || { Info: ScanSystem(1, 17) }
LogInfo(c.Info.Planets.length, "planets in 1:17")
FindPlayer(name)
Finds players in the cache (part of the name is enough) – all known planets.
Returns [ { Coords, PlanetName, PlayerName, PlayerID, Alliance, HasMoon, Inactive, Vacation, ScannedAt } ]
for (const p of FindPlayer(GetAttacks()[0].AttackerName))
    LogInfo("Attacker planet:", p.Coords, p.HasMoon ? "(with moon)" : "")
GalaxyCacheInfo()
Size of the cache: systems, planets, players, oldest/newest scan.
Returns { Systems, Planets, Players, OldestScan, NewestScan }
const i = GalaxyCacheInfo()
LogInfo(i.Systems, "systems,", i.Players, "players in the cache")
ClearGalaxyCache()
Clears this bot's galaxy cache.
Returns –
ClearGalaxyCache()
Espionage 3 GetEspionageReports · GetEspionageReport · GetEspionageReportFor
GetEspionageReports(seite?)
List of espionage reports (default page 1).
Returns [ { ID, Type, From, Target, LootPercentage } ]
for (const b of GetEspionageReports())
    LogInfo("Report", b.ID, "for", FormatCoord(b.Target))
GetEspionageReport(meldungsId)
One espionage report in detail. Ships/defence are null if not spied.
Returns { Username, Metal, Crystal, Deuterium, HasFleetInformation, HasDefensesInformation, …, Schiffe, Verteidigung }
const r = GetEspionageReport(GetEspionageReports()[0].ID)
LogInfo(r.Username, "has", r.Metal + r.Crystal + r.Deuterium, "resources")
GetEspionageReportFor(koordinate)
The latest espionage report for a coordinate.
Returns espionage report
const r = GetEspionageReportFor("1:18:7")
if (r.HasFleetInformation && r.LightFighter === 0) LogInfo("Target without fighters")
Battle simulator 1 SimulateBattle
SimulateBattle(angreifer, verteidiger, optionen?)
Simulates a battle several times (default 10×, max. 50): 6 rounds, shields, 1 % rule, explosions, rapid fire, weapons/shields/armour. Sides as a ships object, { ships, defences, tech: { Weapons, Shielding, Armour } } or an espionage report directly. Attacker without tech = your research. An approximation without class and lifeform combat bonuses.
Returns { AttackerWins, DefenderWins, Draws (in %), AverageRounds, Attacker: { Lost, Remaining, LostResources }, Defender: {…}, Debris, DefencesRebuilt }
const report = GetEspionageReportFor("1:18:7")
const sim = SimulateBattle({ Cruiser: 200, LargeCargo: 50 }, report)
LogInfo("Win:", sim.AttackerWins, "% – own losses:", FormatNumber(ResourceValue(sim.Attacker.LostResources)), "MSU")
if (sim.AttackerWins === 100 && sim.Attacker.LostResources.Metal === 0) LogInfo("Attack without losses possible")
Discovery 4 GetAvailableDiscoveries · GetDiscoveryPositions · SendDiscovery · SendSystemDiscovery
GetAvailableDiscoveries(ref)
Number of available discovery fleets.
Returns number
const n = GetAvailableDiscoveries(GetHomeWorld())
LogInfo(n, "discovery fleets available")
GetDiscoveryPositions(ref, koordinate)
Positions in the coordinate's system that can still be explored (query only).
Returns [ coordinate ]
const free = GetDiscoveryPositions(GetHomeWorld(), "1:17:1")
LogInfo(free.length, "positions in system 1:17 can be explored")
SendDiscovery(ref, ziel)
Sends a discovery mission to a position. Don't repeat in a fast loop – an error doesn't mean for sure that nothing was sent.
Returns true | false
for (const c of GetDiscoveryPositions(home, "1:17:1").slice(0, 3)) {
    SendDiscovery(home, c)
    SleepRandSec(2, 5)
}
SendSystemDiscovery(ref, galaxie, system)
Explores a whole system at once (system discovery).
Returns [ sent coordinates ]
const targets = SendSystemDiscovery(GetHomeWorld(), 1, 17)
LogInfo(targets.length, "discoveries sent to system 1:17")
Game pages directly 2 GetGamePage · GetAllianceInfoPage
GetGamePage(seite)
Loads any game page as HTML – for data no other function provides (page as text "page=…&component=…" or object). Signing out is blocked.
Returns the page's HTML as text
const html = GetGamePage({ page: "ingame", component: "overview" })
const m = html.match(/darkmatter[^>]*>\s*([\d.]+)/i)
if (m) LogInfo("Dark matter:", m[1])
GetAllianceInfoPage(allianzId)
An alliance's public info page as HTML (name, tag, member count, application status).
Returns HTML as text
const html = GetAllianceInfoPage(500123)
LogInfo(html.includes("Bewerbung") ? "Accepts applications" : "closed")

Trade & communication

Trade 4 BuyOfferOfTheDay · GetAuction · BidAuction · BidAuctionMinimum
BuyOfferOfTheDay()
Buys the trader's daily offer.
Returns "bought" | "already" | "unknown"
const r = BuyOfferOfTheDay()
if (r === "bought") LogInfo("Daily offer bought")
GetAuction()
Current state at the auctioneer.
Returns { HasFinished, Endtime, NumBids, CurrentBid, MinimumBid, HighestBidder, CurrentItem, Resources, … }
const a = GetAuction()
LogInfo(a.CurrentItemLong, "– bid", a.CurrentBid, "– ends in", FormatDuration(a.Endtime))
BidAuction(ref, rohstoffe)
Bids at the auctioneer with a planet's resources.
Returns –
const a = GetAuction()
if (!a.HasFinished && a.HighestBidder !== GetUserInfo().PlayerName)
    BidAuction(GetHomeWorld(), { Metal: a.MinimumBid })
BidAuctionMinimum()
TBot function: bids the minimum in the running auction from the repatriation target (or the first planet that has enough). The result comes as a Telegram message.
Returns –
const a = GetAuction()
if (a && !a.HasFinished) BidAuctionMinimum()
Notifications 3 Notify · NotifyDiscord · NotifyTelegram
Notify(text, titel?)
Sends a message to all set-up channels: Discord (the bot's settings) and Telegram (Bots → Global). Max. 60 per hour and bot.
Returns { Discord, Telegram } – each true if sent
const f = FleetSave(GetHomeWorld(), "06:30")
Notify("Back at " + FormatTime(f.ReturnAt) + ", deut " + FormatNumber(f.Fuel), "Fleet save started")
NotifyDiscord(text, titel?)
Discord only (webhook from the bot settings).
Returns true | false
if (IsUnderAttack()) NotifyDiscord("Attack on " + GetAttacks()[0].DestinationName, "⚠️ Attack")
NotifyTelegram(text, titel?)
Telegram only (Telegram bot from Bots → Global).
Returns true | false
NotifyTelegram("Daily offer: " + BuyOfferOfTheDay())

Automation

HIVE modules 4 StartModule · StopModule · IsModuleActive · DefenderOnExit
StartModule(name)
Switches a module on – exactly like the switch on the modules page (modules are only on or off, there is no pause). Name technical ("Expeditions", "Defender") or German ("Expeditionen"). Only this module starts, the others keep running undisturbed.
Returns true | false
StartModule("Expeditions")
StopModule(name, sofort?)
Switches a module off – like the switch on the modules page, visible to you there and switchable on again by hand any time. Buildings, research and the lifeform modules: if resources for their build orders are already on their way, they still build with them after arrival (status “finishing”, no new transports) and are then fully off. now = true switches them off without that.
Returns true | false
// the script handles the expeditions itself
StopModule("Expeditions")
IsModuleActive(name)
Whether a module is switched on (state of the switch).
Returns true | false
if (!IsModuleActive("Defender")) StartModule("Defender")
DefenderOnExit()
Guarantee for attack protection: when this script ends – normally, via “stop”, through an error, because the bot restarts or because HIVE was closed (then at the next HIVE start) – HIVE switches attack protection on. If it had to be switched on, an “IMPORTANT” Discord message (with @here) comes with bot, script, reason and time; if switching on fails, a message that you have to check by hand right away. Call once at the start of the script.
Returns –
DefenderOnExit()
// ... attack protection may be off for a while now:
StopModule("Defender")
TBot features & profiles 5 IsFeatureRunning · ListProfiles · GetRunningProfiles · LoadProfile · ResetProfile
IsFeatureRunning(feature)
Whether a TBot feature is actually running right now (e.g. not during the sleep plan). Switch on and off: StartModule/StopModule.
Returns true/false
LogInfo("Defender running:", IsFeatureRunning(FEATURE.Defender))
ListProfiles()
Names of the TBot profiles in the bot's profiles folder.
Returns list of texts
LogInfo(ListProfiles())
GetRunningProfiles()
Which profiles are loaded right now.
Returns list of texts
LogInfo("Active:", GetRunningProfiles())
LoadProfile(name | [namen])
Loads one or more TBot profiles (settings overlays, Telegram /profile load).
Returns –
LoadProfile(IsTimeBetween("23:00", "07:00") ? "Night" : "Day")
ResetProfile()
Takes back all loaded profiles (base settings).
Returns –
ResetProfile()
Sleep mode 4 StartSleepMode · WakeUpNow · CancelGhostSleep · GetNextWakeTime
StartSleepMode(bis)
Sends the bot to sleep right away (like Telegram /sleep) – incl. fleet save if set in the sleep mode. until = "HH:MM", timestamp or seconds from now.
Returns –
StartSleepMode("07:30")
WakeUpNow()
Wakes the bot up right away (Telegram /wakeup).
Returns –
if (IsSleeping() && IsUnderAttack()) WakeUpNow()
CancelGhostSleep()
Cancels a planned ghost sleep while the fleets haven't left yet (Telegram /cancelghostsleep).
Returns –
CancelGhostSleep()
GetNextWakeTime()
When the bot wakes up from the current sleep.
Returns timestamp or null
const t = GetNextWakeTime()
if (t) LogInfo("Wakes up at", FormatTime(t))
Control scripts 7 StartScript · StopScript · PauseScript · ResumeScript · IsScriptRunning · GetScriptState · ListScripts
StartScript(name, args?)
Starts another script of this bot, optionally with start parameters (as args in the target script).
Returns true if started
StartScript("Transport", { target: "1:20:8", amount: 500 })
StopScript(name)
Stops a running script (its OnExit still runs).
Returns true if it was running
if (IsUnderAttack()) StopScript("Expos")
PauseScript(name)
Pauses a running script.
Returns true | false
PauseScript("FarmRound")
SleepMin(15)
ResumeScript("FarmRound")
ResumeScript(name)
Resumes a paused script.
Returns true | false
if (GetScriptState("Expos") === "paused") ResumeScript("Expos")
IsScriptRunning(name)
Whether a script is running or paused.
Returns true | false
if (!IsScriptRunning("Guard")) StartScript("Guard")
GetScriptState(name)
State of a script.
Returns "running" | "paused" | "stopped" | "finished" | "error"
if (GetScriptState("Expos") === "error") StartScript("Expos")   // restart after an error
ListScripts()
All scripts of this bot with state and autostart flag.
Returns [ { Name, State, Autostart } ]
for (const s of ListScripts()) LogInfo(s.Name, s.State, s.Autostart ? "(Autostart)" : "")
Signals & shared values 4 SendSignal · WaitSignal · SetShared · GetShared
SendSignal(skript, daten?)
Sends a message to a running script.
Returns true if delivered
SendSignal("Expos", { pause: true, reason: "fleet save" })
WaitSignal(timeoutSek?)
Waits for the next message to this script (without a timeout: forever).
Returns { from, data } | null bei Timeout
const msg = WaitSignal(60)
if (msg && msg.data.pause) {
    LogInfo("Pause requested by", msg.from)
    SleepMin(10)
}
SetShared(schlüssel, wert)
Stores a value all scripts of the bot can read (until HIVE restarts). Value undefined deletes it.
Returns –
SetShared("fleetSaveActive", true)
// … save the fleet …
SetShared("fleetSaveActive", false)
GetShared(schlüssel, standard?)
Reads a shared value.
Returns value | default | null
while (GetShared("fleetSaveActive", false)) SleepSec(30)
Permanent storage 5 StorePut · StoreGet · StoreHas · StoreDelete · StoreKeys
StorePut(schlüssel, wert)
Stores a value PERMANENTLY (survives script and HIVE restarts). Any value: number, text, object, list. Max. 5 MB per bot.
Returns –
const today = new Date().toISOString().slice(0, 10)
StorePut("expo:" + today, ExpeditionStats(24))
StoreGet(schlüssel, standard?)
Reads a permanently stored value, otherwise default (or null).
Returns value | default
const cfg = StoreGet("config", { lcPerExpo: 4000, systems: 2 })
LogInfo("LC per expedition:", cfg.lcPerExpo)
StoreHas(schlüssel)
Whether a key is stored.
Returns true | false
if (!StoreHas("config")) StorePut("config", { lcPerExpo: 4000 })
StoreDelete(schlüssel)
Deletes a stored value.
Returns –
StoreDelete("tmp:fleetsave")
StoreKeys(präfix?)
All stored keys (optionally with a prefix only).
Returns [ text ]
for (const k of StoreKeys("expo:")) LogInfo(k, StoreGet(k).Count, "expeditions")
Global storage (all bots) 6 GlobalPut · GlobalGet · GlobalGetEntry · GlobalHas · GlobalDelete · GlobalKeys
GlobalPut(schlüssel, wert)
Stores a value in the global storage all bots can read. Every entry remembers automatically which bot (and universe) wrote it last. Survives restarts.
Returns –
GlobalPut("settings/" + InstanceName, { expoSlots: 5 })
GlobalGet(schlüssel, standard?)
Reads a value from the global storage (no matter which bot wrote it).
Returns the stored value | default | null
const e = GlobalGet("settings/" + InstanceName, {})
LogInfo(e)
GlobalGetEntry(schlüssel)
Like GlobalGet, but with its origin: which bot, which universe, when last written.
Returns { Value, Bot, Universe, UpdatedAt } | null
const e = GlobalGetEntry("settings/" + InstanceName)
if (e) LogInfo("from", e.Bot, "in", e.Universe, "at", FormatTime(e.UpdatedAt))
GlobalHas(schlüssel)
Whether the key exists in the global storage.
Returns true/false
if (!GlobalHas("settings/" + InstanceName)) StartScript("Settings")
GlobalDelete(schlüssel)
Deletes an entry from the global storage.
Returns –
GlobalDelete("test")
GlobalKeys(präfix?, bot?)
All entries in the global storage with their origin (optionally with a prefix only and/or from one bot only).
Returns [ { Key, Bot, Universe, UpdatedAt } ]
for (const e of GlobalKeys("settings/")) LogInfo(e.Key, "–", e.Bot, e.Universe)
Dashboard & form 4 SetDashboardCard · RemoveDashboardCard · FORM · GetFormValues
SetDashboardCard(id, kasten)
Creates or updates a card of its own on the bot's dashboard (same id = same card). It stays, even after the script ends and HIVE restarts, until RemoveDashboardCard or the “×” on the dashboard removes it. card: { title, text (multi-line), rows ([[label, value], …] or { label: value }), level ("info" | "success" | "warning" | "danger" = colour of the left edge), icon (e.g. "rocket", "planet", "shield") }.
Returns –
const r = GetResources(GetHomeWorld())
SetDashboardCard("storage", {
    title: "Homeworld storage",
    level: r.Deuterium < 1000000 ? "warning" : "success",
    rows: { Metal: FormatNumber(r.Metal), Crystal: FormatNumber(r.Crystal), Deuterium: FormatNumber(r.Deuterium) },
    text: "As of " + TimeOfDay(),
})
RemoveDashboardCard(id)
Removes a card created with SetDashboardCard from the dashboard.
Returns –
function OnExit() {
    RemoveDashboardCard("storage")
}
const FORM = { … }
A form of its own for a script: sits at the top of the script and contains fixed values only. The scripts page then shows it before the code (switch “form | code”), the script reads the values with GetFormValues(). Structure: { title, description, sections: [ { title, description, collapsed, fields: [ … ] } ] } or directly fields: [ … ]. Field: { key, label, type, default, help, placeholder, min, max, step, options }. type: "text", "textarea", "number", "bool", "time" (HH:MM:SS), "select" / "multiselect" (options: ["A", "B"] or [{ value, label }]), "celestial" / "celestials" (own planets/moons as "1:2:3" or "1:2:3:3").
Returns –
const FORM = {
    title: "Transport",
    fields: [
        { key: "target", label: "Target", type: "celestial" },
        { key: "amount", label: "Deuterium", type: "number", default: 100000, min: 0 },
        { key: "now", label: "Send right away", type: "bool", default: true },
    ],
}

const values = GetFormValues()
LogInfo(values.target, values.amount, values.now)
GetFormValues(skript?)
Values of this script's form (const FORM): saved values, otherwise the default values. With a script name: the form of another script of the same bot (e.g. a shared settings script).
Returns { key: value, … }
const cfg = GetFormValues("Settings")
if (cfg.active) LogInfo("Target:", cfg.target)

Universe (bots among each other)

Bots & roles 3 UniBots · UniRole · UniMain
UniBots()
All bots in the same universe as this one (including itself, Self = true), with their role from “Bot settings” › “Role in the universe”. Information only – accounts with the same IP must not have fleet contact with each other.
Returns [{ Alias, Role ("main" | "guard" | "none"), Protects, LoggedIn, PlayerName, Self }]
for (const b of UniBots())
    LogInfo(b.Alias, b.Role, b.LoggedIn ? "online" : "offline")
UniRole()
This bot's role in the universe.
Returns "main" | "guard" | "none"
if (UniRole() === "guard") LogInfo("I'm watching over", UniMain())
UniMain()
The main account this bot belongs to: itself, the one set for the guard, otherwise the universe's main account.
Returns bot name | null
const main = UniMain()
if (main) UniSend("note", { text: "Player X active" }, main)
Messages 2 UniSend · UniReceive
UniSend(thema, daten?, an?)
Sends a message to all other bots of the universe (or only to the bot “to”). The last 300 messages per universe can be read until HIVE restarts. The threat assessment itself sends under the topic "attack".
Returns message ID
UniSend("active", { player: "Raider", system: "1:120" })
UniReceive(thema?)
New messages to this bot since the last call (on the first call: since the script started), optionally of one topic only. Own messages don't come back.
Returns [{ Id, At, From, To, Topic, Data }]
while (true) {
    for (const m of UniReceive("attack"))
        LogWarn(m.From, "is under attack:", m.Data.attacker, "→", m.Data.target, "level", m.Data.level)
    SleepRandSec(20, 40)
}
Shared values & reservations 6 UniShare · UniGet · UniGetEntry · UniReserve · UniRelease · UniHolder
UniShare(schlüssel, wert, minuten?)
Stores a value for all bots of the universe, optionally valid for some minutes only. null deletes it. Lives in memory only (until HIVE restarts) – GlobalPut stores permanently.
Returns –
UniShare("inactives/1:120", GetCachedSystem(1, 120), 60)
UniGet(schlüssel, standard?)
Reads a value stored with UniShare (from any bot of the universe).
Returns the value | default | null
const sys = UniGet("inactives/1:120")
if (!sys) ScanSystem(1, 120)
UniGetEntry(schlüssel)
Like UniGet, with its origin.
Returns { Value, From, At } | null
const e = UniGetEntry("inactives/1:120")
if (e) LogInfo("from", e.From, "at", e.At)
UniReserve(schlüssel, minuten?)
Reserves something for this bot (default 30 minutes), e.g. a farm target – so two bots don't do the same. true = belongs to this bot now (was free, expired or already its own; then extended), false = another bot holds it.
Returns true/false
if (UniReserve("farm/1:120:8", 45))
    LogInfo("Target is mine")
else
    LogInfo("Target reserved by", UniHolder("farm/1:120:8"))
UniRelease(schlüssel)
Releases an own reservation early.
Returns –
UniRelease("farm/1:120:8")
UniHolder(schlüssel)
Which bot currently holds a reservation.
Returns bot name | null
LogInfo(UniHolder("farm/1:120:8") ?? "free")
Threat assessment 1 GetThreats
GetThreats()
This bot's current threat assessment (every 20 s from TBot's event list, no game requests): per attack level, target, attacker, arrival, ships, the attacker's chance to win (techs unknown, none on either side), possible loot and own fleets landing around the arrival – with the landing time if recalled now.
Returns [{ Level ("green" | "yellow" | "red"), Target, TargetName, TargetIsMoon, Attacker, AttackerId, Origin, Arrival, ArriveIn, Fleets, OnlyProbes, ShipsKnown, Ships, Missiles, AttackerWinChance, Loot, Collisions: [{ FleetId, Mission, ReturnFlight, Lands, MinutesFromArrival, Ships, Cargo, RecallLands, RecallHelps }], Reasons }]
for (const t of GetThreats()) {
    for (const c of t.Collisions)
        if (c.RecallHelps) { LogWarn("Recalling fleet", c.FleetId); CancelFleet(c.FleetId) }
}

Careful

Irreversible actions 11 AbandonPlanet · TearDown · SendIPM · DeleteEspionageReport · DeleteAllEspionageReports · DeleteAllMessages · ActivateItem · SendPlayerMessage · MessageAttackers · PostGamePage · GameLogout
AbandonPlanet(ref, "BESTÄTIGT")
Abandons an own planet – IRREVERSIBLE. Without the confirmation word as the second argument nothing happens.
Returns true | false
const p = GetCelestial("1:400:8")
if (p.Fields.Total < 150 && p.Fields.Built === 0)
    AbandonPlanet(p, "BESTÄTIGT")
TearDown(ref, gebäude, "BESTÄTIGT")
Tears a building down by one level (costs resources, frees fields). Only with the confirmation word.
Returns –
// tear down a lunar base level to free a field
TearDown("1:16:4:3", BUILDING.LunarBase, "BESTÄTIGT")
SendIPM(von, ziel, anzahl, [primärziel], "BESTÄTIGT")
Fires interplanetary missiles from an own planet at a target. Primary target optional (e.g. DEFENCE.PlasmaTurret), otherwise any defence is hit. Needs a missile silo and range (impulse drive).
Returns flight time of the missiles in seconds
const sec = SendIPM("Home planet", "1:20:8", 10, DEFENCE.PlasmaTurret, "BESTÄTIGT")
LogInfo("Impact in", FormatDuration(sec))
DeleteEspionageReport(meldungsId, "BESTÄTIGT")
Deletes an espionage report.
Returns –
for (const b of GetEspionageReports())
    if (b.LootPercentage < 0.5) DeleteEspionageReport(b.ID, "BESTÄTIGT")
DeleteAllEspionageReports("BESTÄTIGT")
Deletes all espionage reports.
Returns –
DeleteAllEspionageReports("BESTÄTIGT")
DeleteAllMessages(tab, "BESTÄTIGT")
Empties a whole message tab: MESSAGE_TAB.ESPIONAGE, COMBAT, EXPEDITIONS, TRANSPORT or OTHER (also as text, e.g. "kampf").
Returns –
// clean up expedition and combat reports once a day
DeleteAllMessages(MESSAGE_TAB.EXPEDITIONS, "BESTÄTIGT")
DeleteAllMessages(MESSAGE_TAB.COMBAT, "BESTÄTIGT")
ActivateItem(ref, itemRef, "BESTÄTIGT")
Activates an item/booster on a celestial (itemRef from GetItems). Uses up the item.
Returns ogamed's answer
const booster = GetItems(home).find(i => i.Name === "Bronze Deuterium Booster" && i.Amount > 0)
if (booster) ActivateItem(home, booster.Ref, "BESTÄTIGT")
SendPlayerMessage(spielerId, text, "BESTÄTIGT")
Sends another player an in-game message (visible to them – use with care).
Returns –
for (const a of GetAttacks())
    SendPlayerMessage(a.AttackerID, "Nothing to get here.", "BESTÄTIGT")
MessageAttackers(text, "BESTÄTIGT")
TBot function (/msg): sends all players currently attacking you the same in-game message (each only once).
Returns –
if (IsUnderAttack()) MessageAttackers("The fleet is gone and so are the resources – save your fuel.", "BESTÄTIGT")
PostGamePage(seite, formulardaten, "BESTÄTIGT")
Sends a form directly to a game page (e.g. marketplace, trader, dark matter). For everything without a function of its own – you need the game's exact parameters. Signing out is blocked.
Returns the game's answer as text (read JSON answers with JSON.parse)
const answer = PostGamePage("page=ingame&component=marketplace&tab=history_buying&action=collectItem&asJson=1",
    { marketItemId: 12345, token: "…" }, "BESTÄTIGT")
LogInfo(answer)
GameLogout("BESTÄTIGT")
Signs out of the game session. Careful: the bot uses the same session and only continues after GameLogin().
Returns –
GameLogout("BESTÄTIGT")
SleepMin(RandomInt(20, 40))
GameLogin()