Scripting Manual

Intro

NJA Scripts are running in a supervised environment allowing to :

  • have access to NJA API: NJA internal data structures and low-level functions
  • stop/start/create scripts at any moment
  • schedule tasks

For scripting anko Programming Language is used.

Programming Basics

Code Comments

// All below are comments and are not executed. This one is so called "one line comment", it comment out everything after '//' symbol

/*
Next one is
 several
  lines
   comment
*/

Variables

// Define a global variable called 'name' and assigning it with a value
name = "Johny"

// Changing the value of variable from 'Johny' to 'Tommy' by assigning (=) a new value
name = "Tommy" 

Special Scripts

You can create a script with the exact name:
!global.ank any variable or function inside will be available from any of your scripts.
!sleep.ank will be executed before the bot goes to sleep mode.
!wake.ank will be executed after the bot exit the sleep mode.

Loops

for i = 0; i < 5; i++ {
    Print(i)
}
for el in [10, 20, 30, 40, 50] {
    Print(el)
}
for key, value in {"a": "b", "c": "d", 1: 12, true: false} {
    Print(key, value)
}
for shipID in ShipsArr {
    Print(shipID)
}

How to sort

sort = import("sort")
arr = [["c", 3], ["a", 1], ["b", 2]]
sort.Slice(arr, func(i, j) { return arr[i][1] < arr[j][1] })
Print(arr) // [[[a 1] [b 2] [c 3]]]

How to use json

json = import("encoding/json")
s = `{"a": 1, b": 2.1, "c": "a string", "d": true}`
out = nil
json.Unmarshal(s, &out)
Print(out["a"])

out, err = JsonDecode(s) // This would also work
Print(out, err)
fmt = import("fmt")
json = import("encoding/json")
s = NewShipsInfos()
s.Set(SMALLCARGO, 1)
s.Set(LARGECARGO, 2)
bytes, _ = json.Marshal(s)
Print(fmt.Sprintf("%s", bytes))

How to debug errors

syntax error

If you receive a message that looks like:

22:20:11 ERROR [[9:24] syntax error]

It means that you have a syntax error at line 9, charaSendMessagecter 24.

does not support member operation

22:36:13 ERROR [[46:34] type invalid does not support member operation]

Means that you are trying to call a "method" on a variable that is not an "object".
It would usually look like notAnObject.method().
One way to know what's going on is to Print(notAnObject), and rerun the script to know what's the value of notAnObject.

function wants X arguments but received Y

23:10:21 ERROR [[24:23] function wants 1 arguments but received 3]

This happens when you call a function that only takes X argument, but you are giving it Y.
Example:

planet = GetPlanet(1, 2, 3) // Triggers error: function wants 1 arguments but received 3

Should actually be something like:

planet = GetPlanet("1:2:3")

no member named 'xxx' for struct

23:56:42 ERROR [[29:12] no member named 'max' for struct]

This occurs when you try to get a property that does not exists.

planet, _ = GetPlanet("1:2:3")
Print(planet.Temperature.max) // Triggers error: no member named 'max' for struct
Print(planet.Temperature.Max) // This is the correct name

function wants argument type X but received type Y

00:02:03 ERROR [[73:40] function wants argument type func() but received type bool]

This happens when the wrong type of argument is given to a function.

func callback() {
    return true
}
ExecIn(1000, callback()) // Trigger error: function wants argument type func() but received type bool
                         // In this example, you are actually calling the callback function and giving
                         // "true" as a parameter to ExecIn.
ExecIn(1000, callback)   // This is the correct way.
Sleep(2000)

Scripting API

Constants

ShipsArr = [SMALLCARGO, LARGECARGO, LIGHTFIGHTER, HEAVYFIGHTER, CRUISER, BATTLESHIP, COLONYSHIP, RECYCLER, ESPIONAGEPROBE, BOMBER, DESTROYER, DEATHSTAR, BATTLECRUISER, CRAWLER, REAPER, PATHFINDER]
DefencesArr = [ROCKETLAUNCHER, LIGHTLASER, HEAVYLASER, GAUSSCANNON, IONCANNON, PLASMATURRET, SMALLSHIELDDOME, LARGESHIELDDOME, ANTIBALLISTICMISSILES, INTERPLANETARYMISSILES]
TechnologiesArr = [ESPIONAGETECHNOLOGY, COMPUTERTECHNOLOGY, WEAPONSTECHNOLOGY, SHIELDINGTECHNOLOGY, ARMOURTECHNOLOGY, ENERGYTECHNOLOGY, HYPERSPACETECHNOLOGY, COMBUSTIONDRIVE, IMPULSEDRIVE, HYPERSPACEDRIVE, LASERTECHNOLOGY, IONTECHNOLOGY, PLASMATECHNOLOGY, INTERGALACTICRESEARCHNETWORK, ASTROPHYSICS, GRAVITONTECHNOLOGY]
BuildingsArr = [METALMINE, CRYSTALMINE, DEUTERIUMSYNTHESIZER, SOLARPLANT, FUSIONREACTOR, SOLARSATELLITE, METALSTORAGE, CRYSTALSTORAGE, DEUTERIUMTANK, SHIELDEDMETALDEN, UNDERGROUNDCRYSTALDEN, SEABEDDEUTERIUMDEN, ALLIANCEDEPOT, ROBOTICSFACTORY, SHIPYARD, RESEARCHLAB, MISSILESILO, NANITEFACTORY, TERRAFORMER, SPACEDOCK, LUNARBASE, SENSORPHALANX, JUMPGATE]
PlanetBuildingsArr = [METALMINE, CRYSTALMINE, DEUTERIUMSYNTHESIZER, SOLARPLANT, FUSIONREACTOR, SOLARSATELLITE, METALSTORAGE, CRYSTALSTORAGE, DEUTERIUMTANK, SHIELDEDMETALDEN, UNDERGROUNDCRYSTALDEN, SEABEDDEUTERIUMDEN, ALLIANCEDEPOT, ROBOTICSFACTORY, SHIPYARD, RESEARCHLAB, MISSILESILO, NANITEFACTORY, TERRAFORMER, SPACEDOCK]
MoonBuildingsArr = [SOLARSATELLITE, METALSTORAGE, CRYSTALSTORAGE, DEUTERIUMTANK, ROBOTICSFACTORY, SHIPYARD, LUNARBASE, SENSORPHALANX, JUMPGATE]
// Missions
ATTACK             = 1
GROUPEDATTACK      = 2
TRANSPORT          = 3
PARK               = 4
PARKINTHATALLY     = 5
SPY                = 6
COLONIZE           = 7
RECYCLEDEBRISFIELD = 8
DESTROY            = 9
MISSILEATTACK      = 10
EXPEDITION         = 15

// Speed
TEN_PERCENT     = 1
TWENTY_PERCENT  = 2
THIRTY_PERCENT  = 3
FORTY_PERCENT   = 4
FIFTY_PERCENT   = 5
SIXTY_PERCENT   = 6
SEVENTY_PERCENT = 7
EIGHTY_PERCENT  = 8
NINETY_PERCENT  = 9
HUNDRED_PERCENT = 10

// Celestial types
PLANET_TYPE = 1
DEBRIS_TYPE = 2
MOON_TYPE   = 3
TELEGRAM_CHAT_ID = (alias to telegram chat id bot setting)
OGAME_SERVER = (ogame server information)
__FILE__ // Name of current script file
GALAXIES // Number of galaxies in the universe
SYSTEMS  // Number of systems in a galaxy

Internal Types

ID

// ID represent an ogame id
type ID int64

// Methods
IsSet() bool
Int64() int64
String() string
IsFacility() bool
IsResourceBuilding() bool
IsBuilding() bool
IsTech() bool
IsDefense() bool
IsShip() bool

CharacterClass

type CharacterClass int64
NO_CLASS   // 0
COLLECTOR  // 1
GENERAL    // 2
DISCOVERER // 3

Celestial

// Celestial ...
type Celestial interface {
    GetID() CelestialID
    GetType() CelestialType
    GetName() string
    GetCoordinate() Coordinate
    GetFields() Fields
    GetResources() (Resources, error)
    GetResourcesDetails() (ResourcesDetails, error)
    GetFacilities() (Facilities, error)
    SendFleet([]Quantifiable, Speed, Coordinate, MissionID, Resources, int64) (Fleet, error)
    EnsureFleet([]Quantifiable, Speed, Coordinate, MissionID, Resources, int64) (Fleet, error)
    GetDefense() (DefensesInfos, error)
    GetShips() (ShipsInfos, error)
    BuildDefense(defenseID ID, nbr int64) error
    ConstructionsBeingBuilt() (ID, int64, ID, int64)
    GetProduction() ([]Quantifiable, int64, error)
    GetResourcesBuildings() (ResourcesBuildings, error)
    Build(id ID, nbr int64) error
    BuildBuilding(buildingID ID) error
    BuildTechnology(technologyID ID) error
    CancelResearch() error
    CancelBuilding() error
}

