Git Product home page Git Product logo

pyogame's Introduction

pyogame

logo

OGame is a browser-based, money-management and space-war themed massively multiplayer online browser game with over two million accounts.

This lib is supposed to help write scripts and bots for your needs. it supports ogame_version: 8.4.0 version 22

install

pip install ogame

update

pip install ogame==8.4.0.22

dont want to wait for new updates download direct from the develop branch

pip install git+https://github.com/alaingilbert/pyogame.git@develop

get started

Code Snippets

Code Style

Discord

Join Discord

You wanna try a finished bot

pyogame.net~~

functions

login

from ogame import OGame
from ogame.constants import destination, coordinates, ships, mission, speed, buildings, status
 
empire = OGame(UNI, USER, PASSWORD)

#optional
empire = OGame(UNI, USER, PASSWORD, user_agent='NCSA_Mosaic/2.0 (Windows 3.1)', 
                                    proxy='https://proxy.com:port', 
                                    language='us'
)

test

This is a command that will try to run all functions with parameters. 
empire.test()                       returns bool

If this lib is running for long time it is recommended to test it during run time. 
If it fails you can set up a telegram message. A test creates alot of traffic

if not empire.test():
    raise RuntimeWarning("Pyogame test failed, there are functions that dont work anymore. Be Careful")
    # warn the User

get attacked

empire.attacked()                   returns bool 

get neutral

empire.neutral()                    returns bool 

get friendly

empire.friendly()                   returns bool 

get server (universe)

server = empire.server()
server.version                      returns str
server.Speed.universe               returns int
server.Speed.fleet                  returns int
server.Donut.galaxy                 returns bool
server.Donut.system                 returns bool

get characterclass

Get the class of your Ogame Account['miner', 'explorer', 'warrior', 'none]
empire.character_class()            return string

get rank

empire.rank()                       return int

get planet id's

empire.planet_ids()                 returns list 

empire.id_by_planet_name('name')    returns int

empire.name_by_planet_id(id)        return string

empire.planet_names()               returns list

get moon id's

empire.moon_ids()                   returns list

empire.moon_names()                 returns list

**keep in mind to prefer planets id's moon id dont works on every function**

abandon planet

empire.abandon_planet(id)           returns bool

** keep in mind that this is truly final, that no more fleets are needed at the 
departure or destination of this planet and that there is no construction or research underway on it.

rename planet

empire.rename_planet(id,'new_name') returns bool

** keep in mind that the name must contain at least two characters **

coordinates

coordinates have the format [galaxy, system, position, destination]

destination is referred to planet moon or debris on that coordinate planet=1 debris=2 moon=3
for example [1,200,16,3] = galaxy=1, system=200, position=16, destination=3 for moon
with from ogame.constants import destination the process is much more readable.

when you dont give it an destination it will default to planet

                                        returns list
from ogame.constants import coordinates, destination
pos = coordinates(
    galaxy=1,
    system=2,
    position=12,
    dest=destination.debris
)

coordinates(1, 2, 12, destination.moon)
coordinates(1, 2, 12, destination.debris)
coordinates(1, 2, 12, destination.planet) or coordinates(1, 2, 12)

get slot celestials

returns how many planet slots are free to colonize

slot = empire.slot_celestial()          returns class
slot.free                               returns int
slot.total                              returns int

get celestial

works with planet's and moon's

celestial = empire.celestial(id)        returns class
celestial.temperature                   returns list
celestial.diameter                      returns int
celestial.coordinates                   returns list
celestial.used                          return int
celestial.total                         return int
celestial.free                          return int

get celestial coordinates

works with planet's and moon's

empire.celestial_coordinates(id)        returns list

get celestial queue

get research, building and shipyard construction time works with planet's and moon's

empire.celestial_queue(id)              returns list

queue = empire.celestial_queue(id)
queue.list                              returns list
queue.research                          returns datetime
queue.buildings                         returns datetime
queue.shipyard                          returns datetime

resources

resources have the format [metal, crystal, deuterium]
darkmatter & energy are irrelevant, because you cant transport these.
It is used for transport and market functions

from ogame.constants import resources
res = resources(metal=1, crystal=2, deuterium=3)
[1, 2, 3]

get resources

empire.resources(id)                    returns class(object)

res = empire.resources(id)
res.resources                           returns resources
res.day_production                      returns resources
res.storage                             returns resources
res.darkmatter                          returns int
res.energy                              returns int
res.metal                               returns int
res.crystal                             returns int
res.deuterium                           returns int

get/set resources settings

empire.resources_settings(id)                       returns class(object)
empire.resources_settings(id, settings)             returns class(object)

settings = empire.resources_settings(id, settings)
settings.list                                       returns list
settings.metal_mine                                 returns int
settings.crystal_mine                               returns int
settings.deuterium_mine                             returns int
settings.solar_plant                                returns int
settings.fusion_plant                               returns int
settings.solar_satellite                            returns int
settings.crawler                                    returns int
settings = empire.resources_settings(id)

print(
       settings.list,
       settings.metal_mine,
       settings.crystal_mine,
       settings.deuterium_mine,
       settings.solar_plant,
       settings.fusion_plant,
       settings.solar_satellite,
       settings.crawler
     )

settings = empire.resources_settings(id,
        settings={
            buildings.metal_mine: speed.max,
            buildings.crystal_mine: speed.min,
            buildings.fusion_plant: 0,
            buildings.solar_satellite: speed._50,
        }
    )

print(settings.list)

get prices

get prices of buildings or ships. Level is mandatory if you pass buildings that exist only once like mines.
from ogame.constants import price

price(technology, level)                return resources

price(buildings.metal_mine, level=14))
price(ships.deathstar(100))