Planet

// Planet ogame planet object
type Planet struct {
	Img         string
	ID          PlanetID
	Name        string
	Diameter    int64
	Coordinate  Coordinate
	Fields      Fields
	Temperature Temperature
	Moon        *Moon
}

// Methods
// all methods of Celestial interface
BuildCancelable(id ID) error
GetResourceSettings() (ResourceSettings, error)
BuildShips(shipID ID, nbr int64) error
GetResourcesProductions() (Resources, error)
FlightTime(destination Coordinate, speed Speed, ships ShipsInfos) (secs, fuel int64)
SendIPM(planetID PlanetID, coord Coordinate, nbr int64, priority ID) (int64, error)

Moon

// Moon ogame moon object
type Moon struct {
	ID         MoonID
	Img        string
	Name       string
	Diameter   int64
	Coordinate Coordinate
	Fields     Fields
}

// Methods
// all methods of Celestial interface
Phalanx(coord Coordinate) ([]Fleet, error)

CelestialType

Type of celestial object (planet/moon/debris)

type CelestialType int64
PLANET_TYPE // 1
DEBRIS_TYPE // 2
MOON_TYPE   // 3

EspionageReportType

type EspionageReportType int64
// Action message received when an enemy is seen near your planet
const Action EspionageReportType = 0

// Report message received when you spied on someone
const Report EspionageReportType = 1

Coordinate

type Coordinate struct {
	Galaxy   int64
	System   int64
	Position int64
	Type     CelestialType
}

// Methods
Equal(v Coordinate) bool
String() string
IsPlanet() bool
IsMoon() bool
IsDebris() bool
// Compare two coordinates
coordinate1 = NewCoordinate(1, 2, 3, PLANET_TYPE)
coordinate2 = NewCoordinate(1, 2, 3, PLANET_TYPE)
if coordinate1.Equal(coordinate2) {
    Print("The coordinates are equal")
}

// Use the properties
Print("coordinate1 is in galaxy " + coordinate1.Galaxy)

Temperature

// Temperature planet temperature values
type Temperature struct {
	Min int64
	Max int64
}

// Methods
Mean() int64

Fields

// Fields planet fields stats
type Fields struct {
	Built int64
	Total int64
}

Resources

type Resources struct {
	Metal      int64
	Crystal    int64
	Deuterium  int64
	Energy     int64
	Darkmatter int64
}

// Methods
String() string
Total() int64
Value() int64
Sub(v Resources) Resources
Add(v Resources) Resources
Mul(scalar int64) Resources
Div(price Resources) int64
CanAfford(cost Resources) bool
Gte(val Resources) bool
Lte(val Resources) bool
metal = 1
crystal = 2
deuterium = 3
res1 = NewResources(metal, crystal, deuterium)
res2 = NewResources(1, 1, 1)
res3 = NewResources(3, 2, 1)
Print("Total: ", res1.Total())                  // Total: 6
Print("Value: ", res1.Value())                  // Value: 14
Print("Can afford: ", res1.CanAfford(res2))     // Can afford: true
Print("Can afford: ", res1.CanAfford(res3))     // Can afford: false
Print("Mul: ", res1.Mul(3))                     // Mul: [3|6|9]
Print("Div: ", NewResources(9, 9, 9).Div(res1)) // Div: 3

ResourcesDetails

type ResourcesDetails struct {
	Metal struct {
		Available         int64
		StorageCapacity   int64
		CurrentProduction int64
	}
	Crystal struct {
		Available         int64
		StorageCapacity   int64
		CurrentProduction int64
	}
	Deuterium struct {
		Available         int64
		StorageCapacity   int64
		CurrentProduction int64
	}
	Energy struct {
		Available         int64
		CurrentProduction int64
		Consumption       int64
	}
	Darkmatter struct {
		Available int64
		Purchased int64
		Found     int64
	}
}

// Methods
Available() Resources

UserInfos

// Currently logged in player information
type UserInfos struct {
	PlayerID     int64
	PlayerName   string
	Points       int64
	Rank         int64
	Total        int64
	HonourPoints int64
}

PlayerData

// PlayerData information returned by ogame xml API
type PlayerData struct {
	ID                        int64
	Name                      string
	Timestamp                 int64
	PointsTotal               int64
	PointsEconomy             int64
	PointsResearch            int64
	PointsMilitary            int64
	PointsMilitaryBuilt       int64
	PointsMilitaryDestroyed   int64
	PointsMilitaryLost        int64
	PointsHonor               int64
	PositionTotal             int64
	PositionEconomy           int64
	PositionResearch          int64
	PositionMilitary          int64
	PositionMilitaryBuilt     int64
	PositionMilitaryDestroyed int64
	PositionMilitaryLost      int64
	PositionHonor             int64
	MilitaryShips             int64
	Celestials                []struct {
		ID         ogame.CelestialID
		Name       string
		Coordinate ogame.Coordinate
	}
	Alliance *struct {
		ID   int64
		Name string
		Tag  string
	}
}

Auction

type Auction struct {
	HasFinished         bool
	Endtime             int64
	NumBids             int64
	CurrentBid          int64
	AlreadyBid          int64
	MinimumBid          int64
	DeficitBid          int64
	HighestBidder       string
	HighestBidderUserID int64
	CurrentItem         string
	CurrentItemLong     string
	Inventory           int64
	Token               string
	ResourceMultiplier  struct {
		Metal     float64
		Crystal   float64
		Deuterium float64
		Honor     int64
	}
	Resources map[string]interface{}
}

Fleet

// Fleet represent a player fleet information
type Fleet struct {
	Mission        MissionID
	ReturnFlight   bool
	ID             FleetID
	Resources      Resources
	Origin         Coordinate
	Destination    Coordinate
	Ships          ShipsInfos
	ArrivalTime    time.Time
	BackTime       time.Time
	ArriveIn       int64
	BackIn         int64
	UnionID        int64
	TargetPlanetID int64
}

ShipsInfos

// ShipsInfos represent a planet ships information
type ShipsInfos struct {
	LightFighter   int64
	HeavyFighter   int64
	Cruiser        int64
	Battleship     int64
	Battlecruiser  int64
	Bomber         int64
	Destroyer      int64
	Deathstar      int64
	SmallCargo     int64
	LargeCargo     int64
	ColonyShip     int64
	Recycler       int64
	EspionageProbe int64
	SolarSatellite int64
	Crawler        int64
	Reaper         int64
	Pathfinder     int64
}

// Methods

Cargo(techs Researches, probeRaids, isCollector bool) int64 // probeRaids determines if spys in your uni have cargo or not
Has(v ShipsInfos) bool
FleetValue() int64
FleetCost() Resources
CountShips() int64
ByID(id ID) int64
String() string
ToPtr() *ShipsInfos
Add(v ShipsInfos)
Set(id ID, val int64)

DefensesInfos

// DefensesInfos represent a planet defenses information
type DefensesInfos struct {
	RocketLauncher         int64
	LightLaser             int64
	HeavyLaser             int64
	GaussCannon            int64
	IonCannon              int64
	PlasmaTurret           int64
	SmallShieldDome        int64
	LargeShieldDome        int64
	AntiBallisticMissiles  int64
	InterplanetaryMissiles int64
}

// Methods
String() string
ByID(id ID) int64
Set(id ID, val int64)

AttackEvent

// AttackEvent all information available about an enemy attack
type AttackEvent struct {
	MissionType     MissionID
	Origin          Coordinate
	Destination     Coordinate
	DestinationName string
	ArrivalTime     time.Time
	ArriveIn        int64
	AttackerName    string
	AttackerID      int64
	Missiles        int64
	Ships           *ShipsInfos
}

// Methods
String() string

SystemInfos

// SystemInfos planets information for a specific system
type SystemInfos struct {
	galaxy           int64
	system           int64
	planets          [15]*PlanetInfos
    ExpeditionDebris struct {
        Metal             int64
        Crystal           int64
        PathfindersNeeded int64
    }
    Events struct {
        Darkmatter int64
    }
}

// Methods
Galaxy() int64
System() int64
Position(idx int64) *PlanetInfos

PlanetInfos