get supply

empire.supply(id)                       returns class(object)

sup = empire.supply(id)

sup.metal_mine.level                    returns int
sup.metal_mine.is_possible              returns bool (possible to build)
sup.metal_mine.in_construction          returns bool

sup.crystal_mine
sup.deuterium_mine
sup.solar_plant
sup.fusion_plant 
sup.metal_storage
sup.crystal_storage
sup.deuterium_storage                   returns class(object)

get facilities

empire.facilities(id)                   returns class(object) 

fac = empire.facilities(id)

fac.robotics_factory.level              returns int
fac.robotics_factory.is_possible        returns bool (possible to build)
fac.robotics_factory.in_construction    returns bool

fac.shipyard
fac.research_laboratory
fac.alliance_depot
fac.missile_silo
fac.nanite_factory
fac.terraformer
fac.repair_dock

get moon facilities

empire.moon_facilities(id)              returns class(object) 

fac = empire.moon_facilities(id) 
fac.robotics_factory.level              returns int
fac.robotics_factory.is_possible        returns bool (possible to build)
fac.robotics_factory.in_construction    returns bool

fac.shipyard
fac.moon_base
fac.sensor_phalanx 
fac.jump_gate

get traider

empire.traider(id)                  returns Exception("function not implemented yet PLS contribute")

get research

empire.research(id)                   returns class(object) 

res = empire.research(id)

res.energy.level
res.energy.is_possible
res.energy.in_construction

res.laser
res.ion
res.hyperspace
res.plasma
res.combustion_drive
res.impulse_drive
res.hyperspace_drive
res.espionage
res.computer
res.astrophysics
res.research_network
res.graviton
res.weapons
res.shielding
res.armor

get ships

empire.ships(id)                    returns class(object) 

shi = empire.ships(id)

shi.light_fighter.amount
shi.light_fighter.is_possible
shi.light_fighter.in_construction

shi.heavy_fighter
shi.cruiser
shi.battleship
shi.interceptor
shi.bomber
shi.destroyer
shi.deathstar
shi.reaper
shi.explorer
shi.small_transporter
shi.large_transporter
shi.colonyShip
shi.recycler
shi.espionage_probe
shi.solarSatellite
shi.crawler

get defences

empire.defences(id)                 returns class(object) 

def = empire.defences(id)

def.rocket_launcher.amount
def.rocket_launcher.is_possible
def.rocket_launcher.in_construction

def.laser_cannon_light
def.laser_cannon_heavy
def.gauss_cannon
def.ion_cannon
def.plasma_cannon
def.shield_dome_small
def.shield_dome_large
def.missile_interceptor
def.missile_interplanetary

get galaxy

empire.galaxy(coordinates)          returns list of class(object)
for planet in empire.galaxy(coordinates(randint(1,6), randint(1,499))):
    print(planet.list)
    print(planet.name, planet.position, planet.player, planet.player_id, planet.rank, planet.status, planet.moon)
    if status.inactive in planet.status and status.vacation not in planet.status:
        #Farm Inactive

get debris in galaxy

empire.galaxy_debris(coordinates)               returns list of class(object)

or use planet coordinates to get only the target debris

empire.galaxy_debris(planet_coordinates)        returns class(object)

pos = empire.galaxy_debris(planet_coordinates)
pos.list                                        returns list
pos.position                                    returns list
pos.has_debris                                  returns bool
pos.resources                                   returns list
pos.metal                                       returns int
pos.crystal                                     returns int
pos.deuterium                                   returns int
for position in empire.galaxy_debris(coordinates(1, 20)):
    print(position.list)
    print(position.position, position.has_debris, position.resources, position.metal, position.crystal, position.deuterium)
    if position.has_debris:
        # Can send recyclers

position = empire.galaxy_debris(coordinates(1, 20, 12))
print(position.list)
print(position.position, position.has_debris, position.resources, position.metal, position.crystal, position.deuterium)
if position.has_debris:
    # Can send recyclers

get ally

Returns your current Ally name None if you didnt join one yet

empire.ally()                       returns list

get officers

officers = empire.officers()
officers.commander                  returns bool
officers.admiral                    returns bool
officers.engineer                   returns bool
officers.geologist                  returns bool
officers.technocrat                 returns bool

get shop

empire.shop()                       returns Exception("function not implemented yet PLS contribute")

get slot

Get the actual free and total Fleet slots you have available
slot = empire.slot_fleet()
slot.fleet.total                     returns int
slot.fleet.free                      returns int
slot.expedition.total                returns int
slot.expedition.free                 returns int

get fleet