// PlanetInfos public information of a planet in the galaxy page
type PlanetInfos struct {
	ID              int64
	Activity        int64
	Name            string
	Img             string
	Coordinate      Coordinate
	Administrator   bool
	Inactive        bool
	Vacation        bool
	StrongPlayer    bool
	Newbie          bool
	HonorableTarget bool
	Banned          bool
	Debris          struct {
		Metal           int64
		Crystal         int64
		RecyclersNeeded int64
	}
	Moon   *MoonInfos
	Player struct {
		ID         int64
		Name       string
		Rank       int64
		IsBandit   bool
		IsStarlord bool
	}
	Alliance *AllianceInfos
}

AllianceInfos

// AllianceInfos public information of an alliance in the galaxy page
type AllianceInfos struct {
	ID     int64
	Name   string
	Rank   int64
	Member int64
}

MoonInfos

// MoonInfos public information of a moon in the galaxy page
type MoonInfos struct {
	ID       int64
	Diameter int64
	Activity int64
}

Facilities

// Facilities represent a planet facilities information
type Facilities struct {
	RoboticsFactory int64
	Shipyard        int64
	ResearchLab     int64
	AllianceDepot   int64
	MissileSilo     int64
	NaniteFactory   int64
	Terraformer     int64
	SpaceDock       int64
	LunarBase       int64
	SensorPhalanx   int64
	JumpGate        int64
}

// Methods
ByID(id ID) int64
String() string

Researches

// Researches represent player's researches
type Researches struct {
	EnergyTechnology             int64
	LaserTechnology              int64
	IonTechnology                int64
	HyperspaceTechnology         int64
	PlasmaTechnology             int64
	CombustionDrive              int64
	ImpulseDrive                 int64
	HyperspaceDrive              int64
	EspionageTechnology          int64
	ComputerTechnology           int64
	Astrophysics                 int64
	IntergalacticResearchNetwork int64
	GravitonTechnology           int64
	WeaponsTechnology            int64
	ShieldingTechnology          int64
	ArmourTechnology             int64
}

// Methods
ByID(id ID) int64
String() string

ResourcesBuildings

// ResourcesBuildings represent a planet resource buildings
type ResourcesBuildings struct {
	MetalMine            int64
	CrystalMine          int64
	DeuteriumSynthesizer int64
	SolarPlant           int64
	FusionReactor        int64
	SolarSatellite       int64
	MetalStorage         int64
	CrystalStorage       int64
	DeuteriumTank        int64
}

// Methods
ByID(id ID) int64
String() string

EspionageReportSummary

// EspionageReportSummary summary of espionage report
type EspionageReportSummary struct {
	ID     int64
	Type   EspionageReportType
	From   string
	Target Coordinate
}

CombatReportSummary

// CombatReportSummary summary of combat report
type CombatReportSummary struct {
	ID           int64
	Origin       *Coordinate
	Destination  Coordinate
	AttackerName string
	DefenderName string
	Loot         int64
	Metal        int64
	Crystal      int64
	Deuterium    int64
	DebrisField  int64
	CreatedAt    time.Time
}

EspionageReport

// EspionageReport detailed espionage report
type EspionageReport struct {
	Resources
	ID                           int64
	Username                     string
	LastActivity                 int64
	CounterEspionage             int64
	APIKey                       string
	HasFleet                     bool
	HasDefenses                  bool
	HasBuildings                 bool
	HasResearches                bool
	HonorableTarget              bool
	IsBandit                     bool
	IsStarlord                   bool
	IsInactive                   bool
	IsLongInactive               bool
	MetalMine                    *int // ResourcesBuildings
	CrystalMine                  *int
	DeuteriumSynthesizer         *int
	SolarPlant                   *int
	FusionReactor                *int
	SolarSatellite               *int
	MetalStorage                 *int
	CrystalStorage               *int
	DeuteriumTank                *int
	RoboticsFactory              *int // Facilities
	Shipyard                     *int
	ResearchLab                  *int
	AllianceDepot                *int
	MissileSilo                  *int
	NaniteFactory                *int
	Terraformer                  *int
	SpaceDock                    *int
	LunarBase                    *int
	SensorPhalanx                *int
	JumpGate                     *int
	EnergyTechnology             *int // Researches
	LaserTechnology              *int
	IonTechnology                *int
	HyperspaceTechnology         *int
	PlasmaTechnology             *int
	CombustionDrive              *int
	ImpulseDrive                 *int
	HyperspaceDrive              *int
	EspionageTechnology          *int
	ComputerTechnology           *int
	Astrophysics                 *int
	IntergalacticResearchNetwork *int
	GravitonTechnology           *int
	WeaponsTechnology            *int
	ShieldingTechnology          *int
	ArmourTechnology             *int
	RocketLauncher               *int // Defenses
	LightLaser                   *int
	HeavyLaser                   *int
	GaussCannon                  *int
	IonCannon                    *int
	PlasmaTurret                 *int
	SmallShieldDome              *int
	LargeShieldDome              *int
	AntiBallisticMissiles        *int
	InterplanetaryMissiles       *int
	LightFighter                 *int // Fleets
	HeavyFighter                 *int
	Cruiser                      *int
	Battleship                   *int
	Battlecruiser                *int
	Bomber                       *int
	Destroyer                    *int
	Deathstar                    *int
	SmallCargo                   *int
	LargeCargo                   *int
	ColonyShip                   *int
	Recycler                     *int
	EspionageProbe               *int
	Crawler                      *int
	Reaper                       *int
	Pathfinder                   *int
	Coordinate                   Coordinate
	Type                         EspionageReportType
	Date                         time.Time
}

// Methods
ShipsInfos() *ShipsInfos
PlunderRatio(CharacterClass) float64
Loot(CharacterClass) Resources

Server

// OGame server information
type Server struct {
	Language      string
	Number        int64
	Name          string
	PlayerCount   int64
	PlayersOnline int64
	Opened        string
	StartDate     string
	EndDate       *string
	ServerClosed  int64
	Prefered      int64
	SignupClosed  int64
	Settings      struct {
		AKS                      int64
		FleetSpeed               int64
		WreckField               int64
		ServerLabel              string
		EconomySpeed             int64
		PlanetFields             int64
		UniverseSize             int64 // Nb of galaxies
		ServerCategory           string
		EspionageProbeRaids      int64
		PremiumValidationGift    int64
		DebrisFieldFactorShips   int64
		DebrisFieldFactorDefence int64
	}
}

ResourceSettings

// ResourceSettings represent a planet resource settings
type ResourceSettings struct {
	MetalMine            int64
	CrystalMine          int64
	DeuteriumSynthesizer int64
	SolarPlant           int64
	FusionReactor        int64
	SolarSatellite       int64
    Crawler              int64
}

// Methods
String() string

FarmSession

type FarmSession struct {
	ID                       int64
	BotID                    int64
	State                    string
	PlanetID                 CelestialID
	RangeGalaxy              int64
	RangeFrom                int64
	RangeTo                  int64
	NbProbes                 int64
	PctCargo                 int64
	CreatedAt                time.Time
	MinimumResourcesToAttack int64
	MinimumDefensesToIgnore  int64
	MinimumMetalStorage      int64
	MinimumCrystalStorage    int64
	MinimumDeuteriumTank     int64
	MinimumPlayerRank        int64
	TotalTargets             int64
	EspionageProbeRaids      bool
	Phase                    int64
	Progress                 int64
	ProgressAttacks          int64
	FarmType                 int64
	FuelConsumption          int64
	MetalRatio               float64
	CrystalRatio             float64
	DeuteriumRatio           float64
	FarmSpeed                Speed
	FastAttacking            bool
	UsePathfinders           bool
	SkipAfter                int64
	AttackFromNearestPlanet  bool
	AttackFromNearestMoon    bool
	DeleteCombatReports      bool
	Planet                   BotPlanet
}

// Methods
TotalSystems() int64
Pause()
Resume()

FleetBuilder

type FleetBuilder struct {
}

// Methods
SetOrigin(v interface{}) *FleetBuilder
SetDestination(v interface{}) *FleetBuilder
SetSpeed(speed Speed) *FleetBuilder
SetResources(resources Resources) *FleetBuilder
SetAllResources() *FleetBuilder
SetAllMetal() *FleetBuilder
SetAllCrystal() *FleetBuilder
SetAllDeuterium() *FleetBuilder
SetMinimumDeuterium(minimumDeuterium int64) *FleetBuilder
SetMission(mission MissionID) *FleetBuilder
SetDuration(expeditiontime int64) *FleetBuilder
SetUnionID(unionID int64) *FleetBuilder
AddShips(id ID, nbr int64) *FleetBuilder
SetShips(ships ShipsInfos) *FleetBuilder
SetAllShips() *FleetBuilder
SetRecallIn(secs int64) *FleetBuilder
FlightTime() (secs, fuel int64)
SendNow() (Fleet, error)
OnError(clb func(error)) *FleetBuilder
OnSuccess(clb func(Fleet)) *FleetBuilder

FarmSessionBuilder

type FarmSessionBuilder struct {
}

// Methods
SetOrigin(v interface{}) *FarmSessionBuilder
SetRange(galaxy, systemFrom, systemTo int64) *FarmSessionBuilder
SetProbes(nbProbes int64) *FarmSessionBuilder
SetAdditionalCargo(pctCargo int64) *FarmSessionBuilder
SetMinimumResourcesToAttack(minimumResourcesToAttack int64) *FarmSessionBuilder
SetMinimumDefensesToIgnore(minimumDefensesToIgnore int64) *FarmSessionBuilder
SetMinimumStorageToIgnore(metal, crystal, deuterium int64) *FarmSessionBuilder
SetMinimumPlayerRank(rank int64) *FarmSessionBuilder
SetEspionageProbeRaids(enabled bool) *FarmSessionBuilder
SetUsePathfinders(enabled bool) *FarmSessionBuilder
SetIgnoreActivity(enabled bool) *FarmSessionBuilder
SetFastAttacking(enabled bool) *FarmSessionBuilder
SetDeleteCombatReports(enabled bool) *FarmSessionBuilder
SetAttackFromNearestPlanet(enabled bool) *FarmSessionBuilder
SetAttackFromNearestMoon(enabled bool) *FarmSessionBuilder
SetFarmSpeed(Speed) *FarmSessionBuilder
SetPriorityRatio(metal, crystal, deuterium float64) *FarmSessionBuilder
BuildFarmSession() (*FarmSession, error)

ACSFlightTime

type ACSFlightTime struct {
	ArriveIn      int64
	HumanArriveIn string
	ArriveAt      time.Time
	HumanArriveAt string
	Fuel          int64
	Groups        []ACSFlightTimeGroup
}

ACS

type ACS struct {
}

// Methods
GetFlightTimes() ACSFlightTime
AddGroup(delaySecs int64, speed Speed, ships ShipsInfos) *ACS
Execute()
ExecuteAsync()
GetUnionID() int64
GetFleetIDs() []FleetID

ChatMsg

type ChatMsg struct {
	SenderID      int64
	SenderName    string
	AssociationID int64
	Text          string
	ID            int64
	Date          int64
}

TelegramMessage

type TelegramMessage struct {
	MessageID int64
	From      struct {
		ID           int64
		IsBot        bool
		FirstName    string
		LastName     string
		Username     string
		LanguageCode string
	}
	Chat struct {
		ID        int64
		FirstName string
		LastName  string
		Username  string
		Type      string
	}
	Date int64
	Text string
}

Channels (events)

OnAttackCh

// Triggered when a new attack is detected
OnAttackCh chan AttackEvent

OnAttackDoneCh

// Triggered once an attack is done
OnAttackDoneCh chan AttackEvent

OnAttackCancelledCh

// Triggered when an attack is cancelled
OnAttackCancelledCh chan AttackEvent

OnQuitCh

// Triggered when `Exit` is called
OnQuitCh chan struct{}
ExecIn(2000, func() {
    Exit()
})
<-OnQuitCh
Print("Exiting")

OnFarmSessionStart

// Triggered when a farm session starts
OnFarmSessionStart chan *FarmSession
for {
    s = <-OnFarmSessionStart
    Print("Start new session " + s.ID)
}

OnFarmSessionAttacksSent

// Triggered when all attacks are sent
OnFarmSessionAttacksSent chan *FarmSession
for {
    s = <-OnFarmSessionAttacksSent
    Print("All attacks sent for session " + s.ID)
}

OnFarmSessionDone

// Triggered when all attacks are back home
OnFarmSessionDone chan *FarmSession
for {
    s = <-OnFarmSessionDone
    Print("All attacks are back home for session " + s.ID)
}

OnTelegramMessageReceivedCh

// Triggered when a private message is received from telegram
OnTelegramMessageReceivedCh chan TelegramMessage
for {
    m = <-OnTelegramMessageReceivedCh
    Print(m.Text)
}

OnChatMessageReceivedCh

// Triggered when a private message is received in ogame (unstable)
OnChatMessageReceivedCh chan ChatMsg
for {
    m = <-OnChatMessageReceivedCh
    Print("From: " + m.SenderName + ", msg: " + m.Text)
}

Global API

Sleep

// Sleeps a defined number of milliseconds
Sleep(milliseconds int64)
Print("Before")
Sleep(5 * 60 * 1000) // Execution of the script will stop here for 5min
Print("After")

Random

// Random generates a number between min and max inclusively
Random(min, max int64)
randomDelay = Random(1000, 5000)
Sleep(randomDelay)
Print("Done sleeping")

Print

// Print some variables
Print(args ...interface{})
Print("Example", 123, true)

print

// Same as Print
print(args ...interface{})

LogDebug

// Same as Print
LogDebug(args ...interface{})

LogInfo

// Creates an Info log
LogInfo(args ...interface{})

LogWarn

// Creates an Warn log
LogWarn(args ...interface{})

LogError

// Creates an Error log
LogError(args ...interface{})

ClearOut

// Clears the output
ClearOut()

RepatriateNow

// Trigger the repatriate feature now and reset the timer
RepatriateNow()
RepatriateNow()

AddItemToQueue

// Add something into a planet/moon build queue
// The "nbr" parameter is only useful for ships and defenses.
AddItemToQueue(celestialID CelestialID, id ID, nbr int64) error
planet = GetCachedPlanets()[0]
err = AddItemToQueue(planet.GetID(), SOLARPLANT, 0)
Print(err)
err = AddItemToQueue(planet.GetID(), BOMBER, 1)
Print(err)
err = AddItemToQueue(planet.GetID(), ROCKETLAUNCHER, 2)
Print(err)
err = AddItemToQueue(planet.GetID(), BOMBER, 0)
Print(err)

GetPrice

// Returns the price of 'entity'. 'nbr' is either a building/research level or a defense/ship quantity.
GetPrice(entityID ID, nbr int64) (Resources)
price = GetPrice(LIGHTFIGHTER, 5)
Print("The price of 5 LF is ", price) // [15,000|5,000|0]

price = GetPrice(METALMINE, 3)
Print("The price of metal mine level 3 is ", price) // [135|33|0]

ConstructionTime

// ConstructionTime returns the duration it takes to build a given level.
// Second argument is either the building level or the number of ships/defences to build
ConstructionTime(ogame.ID, int64, ogame.Facilities) time.Duration
celestial = GetCachedCelestials()[0]
facilities, _ = celestial.GetFacilities()
Print(ConstructionTime(METALMINE, 20, facilities))      // 9m4s
Print(ConstructionTime(LARGECARGO, 20, facilities))     // 16m0s
Print(ConstructionTime(ROCKETLAUNCHER, 20, facilities)) // 2m40s

SolarSatelliteProduction

// Returns the energy production of solar satellite.
SolarSatelliteProduction(temp Temperature, nbr int64) (energy int64)
temp = NewTemperature(-12, 40)
energy = SolarSatelliteProduction(temp, 123)
Print("Energy produced is ", energy)

planet = GetCachedPlanets()[0]
energy = SolarSatelliteProduction(planet.Temperature, 123)
Print("Energy produced is ", energy)

IgnorePlanet

// Adds a planet to the avoid list
IgnorePlanet(int64) error
IgnorePlanet(1234567)

IgnorePlayer

// Adds a player to the avoid list
IgnorePlayer(int64) error
IgnorePlayer(1234567)

IgnoreAlliance

// Adds an alliance to the avoid list
IgnoreAlliance(int64) error
IgnoreAlliance(1234567)

IsPlanetIgnored

// True if planet id is in ignored list
IsPlanetIgnored(int64) bool
if IsPlanetIgnored(1234567) {
    Print("Planet "+1234567+" is in the list")
}

IsPlayerIgnored

// True if player id is in ignored list
IsPlayerIgnored(int64) bool
if IsPlayerIgnored(1234567) {
    Print("Player "+1234567+" is in the list")
}

IsAllianceIgnored