empire.fleet()                      returns list of class(object)
for fleet in empire.fleet():
    if fleet.mission == mission.expedition:
        print(fleet.list)
        print(  
                fleet.id, 
                fleet.mission, 
                fleet.diplomacy, 
                fleet.player, 
                fleet.player_id,
                fleet.returns, 
                fleet.arrival, 
                fleet.origin, 
                fleet.destination
            )

get hostile fleet

empire.hostile_fleet()              returns list of class(object)
for fleet in empire.hostile_fleet():
    print(fleet.list)

get friendly fleet

empire.hostile_fleet()              returns list of class(object)
for fleet in empire.friendly_fleet():
    print(fleet.list)

get phalanx

~~Dangereous!!! it gets you banned when not valid
empire.phalanx(coordinates, id)     returns list of class(object)~~

for fleet in empire.phalanx(moon_id, coordinates(2, 410, 7)):
    if fleet.mission == mission.expedition:
        print(fleet.list)
        print(fleet.id, fleet.mission, fleet.returns, fleet.arrival, fleet.origin, fleet.destination)

get spyreports

empire.spyreports()                           returns list of class(object)
empire.spyreports(firstpage=1, lastpage=30)   returns list of class(object)

reports = empire.spyreports()
report = reports[0]
report.name                                   returns str
report.position                               returns list
report.moon                                   returns bool
report.datetime                               returns str
report.metal                                  returns int
report.crystal                                returns int
report.deuterium                              returns int
report.fleet                                  returns dict
report.defenses                               returns dict
report.buildings                              returns dict
report.research                               returns dict
report.api                                    returns str
report.list                                   returns list
for report in empire.spyreports():
    print(report.list)

send fleet (for both version 7.6 and 8.0.0)

from ogame.constants import coordinates, mission, speed, fleet
empire.send_fleet(mission=mission.expedition,
                  id=id,
                  where=coordinates(1, 12, 16),
                  ships=fleet(light_fighter=12, bomber=1, cruiser=100),
                  resources=[0, 0, 0],  # optional default no resources
                  speed=speed.max,      # optional default speed.max
                  holdingtime=2)        # optional default 0 will be needed by expeditions
                 
                                        returns bool

return fleet

empire.return_fleet(fleet_id):          returns bool

You can't return hostile Fleets :p use the friendly fleet function to avoid confusion.
True if the Fleet you want to return is possible to retreat

send message

empire.send_message(player_id, msg)     returns bool

build

Buildings

from ogame.constants import buildings
empire.build(what=buildings.alliance_depot, 
             id=id)

buildings.metal_mine
buildings.crystal_mine
buildings.deuterium_mine
buildings.solar_plant
buildings.fusion_plant
buildings.solar_satellite(int)
buildings.crawler(int)
buildings.metal_storage
buildings.crystal_storage
buildings.deuterium_storage

buildings.robotics_factory
buildings.shipyard
buildings.research_laboratory
buildings.alliance_depot
buildings.missile_silo
buildings.nanite_factory
buildings.terraformer
buildings.repair_dock

empire.build(what=buildings.rocket_launcher(10), 
             id=id)

buildings.rocket_launcher(int)
buildings.laser_cannon_light(int)
buildings.laser_cannon_heavy(int)
buildings.gauss_cannon(int)
buildings.ion_cannon(int)
buildings.plasma_cannon(int)
buildings.shield_dome_small(int)
buildings.shield_dome_large(int)
buildings.missile_interceptor(int)
buildings.missile_interplanetary(int)

buildings.moon_base
buildings.sensor_phalanx
buildings.jump_gate

Ships

from ogame.constants import ships
empire.build(what=ships.bomber(10), 
             id=id)

ships.light_fighter(int)
ships.heavy_fighter(int)
ships.cruiser(int)
ships.battleship(int)
ships.interceptor(int)
ships.bomber(int)
ships.destroyer(int)
ships.deathstar(int)
ships.reaper(int)
ships.explorer(int)
ships.small_transporter(int)
ships.large_transporter(int)
ships.colonyShip(int)
ships.recycler(int)
ships.espionage_probe(int)
                 
                                        returns None

do research

from ogame.constants import research
empire.build(what=research.energy,
             id=id)

research.energy
research.laser
research.ion
research.hyperspace
research.plasma
research.combustion_drive
research.impulse_drive
research.hyperspace_drive
research.espionage
research.computer
research.astrophysics
research.research_network
research.graviton
research.weapons
research.shielding
research.armor
                 
                                        returns None

deconstruct

from ogame.constants import buildings
empire.deconstruct(what=buildings.metal_mine,
                   id=id)

buildings.metal_mine
buildings.crystal_mine
buildings.deuterium_mine
buildings.solar_plant
buildings.fusion_plant
buildings.metal_storage
buildings.crystal_storage
buildings.deuterium_storage

buildings.robotics_factory
buildings.shipyard
buildings.research_laboratory
buildings.missile_silo
buildings.nanite_factory

buildings.sensor_phalanx
buildings.jump_gate
 

                                        returns None

cancel building and research progress

Buildings

If you need to cancel the construction or deconstruction of a building
empire.cancel_building(id)              returns None

Research

If you need to cancel the current ongoing research
empire.cancel_research(id)              returns None

collect rubble field

 
this will collect your rubble field at the planet id.
                
empire.collect_rubble_field(id)         returns None