// True if alliance id is in ignored list
IsAllianceIgnored(int64) bool
if IsAllianceIgnored(1234567) {
    Print("Alliance "+1234567+" is in the list")
}

ExecIn

// Schedules an execution after 'execIn' milliseconds. Execution will be asynchronous!
ExecIn(milliseconds int64, clb func()) context.CancelFunc
func callback() {
    Print("5min passed")
}

ExecIn(5 * 60 * 1000, callback) // callback will be called after 5min
// You can also cancel a scheduled job
cancelFn = ExecIn(5 * 60 * 1000, callback)
Sleep(5 * 1000)
cancelFn() // Cancel the job, callback won't be executed
// call function with sleep from a loop
func callback() {
    Print("5min passed")
    Sleep(60*1000)
    Print("6min passed")
}

for {
    ExecIn(Random(30*1000, 60*1000), callback)
    Sleep(10*1000)
}

ExecAt

// Schedules a one time callback execution at specific time. ExecAt is asynchronous.
ExecAt(hourMinSec string, clb func()) context.CancelFunc
time = import("time")
ExecAt("17:23:00", func() {
    Print("callback is executed at ", time.Now())
})
<-OnQuitCh // Blocks forever so that ExecAt can be executed

ExecAtCh

// Schedules a one time callback execution at specific time.
ExecAtCh(hourMinSec string, clb func()) <-chan struct{}
time = import("time")
Print("Before")
<-ExecAtCh("17:23:00", func() {
    Print("callback is executed at ", time.Now())
}) // Script will block here until callback is done executing at 17h23
Print("After")

IntervalExec

// Schedules an execution on regular intervals
IntervalExec(milliseconds int64, clb func()) context.CancelFunc
func callback() {
    Print("5min passed")
}

IntervalExec(5 * 60 * 1000, callback) // callback will be called every 5min
// You can also cancel an interval
cancelFn = IntervalExec(5 * 60 * 1000, callback)
Sleep(5 * 1000)
cancelFn() // Cancel the interval, callback won't be executed

CronExec

// Schedules an execution via crontab expression
CronExec(spec string, clb func()) (EntryID, error)
func callback() {
    Print("Callback executed")
}

CronExec("0 43 15 * * *", callback) // Execute callback at 15h43 every day
CronExec("@16h43", callback)        // Execute callback at 16h43 every day
CronExec("16:43:12", callback)      // Execute callback at 16h43m12s every day
<-OnQuitCh // Blocks forever so that cronexec can be executed

RemoveCron

// Remove a schduled cron job
RemoveCron(EntryID)
func callback() {
    Print("Callback executed")
}
entryID = CronExec("0 43 15 * * *", callback)
Sleep(1000)
RemoveCron(entryID) // Remove scheduled cronjob 

RangeCronExec

// Schedule a callback to be executed in a time range.
// If we currently are in the range, the callback will be scheduled in the remaining time of the range.
// RangeCronExec("00:00:00", "00:15:00", "Do something", func() {  })
// Logs if not in range: Do something at 00:00:00 (+ delay up to 15m)
// Logs if in range:     Do something in 5m10s at 00:05:10
//     (5m10s later)     Do something
RangeCronExec(timeString1, timeString2, msg string, callback func()) (EntryID, error)
func callback() {
    Print("Callback executed between 0h and 0h15")
}

RangeCronExec("00:00:00", "00:15:00", "Do something", callback) // Execute callback between 0h and 0h15 every day
<-OnQuitCh // Blocks forever so that cronexec can be executed

Clock

// Return the current time
Clock() (hour, min, sec int64)
hour, min, sec = Clock()
if hour >= 15 && min >= 43 {
    Print("Do something")
}

Date

// Return the current date
Date() (year, month, day int64)
year, month, day = Date()
Print("Today's date is "+year+"-"+month+"-"+day)

Weekday

// Return the week day (Sunday = 0, Monday = 1... Saturday = 6)
Weekday() int64
Print("Today's week day is "+Weekday())

GetTimestamp

// Returns a Unix time, the number of seconds elapsed since January 1, 1970 UTC.
GetTimestamp() int64
ts = GetTimestamp()
Print(ts)

Unix

// Unix returns the local Time corresponding to the given Unix time, sec seconds and nsec nanoseconds since January 1, 1970 UTC. 
Unix(sec int64, nsec int64) Time
ts = GetTimestamp()
Print(Unix(ts, 0))

OnStateChange

// Register a callback which is executed every time the bot change state
OnStateChange(clb func(locked bool, actor string))
OnStateChange(func(botLocked, actor) {
    Print(botLocked, actor)    
})

<-OnQuitCh // Block forever

GetHomeWorld

GetHomeWorld() Celestial
homeworld = GetHomeWorld()
Print(homeworld.GetName(), homeworld.GetID())

SetHomeWorld

SetHomeWorld(CelestialID)
celestial = GetCachedCelestials()[0]
SetHomeWorld(celestial.GetID())

EnableNJA

EnableNJA()
EnableNJA()

DisableNJA

DisableNJA()
DisableNJA()

IsNJAEnabled

IsNJAEnabled() bool
if IsNJAEnabled() {
    Print("yes")
}

Login

// Login to ogame server
Login() error
Logout()
Sleep(5 * 60 * 1000) // Sleep 5min
Login()

Logout

// Logout the bot from ogame server
Logout()
Logout()
Sleep(5 * 60 * 1000) // Sleep 5min
Login()

IsUnderAttack

// Returns true if the user is under attack, false otherwise
IsUnderAttack() bool
isUnderAttack = IsUnderAttack()
Print(isUnderAttack)

CharacterClass

CharacterClass() CharacterClass
Print(CharacterClass())

IsCollector

IsCollector() bool

IsGeneral

IsGeneral() bool

IsDiscoverer

IsDiscoverer() bool

SendMessage

// Sends a message to playerID
SendMessage(playerID int64, message string) error
SendMessage(1234567, "Sup!")

SendMessageAlliance

// Sends a message to associationID
SendMessageAlliance(associationID int64, message string) error
SendMessageAlliance(537, "Sup!")

GetCelestial

// GetCelestial get the player's planet/moon
GetCelestial(interface{}) (Celestial, error)
coord = NewCoordinate(1, 2, 3, PLANET_TYPE)
celestial, err = GetCelestial(coord)
Print(celestial.GetName())

GetCelestials

// GetCelestial get the player's planets & moons
GetCelestials() ([]Celestial, error)
celestials, err = GetCelestials()
Print("We have " + len(celestials) + " celestials")

GetPlanet

// GetPlanet get the player's planet
GetPlanet(interface{}) (Planet, error)
coord = NewCoordinate(1, 2, 3, PLANET_TYPE)
planet, err = GetPlanet(coord)
Print(planet.GetName())

GetPlanets

// GetPlanets get the player's planets
GetPlanets() []Planet
planets = GetPlanets()
Print("We have " + len(planets) + " planets")

GetMoon

// GetMoon get the player's planets
GetMoon(interface{}) (Moon, error)
coord = NewCoordinate(1, 2, 3, MOON_TYPE)
moon, err = GetMoon(coord)
Print(moon.GetName())

GetMoons

// GetMoon get the player's moons
GetMoons() []Moon
moons = GetMoons()
Print("We have " + len(moons) + " moons")

GetCachedPlanets

// GetCachedPlanets return planets from cached value
GetCachedPlanets() []Planet

GetCachedMoons

// GetCachedMoons return moons from cached value
GetCachedMoons() []Moon

GetCachedCelestial

// GetCachedCelestial return celestial from cached value
GetCachedCelestial(interface{}) Celestial

GetCachedCelestials

// GetCachedCelestials get all cached celestials
GetCachedCelestials() []Celestial

GetCachedPlayer

// GetCachedPlayer returns currently logged in cached player information
GetCachedPlayer() UserInfos

PlayerDataByID

// Get a player information using ogame xml API
PlayerDataByID(playerID int64) (PlayerData, error)

GetSystemsInRange

// GetSystemsInRange returns the systems in a radius around the origin
GetSystemsInRange(originSystem, radius int64) []int64
Print(GetSystemsInRange(3, 0)) // [3]
Print(GetSystemsInRange(3, 1)) // [2, 3, 4]
Print(GetSystemsInRange(3, 2)) // [1, 2, 3, 4, 5]
Print(GetSystemsInRange(3, 3)) // [499, 1, 2, 3, 4, 5, 6]

GetSystemsInRangeDesc

// GetSystemsInRangeDesc returns the systems in a radius around the origin sorted by distance (farther away to closer)
GetSystemsInRangeDesc(originSystem, radius int64) []int64
Print(GetSystemsInRangeDesc(3, 0)) // [3]
Print(GetSystemsInRangeDesc(3, 1)) // [2, 4, 3]
Print(GetSystemsInRangeDesc(3, 2)) // [1, 5, 2, 4, 3]
Print(GetSystemsInRangeDesc(3, 3)) // [499, 6, 1, 5, 2, 4, 3]

GetResources

GetResources(CelestialID) (Resources, error)
celestial = GetCachedCelestial("1:2:3")
resources, err = GetResources(celestial.GetID())

// This also work
resources, err = celestial.GetResources()

GetResourcesDetails

// GetResourcesDetails gets the resources details
GetResourcesDetails(CelestialID) (ResourcesDetails, error)
celestial = GetCachedCelestial("1:2:3")
resourcesDetails, err = GetResourcesDetails(celestial.GetID())

// This also work
resourcesDetails, err = celestial.GetResourcesDetails()

GetAllResources

// GetAllResources gets the resources of all planets and moons
GetAllResources() (map[CelestialID]Resources, error)
resources, _ = GetAllResources()
Print(resources)

Abandon

// Abandon a planet
Abandon(interface{}) error

GetFleets

// Get the player's own fleets activities
GetFleets() ([]Fleet, Slots)
fleet, slots = GetFleets()
for f in fleet {
    Print(f)
}

GetAttacks

// GetAttacks get enemy fleets attacking you
GetAttacks() []AttackEvent
attacks = GetAttacks()
for attack in attacks {
    Print(attack)
}

GalaxyInfos

// GalaxyInfos get information of all planets and moons of a solar system
GalaxyInfos(galaxy, system int64) (SystemInfos, error)
systemInfo, _ = GalaxyInfos(4, 116)

Dotify

// Pretty print a large number using dot as thousand separator
Dotify(in int64) string
Print(Dotify(1000000)) // 1.000.000

ShortDur

// Pretty print a duration
ShortDur(v interface{}) string
Print(ShortDur(121)) // 2m1s
Print(ShortDur(10000)) // 2h46m40s

ShortShipsInfos

// Return a short inline description of the ships. eg: "LightFighter: 10, SmallCargo: 3"
ShortShipsInfos(ships ShipsInfos) string

ID2Str

// Get the string representation of an ogame ID
ID2Str(ID) string
Print(ID2Str(204))       // LightFighter
Print(ID2Str(METALMINE)) // MetalMine

Atoi

// Convert a string to an integer
Atoi(string) int64
Print(1 + Atoi("2")) // 3

Itoa

// Convert a integer to a string
Itoa(int64) string
Print(Itoa(123) + "4") // 1234

StartScript

// Start a script. This call is async, it doesn't wait for the script to terminate.
StartScript(name string) error
StartScript("another.ank")
Print("another.ank started")

StopScript

// Stops a script
StopScript(name string) error
StopScript("another.ank")
Print("another.ank stopped")

IsScriptRunning

// Returns true if 'script' is running, otherwise false
IsScriptRunning(name string) bool
Print(IsScriptRunning("another.ank"))

StartFarmingBot

// Starts farming bot
StartFarmingBot()

StopFarmingBot

// Stops farming bot
StopFarmingBot()

PauseFarmingBot

// Pause farming bot
PauseFarmingBot()

ResumeFarmingBot

// Resume farming bot
ResumeFarmingBot()

IsRunningFarmingBot

// Returns true in case Farming Bot is running, otherwise false
IsRunningFarmingBot() bool

IsPausedFarmingBot

// Returns true in case Farming Bot is paused, otherwise false
IsPausedFarmingBot() bool

IsFarmSessionOngoing

// Returns true if the bot is currently working on a farm session
IsFarmSessionOngoing() bool

FarmingBotSessionsCount

// Returns a count of active farm sessions including the one being processed
FarmingBotSessionsCount() int64

AbortAllFarmingSessions

// Abort all farming sessions
AbortAllFarmingSessions()

StartDefenderBot

// Starts defender bot
StartDefenderBot()

StopDefenderBot

// Stops defender bot
StopDefenderBot()

IsRunningDefenderBot

// Returns true in case Defender Bot is running, otherwise false
IsRunningDefenderBot() bool

SetDefenderCheckInterval

// Set the defender check interval (in minutes)
SetDefenderCheckInterval(min, max int64)

DBGetResourceBuildings

// Get resources buildings from database
DBGetResourceBuildings(CelestialID) (ResourcesBuildings, error)

DBGetResourceSettings

// Get resources settings from database
DBGetResourceSettings(CelestialID) (ResourceSettings, error)

DBGetFacilities

// Get Facilities from database
DBGetFacilities(CelestialID) (Facilities, error)

DBGetShips

// Get Ships from database
DBGetShips(CelestialID) (ShipsInfos, error)

DBGetDefenses

// Get defenses from database
DBGetDefenses(CelestialID) (DefensesInfos, error)

DBGetResearches

// Get Ships from database
DBGetResearches() Researches

Put

// Put data into storage
Put(key string, val interface{}) error
Put("key1", 123)
Put("key2", "Hello world!")
Put("key3", true)
Put("key4", [1, 2, 3])

Get

// Get data from storage
Get(key string) (interface{}, error)
val, err = Get("key1")
Print(val, err)

Has

// Has returns if the key exists in storage
Has(key string) bool

Delete

// Delete a key/value pair from storage
Delete(key string) bool

ParseCoord

// Parse a string into a coordinate
ParseCoord(str string) (coord Coordinate, err error)
Print(ParseCoord("1:2:3"))     // [P:1:2:3]
Print(ParseCoord("P:1:2:3"))   // [P:1:2:3]
Print(ParseCoord("[1:2:3]"))   // [P:1:2:3]
Print(ParseCoord("[P:1:2:3]")) // [P:1:2:3]
Print(ParseCoord("M:1:2:3"))   // [M:1:2:3]
Print(ParseCoord("[M:1:2:3]")) // [M:1:2:3]
Print(ParseCoord("D:1:2:3"))   // [D:1:2:3]
Print(ParseCoord("[D:1:2:3]")) // [D:1:2:3]

NowTimeString

// NowTimeString returns time.Now in a time string format "XX:XX:XX"
NowTimeString() string
Print(NowTimeString()) // 01:15:47

NowInTimeRange

// NowInTimeRange returns either or not the current time is in a time range
NowInTimeRange(timeStr1, timeStr2 string) bool
Print(NowInTimeRange("01:00:00", "02:00:00")) // true

DurationBetweenTimeStrings

// DurationBetweenTimeStrings returns the duration between two time strings
DurationBetweenTimeStrings(timeStr1, timeStr2 string) time.Duration
Print(DurationBetweenTimeStrings("01:00:00", "02:00:00")) // 1h0m0s

MillisecondsBetweenTimeStrings

// MillisecondsBetweenTimeStrings returns the duration in milliseconds between two time strings
MillisecondsBetweenTimeStrings(timeStr1, timeStr2 string) time.Duration
Print(MillisecondsBetweenTimeStrings("01:00:00", "02:00:00")) // 3600000

ParseNextDatetimeAt

// ParseNextDatetimeAt given a string in this format 00:00:00 returns the next Time object at that time.
ParseNextDatetimeAt(hourMinSec string) (time.Time, error)
parsedTime, err = ParseNextDatetimeAt("23:20:31")
Print(parsedTime, err)

GetNextDatetimeAt

// GetNextDatetimeAt given a hour, minute, second, returns the next Time object at that time.
GetNextDatetimeAt(hour, min, sec int64) (time.Time, error)
nextDatetime, err = ParseNextDatetimeAt(23, 20, 31)
Print(nextDatetime, err)

Cargo

Cargo(shipsInfos ShipsInfos) int64
s1 = NewShipsInfos()
s1.Set(LARGECARGO, 10)
Print(Cargo(*s1))

celestial = GetCachedCelestials()[0]
s2, _ = celestial.GetShips()
Print(Cargo(s2))

CalcCargo

// Calculate how many small cargo OR how many large cargo you need to transport a total amount of resources
CalcCargo(resourcesTotal int64) (largeCargoNeeded, smallCargoNeeded int64)
resources = NewResources(10000, 20000, 30000)
lc, sc = CalcCargo(resources.Total())
Print("You need either " + lc + " large cargo OR " + sc + " small cargo")

CalcFastCargo

// Calculate the best combo to transport a total amount of resources according to your available ships.
CalcFastCargo(lcAvail, scAvail, resourcesTotal int64) (largeCargo, smallCargo, cargo int64)
resources = NewResources(10000, 20000, 30000)