im i still loged In?

                 
empire.is_logged_in()                   returns Bool

relogin

                 
empire.relogin()                        returns Bool

switch universes with the same login
empire.relogin('UNI')

keep going

If you are running code for long time you can decorate it with the keep going Decorator. If the function gets logged out it will try to relogin and continuing execution.

@empire.keep_going
def run():
    while True:
        print(empire.attacked())
        time.sleep(1)

logout

                 
empire.logout()                         returns Bool

pyogame's People

Contributors

alaingilbert avatar brodo97 avatar dlacoding avatar dustinscharf avatar flashover avatar jc01rho avatar khanmaytok avatar lantoine avatar maximophone avatar mjurczik avatar oalieno avatar onizakuma avatar piecepapercode avatar prior-l avatar ss1h2a3tw avatar starbuckneo avatar systemac avatar the1ndnly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyogame's Issues

galaxy_infos

galaxy_infos permet de naviguer dans les galaxy/ss.

Cette navigation consomme du deuterium.
Est il possible de spรฉcifier depuis quelle planรจte nous souhaitons rรฉcupรฉrer les infos de la galaxy ?

Grab fleet hostile info

Hello,
I am not able to grab hostile fleet info from eventList, as you do for friendly, do you know why ?

Building of Facilities not working.

It sends the command to the server, planet_id and the correct id for the RF (14), but it doesn't build it.
It works with Buildings and Ships, but not for Facilities?

ogame.build(planet_id, Buildings['RoboticsFactory'])

Seems Facilities is ignore, but should be grouped together with Buildings when building.

New function : send galaxy info to 'galaxytool' server ( galaxytool-toolbar feature )

do you know galaxytool and galaxytoolbar?
when you're viewing galaxy/systems, toolbar sends galaxyinfo as xml to galaxytool server
colud you make this function?

xml sending to designated galaxytool server

http://GalaxyToolSever/galaxytool/secret/galaxyplugin.php
with secret logon key


<?xml version="1.0" encoding="UTF-8"?>
<galaxyviews xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="galaxyview.xsd">
	<header version="2.8.4" universe="Virgo" debug="true" language="english" token="225a92e168a27fa41231bfb97c8e7583" content_type="galaxyview"/>
	<galaxyview galaxy="1" system="33">
		<position pos="1"/>
		<position pos="2"/>
		<position pos="3"/>
		<position pos="4">
			<planetname>Eden Prime</planetname>
			<player playername="Harbinger" rank="202" playerid="100180"/>
			<alliance allyname="ENL" allyid="500001" rank="3" member="51"/>
			<activity year="2017" month="11" day="7" hour="9" minute="29" weekday="2"/>
		</position>
		<position pos="5"/>
		<position pos="6">
			<planetname>Homeworld</planetname>
			<player playername="merry" rank="635" playerid="100181"/>
			<activity year="2017" month="11" day="7" hour="9" minute="29" weekday="2"/>
		</position>
		<position pos="7"/>
		<position pos="8">
			<planetname>Leuk een planeet</planetname>
			<player playername="Bassie" rank="81" playerid="100060"/>
			<alliance allyname="ENL" allyid="500001" rank="3" member="51"/>
			<activity year="2017" month="11" day="7" hour="9" minute="29" weekday="2"/>
		</position>
		<position pos="9"/>
		<position pos="10">
			<planetname>DUBLIN</planetname>
			<player playername="Czar Aerglo" rank="151" playerid="100182"/>
			<alliance allyname="DOOM" allyid="500018" rank="5" member="10"/>
			<activity year="2017" month="11" day="7" hour="9" minute="29" weekday="2"/>
		</position>
		<position pos="11"/>
		<position pos="12">
			<planetname>i like pizza</planetname>
			<player playername="Viceregent Sattelite" rank="44" playerid="100081"/>
			<alliance allyname="TFT" allyid="500006" rank="20" member="4"/>
		</position>
		<position pos="13"/>
		<position pos="14"/>
		<position pos="15"/>
	</galaxyview>
</galaxyviews>

Issue scanning galaxy when outlaw user.

When you try to execute a galaxy scan with:

empire.galaxy(coordinates(3, 208))

but on that system there's any Outlaw user (purple highlight) I'm always getting the same error:

File "/Users/scripts/python/python-scripts/ogame/ogames.py", line 917, in galaxy collect_player()[0],
File "/Users/scripts/python/python-scripts/ogame/ogames.py", line 868, in collect_player name = html.find_all('class', 'status_abbr_', 'value')
File "/Users/scripts/python/python-scripts/ogame/ogames.py", line 140, in find_all append_attributes()
File "/Users/scripts/python/python-scripts/ogame/ogames.py", line 132, in append_attributes val = line[result].replace(' ', '')
AttributeError: 'NoneType' object has no attribute 'replace'
I've being doing some test playing around with the init.py with no luck...
Any clue why this might be happening?

Thanks!

Python 2.7 ou 3+

Bonjour, est-ce que le script fonctionne avec la derniรจre version de python 3 ou faut-il utiliser python 2.7 ?

freelancer

NEW UPCOMING UPDATE