smallCargoAvailable = 10
largeCargoAvailable = 10
lc, sc, cargo = CalcFastCargo(largeCargoAvailable, smallCargoAvailable, resources.Total())
Print("You need to send " + lc + " large cargo and " + sc + " small cargo") // You need to send 0 large cargo and 9 small cargo

smallCargoAvailable = 8
largeCargoAvailable = 10
lc, sc, cargo = CalcFastCargo(largeCargoAvailable, smallCargoAvailable, resources.Total())
Print("You need to send " + lc + " large cargo and " + sc + " small cargo") // You need to send 1 large cargo and 4 small cargo

CalcFastCargoPF

// Calculate the best combo to transport a total amount of resources according to your available ships.
CalcFastCargoPF(pfAvail, lcAvail, scAvail, resourcesTotal int64) (pathfinder, largeCargo, smallCargo, cargo int64)

GetPlayerCoordinates

// Gets all the coordinates of a player from the local database
GetPlayerCoordinates(playerID int64) []Coordinate

Base64

// Base64 encode a string 
Base64(string) string

GetSortedCelestials

// GetSortedCelestials gets all celestials sorted by proximity to destination.
// If planets are at different distances to the destination, the order will be moon first, planet second.
// M1, P1, M2, P2, M3, P3 ...
// If planets are at the same distance to the destination, the order will be all the moons first then all planets.
// M1, M2, M3, P1, P2, P3 ...
GetSortedCelestials(destination Coordinate) []Celestial

GetSortedPlanets

// GetSortedPlanets ...
GetSortedPlanets(destination Coordinate) []Planet

GetSortedMoons

// GetSortedMoons ...
GetSortedMoons(destination Coordinate) []Moon

SendMail

// Send an email. Your SMTP settings must be properly configured. 
SendMail(subject, body, to string) error
SendMail("Attack detected", "I'm under attack at x:x:x", "[email protected]")

SendTelegram

// Send a telegram notification
SendTelegram(chatID int64, msg string) error
SendTelegram(TELEGRAM_CHAT_ID, "Attack detected") // use chat id from bot setting
SendTelegram(1234567, "Attack detected")

NewFleet

// Return a fleet builder
NewFleet() *FleetBuilder
f = NewFleet()
f.SetOrigin("1:2:3")
f.SetDestination("1:2:16")
f.SetSpeed(HUNDRED_PERCENT)
f.SetMission(EXPEDITION)
f.AddShips(LIGHTFIGHTER, 2)
f.AddShips(SMALLCARGO, 3)
f.SetDuration(1)
f.SendNow()

f = NewFleet()
f.SetOrigin("M:1:2:3")
f.SetDestination("M:1:2:4")
f.SetSpeed(TEN_PERCENT)
f.SetMission(PARK)
f.SetAllResources()
f.SetAllShips()
fourHours = 4 * 60 * 60
f.SetRecallIn(fourHours)
f.SendNow()

NewFarmSession

// Return a farm session builder
NewFarmSession() *FarmSessionBuilder
origin = GetCachedCelestials()[0]
f = NewFarmSession()
f.SetOrigin(origin)
f.SetRange(4, 1, 497)
f.SetProbes(6)
f.SetAdditionalCargo(11)
f.SetMinimumResourcesToAttack(300000)
f.SetMinimumDefensesToIgnore(0)
f.SetMinimumStorageToIgnore(0, 0, 0)
f.SetMinimumPlayerRank(0)
f.SetEspionageProbeRaids(false)
f.SetUsePathfinders(false)
f.SetFastAttacking(true)
f.SetAttackFromNearestPlanet(false)
f.SetAttackFromNearestMoon(false)
f.SetDeleteCombatReports(true)
f.SetFarmSpeed(HUNDRED_PERCENT)
f.SetPriorityRatio(1, 1, 1)
session, err = f.BuildFarmSession()
Print(session.ID, err)

NewACS

// Return a new ACS builder
NewACS() *ACS
planet = GetCachedPlanets()[0]
group1 = NewShipsInfos()
group1.Set(SMALLCARGO, 1)
group2 = NewShipsInfos()
group2.Set(SMALLCARGO, 2)
a = NewACS(planet.GetID(), NewCoordinate(1, 2, 3, PLANET_TYPE))
a.AddGroup(0, HUNDRED_PERCENT, *group1)
a.AddGroup(10, HUNDRED_PERCENT, *group2)
Print(a.Execute())

planet = GetCachedPlanets()[0]
group1 = NewShipsInfos()
group1.Set(SMALLCARGO, 1)
group2 = NewShipsInfos()
group2.Set(SMALLCARGO, 2)
a = NewACS(planet.GetID(), NewCoordinate(1, 2, 3, PLANET_TYPE))
a.AddGroup(0, HUNDRED_PERCENT, *group1)
a.AddGroup(10, HUNDRED_PERCENT, *group2)
Print(a.ExecuteAsync())

CreateUnion

// CreateUnion creates a union
CreateUnion(Fleet) (int64, error)
f = NewFleet().SetOrigin("M:1:2:3").SetDestination("M:1:2:4").SetMission(PARK).SetAllShips()
fleet, _ = f.SendNow()
unionID, _ = CreateUnion(fleet)
Print("Union ID: " + unionID)

Notify

// Display a desktop notification
Notify(title, message string)
Notify("Player online", "Player 'target' was seen online")

PlaySound

// Play a sound
// soundID is a value between 1 and 7.
// volume must be between 0.0 and 1.0
PlaySound(soundID int64, volume float64) error
PlaySound(1, 1.0)

GetEspionageReportMessages

// Gets the summary of each espionage reports
GetEspionageReportMessages() ([]EspionageReportSummary, error)

GetEspionageReportFor

// Gets the latest espionage report for a given coordinate
GetEspionageReportFor(Coordinate) (EspionageReport, error)

GetEspionageReport

// Gets a detailed espionage report
GetEspionageReport(msgID int64) (EspionageReport, error)

GetCombatReportSummaryFor

// Gets the latest combat report for a given coordinate
GetCombatReportSummaryFor(Coordinate) (CombatReportSummary, error)

DeleteMessage

// Deletes a message from the mail box
DeleteMessage(msgID int64) error

Build

// Builds any ogame objects (building, technology, ship, defence)
Build(celestialID CelestialID, id ID, nbr int64) error
celestial = GetCachedCelestial("1:2:3")
Build(celestial.GetID(), LIGHTFIGHTER, 5)     // Build 5 LightFighter
Build(celestial.GetID(), LIGHTLASER, 5)       // Build 5 LightLaser
Build(celestial.GetID(), METALMINE, 0)        // Build next MetalMine
Build(celestial.GetID(), ENERGYTECHNOLOGY, 0) // Build next EnergyTechnology

// This also work
celestial.Build(LIGHTFIGHTER, 5)     // Build 5 LightFighter
celestial.Build(LIGHTLASER, 5)       // Build 5 LightLaser
celestial.Build(METALMINE, 0)        // Build next MetalMine
celestial.Build(ENERGYTECHNOLOGY, 0) // Build next EnergyTechnology

BuildBuilding

// BuildBuilding ensure what is being built is a building
BuildBuilding(celestialID CelestialID, buildingID ID) error
celestial = GetCachedCelestial("1:2:3")
BuildBuilding(celestial.GetID(), METALMINE) // Build next MetalMine

// This also work
celestial.BuildBuilding(METALMINE) // Build next MetalMine

BuildTechnology

// BuildTechnology ensure that we're trying to build a technology
BuildTechnology(celestialID CelestialID, technologyID ID) error
celestial = GetCachedCelestial("1:2:3")
BuildTechnology(celestial.GetID(), ENERGYTECHNOLOGY) // Build next MetalMine

// This also work
celestial.BuildTechnology(ENERGYTECHNOLOGY) // Build next MetalMine

TearDown

// TearDown tears down any ogame building
TearDown(celestialID CelestialID, buildingID ID) error
celestial = GetCachedCelestial("1:2:3")
TearDown(celestial.GetID(), METALMINE)

// This also work
celestial.TearDown(METALMINE)

CancelBuilding

// CancelBuilding cancel the construction of a building on a specified planet
CancelBuilding(CelestialID) error
celestial = GetCachedCelestial("1:2:3")
CancelBuilding(celestial.GetID())

// This also work
celestial.CancelBuilding()

CancelResearch

// CancelResearch cancel the research
CancelResearch(CelestialID) error
celestial = GetCachedCelestial("1:2:3")
CancelResearch(celestial.GetID())