i know is really soon to ask and it's not yet a issue, but i have tested this wrapper on beta test server on pioners lobby, by changing all lines in file init.py containing lobby.ogame to lobby-pioneers.ogame, the first error i got is on login, giving an error on get universe speed, i just manually set the value and than im able to login, at this point i got moon_ids and planets_ids, but everything else return errors, im not good on python, but im tryng to solve what i can by my self, without sucess so far :(
I think its time for everyone to help start fixing this future issue,
Thanks for any info and really really sorry for my terrible english im hoping you guys can understend

Admins catch on to the fast login.

During regular checks Admins check for super fast logins, as loading the main page and filling in login info and then logging in. The script does this as fast as it can, which raises flags.

Suggested temp fix:
Before line 122 add something like "time.sleep(x)"
But would be best to randomize this a bit, so it will look more human, so add a random generator between x and y.
Maybe add some extra delay after login to seem more human.

UI tkinter or embedded C# win form

Hello, I'll ask my questions in English for more understanding for other people.

I'm wondering if someone knows a tool to create in a more easier way than tkinter (directly in python) Windows interface.

For example if we could create our windows interface through C# with visual studio and use it with our main project in python?

Or in another way of it exist any translating tool to transfer the C# to python and use tkinter.
I found bunifu but it cost a lot.

P. S
It could be also C++ or visual studio for example but I'd rather to use C#

Thank you :-)

Freelancer

Other languages

Hey there !

Now that my previous issue is resolved (:D), would it be possible to make the project multi language ?
It currently just works on the en.* universes, it would be nice to have the possibility, without tweaking your code, to use it on different ogame countries. I can help for the french universes, for example, if you need help about this.

Build not woking

when I try to build something I get the following error :

Traceback (most recent call last):
  File "/home/lantoine/python-workspace/script_ogame.py", line 6, in <module>
    ogame.build(PLANET_ID, Buildings['MetalMine'])
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 55, in wrapper
    res = fn(self, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 466, in build
    self._build(planet_id, elem_id)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 55, in wrapper
    res = fn(self, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 449, in _build
    self.build_building(planet_id, object_id)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 55, in wrapper
    res = fn(self, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "/usr/lib/python3.5/site-packages/ogame/__init__.py", line 427, in build_building
    token = form.find('input', {'name': 'token'}).get('value')
AttributeError: 'NoneType' object has no attribute 'find'

I used this command :

PLANET_ID = ogame.get_planet_ids()
ogame.build(PLANET_ID, Buildings['MetalMine'])

Supply metal storage level not working.

Hi,

When I try checking the metal storage level of a planet, I don't get the real level of the building but 0

for id in empire.planet_ids():
  print(empire.supply(id).metal_storage.level) # always prints 0

Question

Hi!
I'm on the european server, i just wanted to know if i am supposed to change something in init.py to login succesfully.
Ogame now is at 7.6.0-pl1, do i have to change this too?

Thank you, i really appreciated your work :)

Planet name not complete

get_planet_by_name() doesn't return the full name, just the displayed name.
If the name is "to long" ingame it gets shorterend with "..." at some point as a simple display 'fix'. But full name is still in the content, just not used. The following ahref does contain the full name in "title", but also a lot of other info that will need to be "regex'ed out".
Happened with a planet-name with 15 chars, in which the last 3 chars get replaced with "..." so not shorter in chars, but just display-size.

send_fleet to debris fields

Sorry to bother you again.
I'm trying to automate recycling but it won't work.

from ogame.constants import Ships, Speed, Missions, Buildings, Research, Defense
ogame = OGame(uni, username, password) 

ships = [(Ships['Recycler'], 1)]
speed = Speed['100%']
where = {'galaxy': 1, 'system': 1, 'position': 1}
mission = Missions['RecycleDebrisField']
resources = {'metal': 0, 'crystal': 0, 'deuterium': 0}
ogame.send_fleet(PLANET_ID, ships, speed, where, mission, resources)

Unfortunately the code above won't send a fleet. Though there are no error messages either.
I have tried finding the issue and I guess it's the mission number, because sending a recycler on deploy or transport mission to another planet works just fine.

I also tried sending it to coordinates with existing debris fields and without, nothing happens unfortunately.
I noticed when you are in game you need to actively select the debris field AND the mission type when sending a fleet, so maybe that's where the problem is.

Supply, level disorder

if solar satellites or crawlers are in queue, another level is added after the inital 'data-value',
which results in wrong levels for metal_storage, crystal_storage (basically everything after solar_satellites or crawlers)
as a quick fix I have added the re.search to the list comprehension

def supply(self, id):
        response = self.session.get(
            url=self.index_php + 'page=ingame&component=supplies&cp={}'
                    .format(id)
        ).text
        bs4 = BeautifulSoup4(response)
        levels = [
            int(level['data-value'])
            for level in bs4.find_all('span', {'data-value': True})
            if not re.search(r'stockAmount', str(level))          <---- or if not level.find(class_=r"stockAmount")
        ]

Suggestion: Function to get all fleets

Sometimes you need all fleets currently in your overview, made a simple addition. Might be handy to give it an optional parameter so you can get only mission_type = 1, or maybe a list [1, 2, 4] even?
So you can choose yourself if you want all (no extra parameter) or only specific types.

def get_fleets(self):
        headers = {'X-Requested-With': 'XMLHttpRequest'}
        res = self.session.get(self.get_url('eventList'), params={'ajax': 1},
                               headers=headers).content
        soup = BeautifulSoup(res, 'lxml')
        if soup.find('head'):
            raise NOT_LOGGED
        events = soup.findAll('tr', {'class': 'eventFleet'})
        events = filter(lambda x: 'partnerInfo' not in x.get('class', []), events)

        missions = []
        for event in events:
            mission_type = int(event['data-mission-type'])
            mission = {}
            mission.update({'mission_type': mission_type})

            return_flight = event['data-return-flight']
            mission.update({'return_flight': return_flight})

            id = str(event['id'])
            #id = self.get_event_id(str(event['id']))
            mission.update({'id': id})

            coords_origin = event.find('td', {'class': 'coordsOrigin'}) \
                .text.strip()
            coords = re.search(r'\[(\d+):(\d+):(\d+)\]', coords_origin)
            galaxy, system, position = coords.groups()
            mission.update({'origin': (int(galaxy), int(system), int(position))})


            dest_coords = event.find('td', {'class': 'destCoords'}).text.strip()
            coords = re.search(r'\[(\d+):(\d+):(\d+)\]', dest_coords)
            galaxy, system, position = coords.groups()
            mission.update({'destination': (int(galaxy), int(system), int(position))})

            arrival_time = event.find('td', {'class': 'arrivalTime'}).text.strip()
            coords = re.search(r'(\d+):(\d+):(\d+)', arrival_time)

            hour, minute, second = coords.groups()
            hour = int(hour)
            minute = int(minute)
            second = int(second)
            arrival_time = self.get_datetime_from_time(hour, minute, second)
            mission.update({'arrival_time': arrival_time})

            if mission_type == 1:
                attacker_id = event.find('a', {'class': 'sendMail'})['data-playerid']
                mission.update({'attacker_id': int(attacker_id)})
            else:
                mission.update({'attacker_id': None})

            missions.append(mission)
        return missions

hostile_fleet(): Get destination type or name

Currently we only get the destination coordinates of the attacked/spied target.
Is it possible to extract the destination "type" (as in constants: planet, debris, moon) or the name of the destination?
With those information one can easily get the id of planet/moon and save ships and resources just in time.

For friendly fleet i've found:
<td class="destFleet"><figure class="planetIcon planet [..]" title="Planet"></figure>PLANET-NAME</td>
and
<td class="destFleet"><figure class="planetIcon moon [..]" title="Mond"></figure>MOON-NAME</td>

Maybe someone with more frequent access to hostile fleet data can help us out.

fleet() function

Hello,

The fleet() function is returning only one event, is this normal? how could i modify it in order to catch hostile event?

I already catch them if there is no other fleet movement, but not if there are several.

After changing password I've got always "Bad login".

image
Hello I've changed my password. I can login on website normal, but not via bot. I'm using the same updated password for bot and website . My password has only numbers and letters. I'm 100% sure that lgoin data is valid.

send_fleet issue

send_fleet function returns me 'False"

Do you know what's wrong ?

galaxy_infos error when 'vacation' player is in

Hello!

I wanted to try this function but I found a problem:

File "/usr/local/lib/python3.7/site-packages/ogame/__init__.py", line 56, in wrapper res = method(self, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/ogame/__init__.py", line 39, in wrapper  return some_fn(ogame, *args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/ogame/__init__.py", line 930, in galaxy_infos player_id = int(re.search(r'player(\d+)', player_id_raw).groups()[0])
AttributeError: 'NoneType' object has no attribute 'groups'

I'm trying to get the solution.

Best regards.

user-agent: string or dictionary?

Hello,
the wiki states that the user-agent parameter should be passed as a string on OGame object initialization, but at the moment a dictionary is required.
Lines 32-38 in __init__.py:

        if self.user_agent is None:
            self.user_agent = {
                'User-Agent':
                    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
                    '(KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
            }
        self.session.headers.update(self.user_agent)

As a string makes more sense, shouldn't the code above be:

        if self.user_agent is None:
            self.user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 ' + \
                    '(KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
            }
        self.session.headers.update({'User-Agent': self.user_agent})

?

Starting a research results in an error

Trying to start HyperspaceTechnology-7 (or any) results in a TypeError which crashes the script:

Traceback (most recent call last):
  File "C:\Python27\lib\threading.py", line 801, in __bootstrap_inner
    self.run()
  File "C:\Python27\lib\threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "C:\Users\xxx\PycharmProjects\ogame\pygame.py", line 480, in thread_build
    self.build(planet_name)
  File "C:\Users\xxx\PycharmProjects\ogame\pygame.py", line 341, in build
    self.ogame.build(self.planets[planet_name], building)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 55, in wrapper
    res = method(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 436, in build
    self._build(planet_id, elem_id, cancel=cancel)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 55, in wrapper
    res = method(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 421, in _build
    self.build_technology(planet_id, object_id, cancel=cancel)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 55, in wrapper
    res = method(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 414, in build_technology
    if not self.is_logged(res):
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 55, in wrapper
    res = method(self, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 38, in wrapper
    return some_fn(ogame, *args, **kwargs)
  File "C:\Python27\lib\site-packages\ogame\__init__.py", line 139, in is_logged
    soup = BeautifulSoup(html, 'lxml')
  File "C:\Python27\lib\site-packages\bs4\__init__.py", line 192, in __init__
    elif len(markup) <= 256 and (
TypeError: object of type 'Response' has no len()

Not sending ships anymore

Did they change something to the sending of fleets? My bot is no longer sending ships anymore.

Example of what i send (planet_id and galaxy stuff filtered out)
<planet_id>, [(203, 1)], 10, {'position': 1, 'system': 1, 'galaxy': 1}, 1, {'crystal': 0, 'metal': 0, 'deuterium': 0}

Building still works.

connection problem

impossible to execute the connector:
ogame = OGame('Uriel', USER, PASW)
always the same error -> BAD CREDENTIALS

ImportError: cannot import name 'Ogame'

I always get an error.
here is my code
from ogame import Ogame
empire = Ogame('world','user','pw')
print(empire.is_under_attack())
>>>ImportError: cannot import name 'Ogame'

ACS attack IDs are not int

This morning I woke up with a lot of errors. It turns out that if you're under an ACS attack the fleet ID will be something like 'union959'. So it will throw an exception cause it can't be casted to int.

How can we handle this problem without breaking anything?

Traceback (most recent call last):
  File "/home/pi/bot/FleetSave.py", line 234, in <module>
    check_attacked()
  File "/home/pi/bot/FleetSave.py", line 80, in check_attacked
    for hostile_fleet in EMPIRE.hostile_fleet():
  File "/home/pi/bot/venv/lib/python3.7/site-packages/ogame/__init__.py", line 840, in hostile_fleet
    for id in fleet_ids
  File "/home/pi/bot/venv/lib/python3.7/site-packages/ogame/__init__.py", line 840, in <listcomp>
    for id in fleet_ids
ValueError: invalid literal for int() with base 10: 'union959'

data value error in facilities under construction

When there is a facility under construction the classes changes and it returns a data_value error.

This change seems to fix it:

levels = [int(level['data-value']) for level in bs4.find_all('span', {'class': 'level', 'data-value': True})]

I will create a pull request in develop branch

Implement buy_offer_of_the_day

This is the reference implementation of Hunt3r
-> Implement this function into Ogame lib as offer_of_the_day and buy_offer_of_the_day

import json
import math
import time
import random

def buy_offer_of_the_day(self):
    startTime = time.time()
    response = self.session.get(
        url=self.index_php +
            'page=ingame&component=traderOverview').text

    time.sleep(random.randint(250, 1500)/1000)

    response2 = self.session.post(
        url=self.index_php +
            'page=ajax&component=traderimportexport',
        data={
            'show': 'importexport',
            'ajax': 1
        },
        headers={'X-Requested-With': 'XMLHttpRequest'}).text

    time.sleep(random.randint(250, 1500) / 1000)

    bs4 = BeautifulSoup4(response2)

    try:
        item_available = bs4.find_partial(class_='bargain import_bargain take hidden').text
        return f'You have already accepted this offer!'
    except Exception as e:
        err = e
    try:
        item_price = bs4.find_partial(class_='price js_import_price').text
        item_price = int(item_price.replace('.', ''))
    except Exception as e:
        return f'err: {e}, failed to extract offer of the day price'

    try:
        planet_resources = re.search(r'var planetResources\s?=\s?({[^;]*});', response2).group(1)
        planet_resources = json.loads(planet_resources)
    except Exception as e:
        return f'err: {e}, failed to extract offer of the day planet resources'

    try:
        import_token = re.search(r'var importToken\s?=\s?"([^"]*)";', response2).group(1)
    except Exception as e:
        return f'err: {e}, failed to extract offer of the day import_token'

    try:
        multiplier = re.search(r'var multiplier\s?=\s?({[^;]*});', response2).group(1)
        multiplier = json.loads(multiplier)
    except Exception as e:
        return f'err: {e}, failed to extract offer of the day multiplier'

    form_data = {'action': 'trade'}

    remaining = item_price

    for celestial in list(planet_resources.keys()):
        metal_needed = int(planet_resources[celestial]['input']['metal'])
        if remaining < metal_needed * float(multiplier['metal']):
            metal_needed = math.ceil(remaining / float(multiplier['metal']))

        remaining -= metal_needed * float(multiplier['metal'])

        crystal_needed = int(planet_resources[celestial]['input']['crystal'])
        if remaining < crystal_needed * float(multiplier['crystal']):
            crystal_needed = math.ceil(remaining / float(multiplier['crystal']))

        remaining -= crystal_needed * float(multiplier['crystal'])

        deuterium_needed = int(planet_resources[celestial]['input']['deuterium'])
        if remaining < deuterium_needed * float(multiplier['deuterium']):
            deuterium_needed = math.ceil(remaining / float(multiplier['deuterium']))

        remaining -= deuterium_needed * float(multiplier['deuterium'])

        form_data.update(
            {
                'bid[planets][{}][metal]'.format(str(celestial)): '{}'.format(int(metal_needed)),
                'bid[planets][{}][crystal]'.format(str(celestial)): '{}'.format(str(crystal_needed)),
                'bid[planets][{}][deuterium]'.format(str(celestial)): '{}'.format(str(deuterium_needed)),
            }
        )

    form_data.update(
        {
            'bid[honor]': '0',
            'token': '{}'.format(import_token),
            'ajax': '1'
        }
    )

    time.sleep(random.randint(1500, 3000) / 1000)

    response3 = self.session.post(
        url=self.index_php +
            'page=ajax&component=traderimportexport&ajax=1&action=trade&asJson=1',
        data=form_data,
        headers={'X-Requested-With': 'XMLHttpRequest'}).json()

    try:
        new_token = response3['newAjaxToken']
    except Exception as e:
        return f'err: {e}, failed to extract offer of the day newAjaxToken'

    form_data2 = {
        'action': 'takeItem',
        'token': '{}'.format(new_token),
        'ajax': '1'
    }

    time.sleep(random.randint(250, 1500) / 1000)

    response4 = self.session.post(
        url=self.index_php +
            'page=ajax&component=traderimportexport&ajax=1&action=takeItem&asJson=1',
        data=form_data2,
        headers={'X-Requested-With': 'XMLHttpRequest'}).json()

    executionTime = (time.time() - startTime)
    print('Execution time in seconds: ' + str(executionTime))

    getitem = False
    if not response4['error']:
        getitem = True
    return getitem

building need a relogin before

Hello,

each time a try to build something, it works for 1, and failed with this for the second query :

Traceback (most recent call last):
File "", line 1, in
File "C:\Users\mtourlouse\AppData\Local\Programs\Python\Python37-32\lib\site-packages\ogame_init_.py", line 738, in build
build_token = re.search("var urlQueueAdd = (.)token=(.)'", response).group(2)
AttributeError: 'NoneType' object has no attribute 'group'

Ban Issue

Hi,

so as you might still know i forked your repo a while ago and created a full-size automation bot.

I let it run to a test account parallel to my browser based bot solution and the python one was banned within 2-3 Days of running. I bet this is because the wierd order of requests that dont match the logical order of the browser. For example requesting planet infos without the resources ajax box.

The Browser based bot ive done with gecko-fx on c# is running for about 4 months now 24/7 without detection - so my guess is that is based around that.

Login error

From last updating of ogame, when try to perform the login I have the following response:

self.ogame_session = soup.find('meta', {'name': 'ogame-session'}) \ AttributeError: 'NoneType' object has no attribute 'get'
the problem seems to be related on user agent not valid on the post request

moon ships crash

C:\Users\Guitou\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\ogame__init.py", line 605, in ships
class Ships(object):
File "C:\Users\Guitou\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\ogame__init.py", line 606, in Ships
light_fighter = Ship(0)
File "C:\Users\Guitou\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\ogame__init.py", line 589, in init__
self.amount = ships_amount[i]

Pycharm fails to offer autocomplete.

Just want to say i dont really like ToDo Comments because the normaly communicate to me a "dont do".
Now a Problem arosed when trying to work with your code. Because everything is dynamic now Pycharm fails to offer autocomplete. Is there a way to solve this. Most people using this lib are python beginners and will get frustrating by triying to write programms and the IDE fails to tell them if they made an spelling error.

print(empire.supply(empire.planet_ids()[0]).deuterium_storage.in_constructions)

this code start up fine until it gets to it.

Originally posted by @PiecePaperCode in #92 (comment)

galaxycontent

The function get_page_content() doesn't seem to work with page='galaxycontent'.
It always simply returns the overview page's html.

Playing on multiple servers with same name picks only first server

Expected Behavior

Returning an error if more then on server with the same name is returned by https://lobby.ogame.gameforge.com/api/users/me/accounts

AND/OR

possibility to choose which server should be used. Imo it would be enough to pass a language flag.

Actual Behavior

OGame object initialises with the first server in the list.

Steps to Reproduce the Problem

  1. Play on two servers with the same name with different languages
  2. Init OGame lib with universe, username and password
  3. print e.g the planet names or check the uni speed (have to be set differently)

Possible solution

Instead of only checking the server name(which alone is not unique) here, also check for the provided language(extend constructor with language flag). If language is set to None pick the first server in the list, like it is done already.

Error data-value

In facilities and other functions with : levels = [int(level['data-value']) for level in bs4.find_all(class_='level')] data-value doesn't not find.
Solution use instead : levels = [int(level['data-value']) for level in bs4.find_all('span', {'class': 'level', 'data-value': True})]
Like in supply funct

New function : check timers

Hi there,

Would it be possible to implement a new function that would check the timer on a given colony/moon, and log the status ? Ex: no activity, or 16 on planet, 41 on moon, etc...

empire.fleet() picks up wrong "arrival" values

Hello,
nice work here so far, I like it :)

I'd like to report the $subject.

In a code:

for fleet in empire.fleet():
    if fleet.mission == mission.expedition:
        print("Expedition arrival at:", fleet.arrival)

The 'fleet.arrival' sometimes picks up a wrong arrival time. (that is an arrival time of a different fleet with different ID and Mission type).

Haven't yet found out why, however still filling a ticket for tracking puropes, in case anone else would encounter this.

Using Python 3.7.7

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.