// This also work
celestial.CancelResearch()

CancelFleet

// CancelFleet cancels a fleet
CancelFleet(FleetID) error
fleets, slots = GetFleets()
CancelFleet(fleets[0].ID)

fleets, slots = GetFleets()
for fleet in fleets {
    CancelFleet(fleet.ID)
}

GetResourcesBuildings

// GetResourcesBuildings gets the resources buildings levels
GetResourcesBuildings(celestialID CelestialID) (ResourcesBuildings, error)
celestial = GetCachedCelestial("1:2:3")
buildings = GetResourcesBuildings(celestial.GetID())

// This also work
buildings = celestial.GetResourcesBuildings()

GetFacilities

// GetFacilities gets all facilities information of a planet
GetFacilities(CelestialID) (Facilities, error)
celestial = GetCachedCelestial("1:2:3")
facilities = GetFacilities(celestial.GetID())

// This also work
facilities = celestial.GetFacilities()

GetResearch

// GetResearch gets the player researches information
GetResearch() Researches
researches = GetResearch()
Print(researches)

GetShips

// GetShips gets all ships units information of a planet
GetShips(CelestialID) (ShipsInfos, error)
celestial = GetCachedCelestial("1:2:3")
ships, _ = GetShips(celestial.GetID())
Print(ships.LightFighter)

// This also work
ships, _ = celestial.GetShips()

GetDefense

// GetDefense gets all the defenses units information of a planet
GetDefense(CelestialID) (DefensesInfos, error)
celestial = GetCachedCelestial("1:2:3")
defenses, _ = GetDefense(celestial.GetID())

// This also work
defenses, _ = celestial.GetDefense()

GetProduction

// GetProduction get what is in the production queue.
// (ships & defense being built)
GetProduction(CelestialID) ([]Quantifiable, int64, error)
celestial = GetCachedCelestial("1:2:3")
productionLine, _, _ = GetProduction(celestial.GetID())

// This also work
productionLine, _, _ = celestial.GetProduction()

ConstructionsBeingBuilt

// ConstructionsBeingBuilt returns the building & research being built, and the time remaining (secs)
ConstructionsBeingBuilt(CelestialID) (buildingID ID, buildingCountdown int64, researchID ID, researchCountdown int64)
celestial = GetCachedCelestial("1:2:3")
buildingID, buildingCountdown, researchID, researchCountdown = ConstructionsBeingBuilt(celestial.GetID())

// This also work
buildingID, buildingCountdown, researchID, researchCountdown = celestial.ConstructionsBeingBuilt()

GetResourceSettings

// GetResourceSettings gets the resources settings for specified planetID
GetResourceSettings(PlanetID) (ResourceSettings, error)

SetResourceSettings

// SetResourceSettings set the resources settings on a planet
SetResourceSettings(PlanetID, ResourceSettings) error
celestial = GetCachedCelestial("1:2:3")
settings = NewResourceSettings(100, 100, 80, 100, 10, 0)
SetResourceSettings(celestial.GetID(), settings)

GetSlots

// GetSlots gets the player current and total slots information
GetSlots() Slots
slots = GetSlots()
Print("Slots in use:", slots.InUse)
Print("Slots total:", slots.Total)
Print("Expedition slots in use:", slots.ExpInUse)
Print("Expedition slots total:", slots.ExpTotal)

Distance

// Distance return distance between two coordinates
Distance(origin, destination Coordinate) int64
celestial = GetCachedCelestial("1:2:3")
coord1 = NewCoordinate(1, 2, 4, PLANET_TYPE)
dist = Distance(celestial.GetCoordinate(), coord1)
Print("Distance:", dist)

FlightTime

// FlightTime calculate flight time and fuel needed
FlightTime(origin, destination Coordinate, speed Speed, ships ShipsInfos) (secs, fuel int64)
celestial = GetCachedCelestial("1:2:3")
ships, _ = celestial.GetShips()
coord1 = NewCoordinate(1, 2, 4, PLANET_TYPE)
secs, fuel = FlightTime(celestial.GetCoordinate(), coord1, HUNDRED_PERCENT, ships)
Print("Time:", ShortDur(secs))
Print("Fuel:", Dotify(fuel))
origin = NewCoordinate(1, 2, 3, PLANET_TYPE)
coord1 = NewCoordinate(1, 2, 4, PLANET_TYPE)
ships = NewShipsInfos()
ships.Set(RECYCLER, 20)
secs, fuel = FlightTime(origin, coord1, HUNDRED_PERCENT, *ships)
Print("Time:", ShortDur(secs))
Print("Fuel:", Dotify(fuel))

SendIPM

// SendIPM sends IPM
SendIPM(PlanetID, Coordinate, int64, ID) (int64, error)
celestial = GetCachedCelestial("1:2:3")
target = NewCoordinate(1, 1, 1, PLANET_TYPE)
SendIPM(celestial.GetID(), target, 10, 0) // Send 10 IPM to target, (0 is random primary defense target)
SendIPM(celestial.GetID(), target, 10, LIGHTLASER) // Send 10 IPM to target, targetting light laser

BuyOfferOfTheDay

// BuyOfferOfTheDay buys the offer of the day.
BuyOfferOfTheDay() error
Print(BuyOfferOfTheDay())

GetAuction

// GetAuction gets current auction information
GetAuction() (Auction, error)

DoAuction

// DoAuction make a bid on current auction
DoAuction(bid map[CelestialID]Resources) error
celestial = GetCachedCelestials()[0]
bid = {
    celestial.GetID(): NewResources(2000, 0, 0)
}
Print(DoAuction(bid))

Phalanx

// Phalanx scan a coordinate from a moon to get fleets information
Phalanx(MoonID, Coordinate) ([]Fleet, error)

UnsafePhalanx

// UnsafePhalanx same as Phalanx but does not perform any input validation.
// Warning: scanning an invalid coordinate (out of phalanx range) might get your account banned automatically. (10min ban for first time)
UnsafePhalanx(MoonID, Coordinate) ([]Fleet, error)

JumpGate

// JumpGate sends ships through a jump gate.
JumpGate(origin, dest MoonID, ships ShipsInfos) error
moon1 = GetCachedCelestial("M:1:2:3")
moon2 = GetCachedCelestial("M:1:2:4")
ships = NewShipsInfos()
ships.Set(RECYCLER, 20)
err = JumpGate(moon1.GetID(), moon2.GetID(), *ships)
Print(err)

JumpGate2

// JumpGate2 sends ships through a jump gate.
JumpGate2(origin, dest MoonID, ships ShipsInfos) (success bool, rechargeTime int64, err error)

GetFleetSlotsReserved

// Returns current fleet slots reserved for player setting
GetFleetSlotsReserved() int64
reserved = GetFleetSlotsReserved()
Print(reserved)

SetFleetSlotsReserved

// Set fleet slots reserved for player setting
SetFleetSlotsReserved(reserved int64)

NewResources

// Represent ogame resources
NewResources(metal, crystal, deuterium int64) Resources

NewResourceSettings

// Represent an ogame ResourceSettings
NewResourceSettings(metalMine, crystalMine, deuteriumSynthesizer, solarPlant, fusionReactor, solarSatellite int64) ResourceSettings

NewCoordinate

// Represent an ogame coordinate
NewCoordinate(galaxy, system, position int64, celestialType CelestialType) Coordinate
myCoordinate = NewCoordinate(1, 2, 3, PLANET_TYPE)
Print(myCoordinate)

NewTemperature

// Represent an ogame temperature
NewTemperature(min, max int64) Temperature

NewShipsInfos

// Represent an ogame ShipsInfos
NewShipsInfos() *ShipsInfos

JsonDecode

JsonDecode(data []byte) (out interface{}, err error)
out, err = JsonDecode(`{"a": 1, b": 2.1, "c": "a string", "d": true}`)
Print(out, err)

Min

// Min returns the smaller of x or y.
Min(x, y float64) float64

Max

// Max returns the larger of x or y.
Max(x, y float64) float64

Ceil

// Ceil returns the least integer value greater than or equal to x.
Ceil(x float64) float64

Floor

// Floor returns the greatest integer value less than or equal to x.
Floor(x float64) float64

Round

// Round returns the nearest integer, rounding half away from zero.
Round(x float64) float64

Abs

// Abs returns the absolute value of x.
Abs(x float64) float64

Pow

// Pow returns x**y, the base-x exponential of y.
Pow(x, y float64) float64

Sqrt

// Sqrt returns the square root of x.
Sqrt(x float64) float64