Compare commits

..

21 Commits

Author SHA1 Message Date
b13bfcdbf3 Bump version: 0.23.3.3 → 0.23.3.4 2020-12-17 18:09:43 +02:00
771dbdf826 With invalid bomb (bomb not in inventory) quit after first try 2020-12-17 18:03:04 +02:00
9646d112d2 If exception occures - set concurrency as available 2020-12-17 18:02:14 +02:00
a09c37a065 Bump version: 0.23.3.2 → 0.23.3.3 2020-12-17 15:23:39 +02:00
ba75e961fa Updated config generator 2020-12-17 15:20:21 +02:00
3b5780dbd6 Updated config generator 2020-12-17 15:18:22 +02:00
fccd0134b5 Merge branch 'remove-tox' 2020-12-17 14:07:46 +02:00
b9010fa856 Fixed MRO error 2020-12-17 14:07:29 +02:00
3e5410289e . 2020-12-17 14:03:45 +02:00
661a019b0a Broken MRO 2020-12-17 14:03:30 +02:00
23d682959d Party presidency and congress election bugfix if player is not part of a party 2020-12-17 12:13:44 +02:00
5806ccb6ca Buy food if unable to work/train because of food shortage 2020-12-14 13:51:16 +02:00
a9bc78b701 Sleep accepts floats and decimals, not only integers. Bomb deploy should use Citizen.sleep instead of utils.sleep 2020-12-11 17:22:45 +02:00
c458eb4b1c Bump version: 0.23.3.1 → 0.23.3.2 2020-12-11 11:12:34 +02:00
4af4d284c9 Updated dev requirement versions 2020-12-11 11:12:27 +02:00
104c1a0b16 Bump required python version 2020-12-11 11:12:01 +02:00
86f820771b Hits done bugfix 2020-12-11 11:11:25 +02:00
2a7af0cb7d Bump version: 0.23.3 → 0.23.3.1 2020-12-10 14:37:12 +02:00
94de509026 __all__ definitions 2020-12-10 14:36:34 +02:00
82d913bc47 Bump version: 0.23.2.11 → 0.23.3 2020-12-10 13:26:11 +02:00
c462eac369 Bomb deploy update 2020-12-10 13:25:47 +02:00
15 changed files with 255 additions and 131 deletions

1
.gitignore vendored
View File

@ -37,7 +37,6 @@ pip-delete-this-directory.txt
# Unit test / coverage reports # Unit test / coverage reports
htmlcov/ htmlcov/
.tox/
.coverage .coverage
.coverage.* .coverage.*
.cache .cache

View File

@ -1,14 +0,0 @@
# Config file for automatic testing at travis-ci.org
language: python
python:
- 3.8
- 3.7
# Command to install dependencies, e.g. pip install -r requirements_dev.txt --use-mirrors
install: pip install -U tox-travis
# Command to run tests, e.g. python setup.py test
script: tox

View File

@ -70,14 +70,14 @@ Ready to contribute? Here's how to set up `erepublik` for local development.
Now you can make your changes locally. Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the 5. When you're done making changes, check that your changes pass flake8, isort and the
tests, including testing other Python versions with tox:: tests::
$ flake8 erepublik tests $ flake8 erepublik tests
$ python setup.py test or py.test $ isort erepublik
$ tox $ python setup.py test
To get flake8 and tox, just pip install them into your virtualenv. To get flake8 and isort, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub:: 6. Commit your changes and push your branch to GitHub::

View File

@ -47,7 +47,6 @@ clean-pyc: ## remove Python file artifacts
rm -rf log/ rm -rf log/
clean-test: ## remove test and coverage artifacts clean-test: ## remove test and coverage artifacts
rm -fr .tox/
rm -f .coverage rm -f .coverage
rm -fr htmlcov/ rm -fr htmlcov/
rm -fr .pytest_cache rm -fr .pytest_cache
@ -58,9 +57,6 @@ lint: ## check style with flake8
test: ## run tests quickly with the default Python test: ## run tests quickly with the default Python
python setup.py test python setup.py test
test-all: ## run tests on every Python version with tox
tox
coverage: ## check code coverage quickly with the default Python coverage: ## check code coverage quickly with the default Python
coverage run --source erepublik setup.py test coverage run --source erepublik setup.py test
coverage report -m coverage report -m
@ -80,6 +76,7 @@ servedocs: docs ## compile the docs watching for changes
release: dist ## package and upload a release release: dist ## package and upload a release
twine upload dist/* twine upload dist/*
clean
dist: clean ## builds source and wheel package dist: clean ## builds source and wheel package
python setup.py sdist python setup.py sdist

View File

@ -8,15 +8,12 @@
<meta name="generator" content="Jekyll v4.0.1"> <meta name="generator" content="Jekyll v4.0.1">
<title>eBot configuration</title> <title>eBot configuration</title>
<!-- CSS only --> <!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
crossorigin="anonymous">
<!-- JS, Popper.js, and jQuery --> <!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
</head> </head>
<body> <body>
<div class="container"> <div class="container">
@ -37,14 +34,14 @@
<div class="col-12 col-sm-8 col-md-6"> <div class="col-12 col-sm-8 col-md-6">
<h3>Login data</h3> <h3>Login data</h3>
<div class="form-group"> <div class="form-group">
<input type="email" class="form-control form-control-sm" onchange="updateJson()" id="email" placeholder="E-mail..."> <label for="email" class="hidden"></label><input type="email" class="form-control" onchange="updateJson()" id="email" placeholder="E-mail...">
<input type="password" class="form-control form-control-sm mt-3" onchange="updateJson()" id="password" disabled placeholder="Password..." <label for="password" class="hidden"></label><input type="password" class="form-control" onchange="updateJson()" id="password" disabled placeholder="Password..."
aria-describedby="passwordHelpBlock"> aria-describedby="passwordHelpBlock">
<small id="passwordHelpBlock" class="form-text text-muted"><strong>NEVER</strong> enter Your passwords on 3rd party sites and <strong class="text-upper">DO NOT</strong> reuse Your <small id="passwordHelpBlock" class="form-text text-muted"><strong>NEVER</strong> enter Your passwords on 3rd party sites and <strong class="text-upper">DO NOT</strong> reuse Your
password!</small> password!</small>
</div> </div>
</div> </div>
<div class="col-6 col-md-3"> <div class="col-6 col-sm-4 col-md-3">
<h3>Basic tasks</h3> <h3>Basic tasks</h3>
<div class="custom-control custom-switch"> <div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="work" checked> <input type="checkbox" class="custom-control-input" onchange="updateJson()" id="work" checked>
@ -59,29 +56,6 @@
<label class="custom-control-label" for="ot">Work overtime</label> <label class="custom-control-label" for="ot">Work overtime</label>
</div> </div>
</div> </div>
<div class="col-6 col-md-3">
<h3>Misc</h3>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="renew_houses" checked>
<label class="custom-control-label" for="renew_houses">Auto renew houses</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="random_sleep" checked>
<label class="custom-control-label" for="random_sleep">Random sleep</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="buy_gold">
<label class="custom-control-label" for="buy_gold">Auto buy 10g</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="interactive" checked>
<label class="custom-control-label" for="interactive">Interactive</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="debug">
<label class="custom-control-label" for="debug">Debug</label>
</div>
</div>
</div> </div>
<div class="row"> <div class="row">
@ -200,6 +174,90 @@
<label class="custom-control-label" for="epic_hunt_ebs">Spend <small>[all]</small> EBs in epics</label> <label class="custom-control-label" for="epic_hunt_ebs">Spend <small>[all]</small> EBs in epics</label>
</div> </div>
</div> </div>
<div class="col-12 col-sm-6">
<h3 class="mt-4">Misc</h3>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="renew_houses" checked>
<label class="custom-control-label" for="renew_houses">Auto renew houses</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="random_sleep" checked>
<label class="custom-control-label" for="random_sleep">Random sleep</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="buy_gold">
<label class="custom-control-label" for="buy_gold">Auto buy 10g</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="interactive" checked>
<label class="custom-control-label" for="interactive">Interactive</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="debug">
<label class="custom-control-label" for="debug">Debug</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="spin_wheel_of_fortune">
<label class="custom-control-label" for="spin_wheel_of_fortune">Auto spin 10% of cc in WheelOfFortune</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="congress">
<label class="custom-control-label" for="congress">Auto candidate for congress</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="party_president">
<label class="custom-control-label" for="party_president">Auto candidate for party presidency</label>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="contribute_cc">
<label class="custom-control-label" for="contribute_cc">Contribute cc to country's account (weekly)</label>
</div>
</div>
<div class="col-12 col-sm-6">
<h3 class="mt-4">Advanced</h3>
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="telegram">
<label class="custom-control-label" for="telegram">Notify trough Telegram</label>
</div>
<label for="telegram_chat_id">Telegram's chat ID</label>
<input type="text" class="form-control" onchange="updateJson()" id="telegram_chat_id" placeholder="Chat ID">
<label for="telegram_token">Telegram Bot token</label>
<input type="text" class="form-control" onchange="updateJson()" id="telegram_token" placeholder="864251270:AAFzZZdjspI-kIgJVk4gF3TViGFoHnf8H4o">
<small id="telegramTokenHelp" class="form-text text-muted">Only enter token if You want to use your own Telegram bot for notification sending</small>
</div>
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" onchange="updateJson()" id="proxy">
<label class="custom-control-label" for="proxy">Use proxy</label>
</div>
<label for="proxy_kind">Proxy kind</label>
<div class="form-group">
<select class="form-control custom-select" id="proxy_kind">
<option value="socks" selected>SOCKS5</option>
<option value="http">HTTP</option>
</select>
</div>
<div class="form-group">
<label for="proxy_host">Proxy hostname or IP address</label>
<input type="text" class="form-control" onchange="updateJson()" id="proxy_host" placeholder="localhost">
</div>
<div class="form-group">
<label for="proxy_port">Proxy port</label>
<input type="text" class="form-control" onchange="updateJson()" id="proxy_port" placeholder="8080">
</div>
<div class="form-group">
<label for="proxy_user">Proxy username (optional)</label>
<input type="text" class="form-control" onchange="updateJson()" id="proxy_user" placeholder="user">
</div>
<div class="form-group">
<label for="proxy_password">Proxy password (optional)</label>
<input type="password" class="form-control" onchange="updateJson()" id="proxy_password" placeholder="password" disabled>
<small id="proxyHelpBlock" class="form-text text-muted"><strong>NEVER</strong> enter Your passwords on 3rd party sites and <strong class="text-upper">DO NOT</strong> reuse Your password!</small>
</div>
</div>
</div> </div>
</form> </form>
</div> </div>
@ -212,7 +270,9 @@
function disable(element){ function disable(element){
element.checked = false; element.checked = false;
element.disabled = true; element.disabled = true;
element.value = null;
} }
function updateJson() { function updateJson() {
let config = {}; let config = {};
let email = document.getElementById('email'); // Generated let email = document.getElementById('email'); // Generated
@ -228,6 +288,14 @@
config.renew_houses = renew_houses.checked; config.renew_houses = renew_houses.checked;
let random_sleep = document.getElementById('random_sleep'); // Generated let random_sleep = document.getElementById('random_sleep'); // Generated
config.random_sleep = random_sleep.checked; config.random_sleep = random_sleep.checked;
let spin_wheel_of_fortune = document.getElementById('spin_wheel_of_fortune'); // Generated
config.spin_wheel_of_fortune = spin_wheel_of_fortune.checked;
let congress = document.getElementById('congress'); // Generated
config.congress = congress.checked;
let party_president = document.getElementById('party_president'); // Generated
config.party_president = party_president.checked;
let contribute_cc = document.getElementById('contribute_cc'); // Generated
config.contribute_cc = contribute_cc.checked ? 10000 : false;
let buy_gold = document.getElementById('buy_gold'); // Generated let buy_gold = document.getElementById('buy_gold'); // Generated
config.buy_gold = buy_gold.checked; config.buy_gold = buy_gold.checked;
let interactive = document.getElementById('interactive'); // Generated let interactive = document.getElementById('interactive'); // Generated
@ -297,7 +365,7 @@
let travel_to_fight = document.getElementById('travel_to_fight'); // Generated let travel_to_fight = document.getElementById('travel_to_fight'); // Generated
let epic_hunt = document.getElementById('epic_hunt'); // Generated let epic_hunt = document.getElementById('epic_hunt'); // Generated
let epic_hunt_ebs = document.getElementById('epic_hunt_ebs'); // Generated let epic_hunt_ebs = document.getElementById('epic_hunt_ebs'); // Generated
if (config.fight){ if (config.fight) {
air.disabled = false; air.disabled = false;
ground.disabled = false; ground.disabled = false;
boosters.disabled = false; boosters.disabled = false;
@ -334,6 +402,60 @@
config.travel_to_fight = travel_to_fight.checked; config.travel_to_fight = travel_to_fight.checked;
config.epic_hunt = epic_hunt.checked; config.epic_hunt = epic_hunt.checked;
config.epic_hunt_ebs = config.epic_hunt ? epic_hunt_ebs.checked : config.epic_hunt; config.epic_hunt_ebs = config.epic_hunt ? epic_hunt_ebs.checked : config.epic_hunt;
// Advanced
let telegram = document.getElementById('telegram'); // Generated
config.telegram = telegram.checked;
let telegram_chat_id = document.getElementById('telegram_chat_id'); // Generated
let telegram_token = document.getElementById('telegram_token'); // Generated
if (config.telegram) {
telegram_chat_id.disabled = false;
telegram_token.disabled = false;
} else {
disable(telegram_chat_id);
disable(telegram_token);
}
config.telegram_chat_id = telegram_chat_id.value;
config.telegram_token = telegram_token.value;
let _proxy = {};
let proxy = document.getElementById('proxy'); // Generated
let proxy_kind = document.getElementById('proxy_kind'); // Generated
let proxy_host = document.getElementById('proxy_host'); // Generated
let proxy_port = document.getElementById('proxy_port'); // Generated
let proxy_user = document.getElementById('proxy_user'); // Generated
if (proxy.checked) {
proxy_kind.disabled = false;
proxy_host.disabled = false;
proxy_port.disabled = false;
proxy_user.disabled = false;
} else {
disable(proxy_kind);
disable(proxy_host);
disable(proxy_port);
disable(proxy_user);
}
_proxy.kind = proxy_kind.value;
_proxy.host = proxy_host.value;
_proxy.port = proxy_port.value;
_proxy.username = proxy_user.value;
_proxy.password = ""
if (proxy.checked) {
delete config._proxy;
config.proxy = _proxy;
} else {
delete config.proxy;
config._proxy = {
'kind': 'socks or http',
'host': 'localhost',
'port': 8080,
'username': 'optional',
'password': 'optional'
}
}
let pre = document.getElementById('json-output'); let pre = document.getElementById('json-output');
pre.textContent = JSON.stringify(config, null, 2); pre.textContent = JSON.stringify(config, null, 2);
} }

View File

@ -4,9 +4,9 @@
__author__ = """Eriks Karls""" __author__ = """Eriks Karls"""
__email__ = 'eriks@72.lv' __email__ = 'eriks@72.lv'
__version__ = '0.23.2.11' __version__ = '0.23.3.4'
from erepublik import classes, utils, constants from erepublik import classes, constants, utils
from erepublik.citizen import Citizen from erepublik.citizen import Citizen
__all__ = ["classes", "utils", "Citizen", 'constants'] __all__ = ["classes", "utils", "Citizen", 'constants']

View File

@ -15,10 +15,10 @@ class SlowRequests(Session):
timeout: datetime.timedelta = datetime.timedelta(milliseconds=500) timeout: datetime.timedelta = datetime.timedelta(milliseconds=500)
uas: List[str] = [ uas: List[str] = [
# Chrome # Chrome
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36', # noqa 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36', # noqa 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', # noqa 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36', # noqa 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
@ -285,7 +285,6 @@ class ErepublikCountryAPI(CitizenBaseAPI):
def _post_main_country_donate(self, country_id: int, action: str, value: Union[int, float], def _post_main_country_donate(self, country_id: int, action: str, value: Union[int, float],
quality: int = None) -> Response: quality: int = None) -> Response:
data = dict(countryId=country_id, action=action, _token=self.token, value=value, quality=quality) data = dict(countryId=country_id, action=action, _token=self.token, value=value, quality=quality)
return self.post(f"{self.url}/main/country-donate", data=data, return self.post(f"{self.url}/main/country-donate", data=data,
headers={"Referer": f"{self.url}/country/economy/Latvia"}) headers={"Referer": f"{self.url}/country/economy/Latvia"})
@ -360,16 +359,20 @@ class ErepublikEconomyAPI(CitizenBaseAPI):
class ErepublikLeaderBoardAPI(CitizenBaseAPI): class ErepublikLeaderBoardAPI(CitizenBaseAPI):
def _get_main_leaderboards_damage_aircraft_rankings(self, country_id: int, weeks: int = 0, mu_id: int = 0) -> Response: # noqa def _get_main_leaderboards_damage_aircraft_rankings(self, country_id: int, weeks: int = 0,
mu_id: int = 0) -> Response: # noqa
return self.get(f"{self.url}/main/leaderboards-damage-aircraft-rankings/{country_id}/{weeks}/{mu_id}/0") return self.get(f"{self.url}/main/leaderboards-damage-aircraft-rankings/{country_id}/{weeks}/{mu_id}/0")
def _get_main_leaderboards_damage_rankings(self, country_id: int, weeks: int = 0, mu_id: int = 0, div: int = 0) -> Response: # noqa def _get_main_leaderboards_damage_rankings(self, country_id: int, weeks: int = 0, mu_id: int = 0,
div: int = 0) -> Response: # noqa
return self.get(f"{self.url}/main/leaderboards-damage-rankings/{country_id}/{weeks}/{mu_id}/{div}") return self.get(f"{self.url}/main/leaderboards-damage-rankings/{country_id}/{weeks}/{mu_id}/{div}")
def _get_main_leaderboards_kills_aircraft_rankings(self, country_id: int, weeks: int = 0, mu_id: int = 0) -> Response: # noqa def _get_main_leaderboards_kills_aircraft_rankings(self, country_id: int, weeks: int = 0,
mu_id: int = 0) -> Response: # noqa
return self.get(f"{self.url}/main/leaderboards-kills-aircraft-rankings/{country_id}/{weeks}/{mu_id}/0") return self.get(f"{self.url}/main/leaderboards-kills-aircraft-rankings/{country_id}/{weeks}/{mu_id}/0")
def _get_main_leaderboards_kills_rankings(self, country_id: int, weeks: int = 0, mu_id: int = 0, div: int = 0) -> Response: # noqa def _get_main_leaderboards_kills_rankings(self, country_id: int, weeks: int = 0, mu_id: int = 0,
div: int = 0) -> Response: # noqa
return self.get(f"{self.url}/main/leaderboards-kills-rankings/{country_id}/{weeks}/{mu_id}/{div}") return self.get(f"{self.url}/main/leaderboards-kills-rankings/{country_id}/{weeks}/{mu_id}/{div}")
@ -435,8 +438,9 @@ class ErepublikMilitaryAPI(CitizenBaseAPI):
data.update(page=page) data.update(page=page)
return self.post(f"{self.url}/military/battle-console", data=data) return self.post(f"{self.url}/military/battle-console", data=data)
def _post_military_deploy_bomb(self, battle_id: int, bomb_id: int) -> Response: def _post_military_deploy_bomb(self, battle_id: int, division_id: int, side_id: int, bomb_id: int) -> Response:
data = dict(battleId=battle_id, bombId=bomb_id, _token=self.token) data = dict(battleId=battle_id, battleZoneId=division_id, sideId=side_id, sideCountryId=side_id,
bombId=bomb_id, _token=self.token)
return self.post(f"{self.url}/military/deploy-bomb", data=data) return self.post(f"{self.url}/military/deploy-bomb", data=data)
def _post_military_fight_air(self, battle_id: int, side_id: int, zone_id: int) -> Response: def _post_military_fight_air(self, battle_id: int, side_id: int, zone_id: int) -> Response:

View File

@ -11,7 +11,7 @@ from typing import Any, Dict, List, NoReturn, Optional, Set, Tuple, Union
from requests import HTTPError, RequestException, Response from requests import HTTPError, RequestException, Response
from . import utils, classes, access_points, constants from . import access_points, classes, constants, utils
from .classes import OfferItem from .classes import OfferItem
@ -417,7 +417,7 @@ class BaseCitizen(access_points.CitizenAPI):
else: else:
utils.process_error(msg, self.name, sys.exc_info(), self, None, None) utils.process_error(msg, self.name, sys.exc_info(), self, None, None)
def sleep(self, seconds: int): def sleep(self, seconds: Union[int, float, Decimal]):
if seconds < 0: if seconds < 0:
seconds = 0 seconds = 0
if self.config.interactive: if self.config.interactive:
@ -1863,7 +1863,18 @@ class CitizenMilitary(CitizenTravel):
self.travel_to_battle(battle, countries) self.travel_to_battle(battle, countries)
err = True err = True
elif r_json.get("message") == "ENEMY_KILLED": elif r_json.get("message") == "ENEMY_KILLED":
hits = (self.energy.recovered - r_json["details"]["wellness"]) // 10 # Non-InfantryKit players
if r_json['user']['earnedXp']:
hits = r_json['user']['earnedXp']
# InfantryKit player
# The almost always safe way (breaks on levelup hit)
elif self.energy.recovered >= r_json["details"]["wellness"]: # Haven't reached levelup
hits = (self.energy.recovered - r_json["details"]["wellness"]) // 10
else:
hits = r_json['hits']
if r_json['user']['epicBattle']:
hits /= 1+r_json['user']['epicBattle']
self.energy.recovered = r_json["details"]["wellness"] self.energy.recovered = r_json["details"]["wellness"]
self.details.xp = int(r_json["details"]["points"]) self.details.xp = int(r_json["details"]["points"])
damage = r_json["user"]["givenDamage"] * (1.1 if r_json["oldEnemy"]["isNatural"] else 1) damage = r_json["user"]["givenDamage"] * (1.1 if r_json["oldEnemy"]["isNatural"] else 1)
@ -1873,14 +1884,19 @@ class CitizenMilitary(CitizenTravel):
return hits, err, damage return hits, err, damage
@utils.wait_for_lock @utils.wait_for_lock
def deploy_bomb(self, battle: classes.Battle, bomb_id: int, inv_side: bool = None, count: int = 1) -> Optional[int]: def deploy_bomb(self, battle: classes.Battle, division: classes.BattleDivision, bomb_id: int, inv_side: bool, count: int = 1) -> Optional[int]:
"""Deploy bombs in a battle for given side. """Deploy bombs in a battle for given side.
:param battle: Battle :param battle: Battle
:type battle: Battle :type battle: classes.Battle
:param division: BattleDivision
:type division: classes.BattleDivision
:param bomb_id: int bomb id :param bomb_id: int bomb id
:param inv_side: should deploy on invader side, if None then will deploy in currently available side :type bomb_id: int
:param count: int how many bombs to deploy :param inv_side: should deploy on invader side
:type inv_side: bool
:param count: how many bombs to deploy
:type count: int
:return: Deployed count :return: Deployed count
:rtype: int :rtype: int
""" """
@ -1895,22 +1911,22 @@ class CitizenMilitary(CitizenTravel):
good_countries = [battle.invader.country] + battle.invader.deployed good_countries = [battle.invader.country] + battle.invader.deployed
if self.details.current_country not in good_countries: if self.details.current_country not in good_countries:
has_traveled = self.travel_to_battle(battle, good_countries) has_traveled = self.travel_to_battle(battle, good_countries)
elif inv_side is not None:
good_countries = [battle.defender.country] + battle.defender.deployed
if self.details.current_country not in good_countries:
has_traveled = self.travel_to_battle(battle, good_countries)
else: else:
involved = [battle.invader.country, involved = [battle.invader.country,
battle.defender.country] + battle.invader.deployed + battle.defender.deployed battle.defender.country] + battle.invader.deployed + battle.defender.deployed
if self.details.current_country not in involved: if self.details.current_country not in involved:
count = 0 count = 0
side = battle.invader if inv_side else battle.defender
errors = deployed_count = 0 errors = deployed_count = 0
while (not deployed_count == count) and errors < 10: while (not deployed_count == count) and errors < 10:
r = self._post_military_deploy_bomb(battle.id, bomb_id).json() r = self._post_military_deploy_bomb(battle.id, division.id, side.id, bomb_id).json()
if not r.get('error'): if not r.get('error'):
deployed_count += 1 deployed_count += 1
self.sleep(0.5)
elif r.get('message') == 'LOCKED': elif r.get('message') == 'LOCKED':
sleep(0.5) self.sleep(0.5)
elif r.get('message') == 'INVALID_BOMB':
errors = 10
else: else:
errors += 1 errors += 1
@ -2160,13 +2176,21 @@ class CitizenPolitics(BaseCitizen):
ret.update({int(id_): name}) ret.update({int(id_): name})
return ret return ret
def candidate_for_congress(self, presentation: str = "") -> Response: def candidate_for_party_presidency(self) -> Optional[Response]:
self._report_action('POLITIC_CONGRESS', 'Applied for congress elections') if self.politics.is_party_member:
return self._post_candidate_for_congress(presentation) self._report_action('POLITIC_PARTY_PRESIDENT', 'Applied for party president elections')
return self._get_candidate_party(self.politics.party_slug)
else:
self._report_action('POLITIC_CONGRESS', 'Unable to apply for party president elections - not a party member')
return None
def candidate_for_party_presidency(self) -> Response: def candidate_for_congress(self, presentation: str = "") -> Optional[Response]:
self._report_action('POLITIC_PARTY_PRESIDENT', 'Applied for party president elections') if self.politics.is_party_member:
return self._get_candidate_party(self.politics.party_slug) self._report_action('POLITIC_CONGRESS', 'Applied for congress elections')
return self._post_candidate_for_congress(presentation)
else:
self._report_action('POLITIC_CONGRESS', 'Unable to apply for congress elections - not a party member')
return None
def get_country_president_election_result( def get_country_president_election_result(
self, country: constants.Country, year: int, month: int self, country: constants.Country, year: int, month: int
@ -2290,7 +2314,7 @@ class CitizenSocial(BaseCitizen):
return self._get_main_city_data_residents(city_id, params={"search": name}).json() return self._get_main_city_data_residents(city_id, params={"search": name}).json()
class CitizenTasks(BaseCitizen): class CitizenTasks(CitizenEconomy):
tg_contract: dict = {} tg_contract: dict = {}
ot_points: int = 0 ot_points: int = 0
next_ot_time: datetime = None next_ot_time: datetime = None
@ -2308,6 +2332,8 @@ class CitizenTasks(BaseCitizen):
if js.get('message') in ['employee', 'money']: if js.get('message') in ['employee', 'money']:
self.resign_from_employer() self.resign_from_employer()
self.find_new_job() self.find_new_job()
elif js.get('message') in ['not_enough_health_food']:
self.buy_food(120)
self.update_citizen_info() self.update_citizen_info()
self.work() self.work()
else: else:
@ -2362,6 +2388,8 @@ class CitizenTasks(BaseCitizen):
else: else:
if r.json().get('message') == 'employee': if r.json().get('message') == 'employee':
self.find_new_job() self.find_new_job()
elif r.json().get('message') == 'not_enough_health_food':
self.buy_food(120)
self.reporter.report_action("WORK_OT", r.json()) self.reporter.report_action("WORK_OT", r.json())
elif self.energy.food_fights < 1 and self.ot_points >= 24: elif self.energy.food_fights < 1 and self.ot_points >= 24:
self._eat("blue") self._eat("blue")
@ -2418,8 +2446,8 @@ class CitizenTasks(BaseCitizen):
self.ot_points = ot.get("points", 0) self.ot_points = ot.get("points", 0)
class Citizen(CitizenAnniversary, CitizenCompanies, CitizenEconomy, CitizenLeaderBoard, class Citizen(CitizenAnniversary, CitizenCompanies, CitizenLeaderBoard,
CitizenMedia, CitizenMilitary, CitizenPolitics, CitizenSocial, CitizenTasks): CitizenMedia, CitizenPolitics, CitizenSocial, CitizenMilitary, CitizenTasks):
def __init__(self, email: str = "", password: str = "", auto_login: bool = False): def __init__(self, email: str = "", password: str = "", auto_login: bool = False):
super().__init__(email, password) super().__init__(email, password)
self._last_full_update = constants.min_datetime self._last_full_update = constants.min_datetime
@ -2568,7 +2596,8 @@ class Citizen(CitizenAnniversary, CitizenCompanies, CitizenEconomy, CitizenLeade
f"(Recoverable until WC end {max_count}hp | want to do {count}hits)") f"(Recoverable until WC end {max_count}hp | want to do {count}hits)")
count = count if max_count > count else max_count count = count if max_count > count else max_count
self.write_log(log_msg, False) if not silent:
self.write_log(log_msg, False)
return count, log_msg, force_fight return count, log_msg, force_fight

View File

@ -3,13 +3,14 @@ import hashlib
import threading import threading
import weakref import weakref
from decimal import Decimal from decimal import Decimal
from typing import Any, Dict, List, NamedTuple, Tuple, Union, NoReturn, Generator, Iterable from typing import Any, Dict, Generator, Iterable, List, NamedTuple, NoReturn, Tuple, Union
from requests import Response, Session, post from requests import Response, Session, post
from . import utils, constants from . import constants, utils
__all__ = ['Battle', 'BattleDivision', 'BattleSide', 'Company', 'Config', 'Details', 'Energy', 'ErepublikException', __all__ = ['Battle', 'BattleDivision', 'BattleSide', 'Company', 'Config', 'Details', 'Energy', 'ErepublikException',
'ErepublikNetworkException', 'EnergyToFight',
'Holding', 'MyCompanies', 'MyJSONEncoder', 'OfferItem', 'Politics', 'Reporter', 'TelegramReporter'] 'Holding', 'MyCompanies', 'MyJSONEncoder', 'OfferItem', 'Politics', 'Reporter', 'TelegramReporter']

View File

@ -10,7 +10,7 @@ import unicodedata
import warnings import warnings
from decimal import Decimal from decimal import Decimal
from pathlib import Path from pathlib import Path
from typing import Any, List, Optional, Union, Dict from typing import Any, Dict, List, Optional, Union
import requests import requests
@ -21,10 +21,10 @@ try:
except ImportError: except ImportError:
import json import json
__all__ = ['VERSION', 'calculate_hit', 'caught_error', 'date_from_eday', 'eday_from_date', __all__ = ['VERSION', 'calculate_hit', 'caught_error', 'date_from_eday', 'eday_from_date', 'deprecation',
'get_air_hit_dmg_value', 'get_file', 'get_ground_hit_dmg_value', 'get_sleep_seconds', 'good_timedelta', 'get_air_hit_dmg_value', 'get_file', 'get_ground_hit_dmg_value', 'get_sleep_seconds', 'good_timedelta',
'interactive_sleep', 'json', 'localize_dt', 'localize_timestamp', 'normalize_html_json', 'now', 'interactive_sleep', 'json', 'localize_dt', 'localize_timestamp', 'normalize_html_json', 'now',
'process_error', 'process_warning', 'send_email', 'silent_sleep', 'slugify', 'write_file', 'process_error', 'process_warning', 'send_email', 'silent_sleep', 'slugify', 'write_file', 'write_request',
'write_interactive_log', 'write_silent_log', 'get_final_hit_dmg', 'wait_for_lock'] 'write_interactive_log', 'write_silent_log', 'get_final_hit_dmg', 'wait_for_lock']
if not sys.version_info >= (3, 6): if not sys.version_info >= (3, 6):
@ -158,6 +158,7 @@ def write_file(filename: str, content: str) -> int:
def write_request(response: requests.Response, is_error: bool = False): def write_request(response: requests.Response, is_error: bool = False):
from erepublik import Citizen from erepublik import Citizen
# Remove GET args from url name # Remove GET args from url name
url = response.url url = response.url
last_index = url.index("?") if "?" in url else len(response.url) last_index = url.index("?") if "?" in url else len(response.url)
@ -396,7 +397,11 @@ def wait_for_lock(function):
return None return None
else: else:
instance.concurrency_available.clear() instance.concurrency_available.clear()
ret = function(instance, *args, **kwargs) try:
ret = function(instance, *args, **kwargs)
except Exception as e:
instance.concurrency_available.set()
raise e
instance.concurrency_available.set() instance.concurrency_available.set()
return ret return ret
return wrapper return wrapper

View File

@ -1,6 +1,6 @@
from datetime import timedelta from datetime import timedelta
from erepublik import Citizen, utils, constants from erepublik import Citizen, constants, utils
CONFIG = { CONFIG = {
'email': 'player@email.com', 'email': 'player@email.com',

View File

@ -4,16 +4,15 @@ edx-sphinx-theme==1.5.0
flake8==3.8.4 flake8==3.8.4
ipython>=7.19.0 ipython>=7.19.0
isort==5.6.4 isort==5.6.4
pip==20.3 pip==20.3.3
PyInstaller==4.1 PyInstaller==4.1
pytz==2020.4 pytz==2020.4
pytest==6.1.2 pytest==6.2.1
responses==0.12.1 responses==0.12.1
setuptools==50.3.2 setuptools==51.0.0
Sphinx==3.3.1 Sphinx==3.3.1
requests==2.25.0 requests>=2.24.0,<2.26.0
PySocks==1.7.1 PySocks==1.7.1
tox==3.20.1
twine==3.2.0 twine==3.2.0
watchdog==0.10.4 wheel==0.36.2
wheel==0.35.1 pur==5.3.0

View File

@ -1,5 +1,5 @@
[bumpversion] [bumpversion]
current_version = 0.23.2.11 current_version = 0.23.3.4
commit = True commit = True
tag = True tag = True
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)\.?(?P<dev>\d+)? parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)\.?(?P<dev>\d+)?
@ -18,13 +18,13 @@ replace = __version__ = '{new_version}'
universal = 1 universal = 1
[flake8] [flake8]
exclude = docs,.tox,.git,log,debug,venv exclude = docs,.git,log,debug,venv
max-line-length = 120 max-line-length = 120
ignore = D100,D101,D102,D103 ignore = D100,D101,D102,D103
[pycodestyle] [pycodestyle]
max-line-length = 120 max-line-length = 120
exclude = .tox,.git,log,debug,venv, build exclude = .git,log,debug,venv, build
[mypy] [mypy]
python_version = 3.7 python_version = 3.7

View File

@ -13,7 +13,7 @@ with open('HISTORY.rst') as history_file:
requirements = [ requirements = [
'pytz==2020.4', 'pytz==2020.4',
'requests==2.25.0', 'requests>=2.24.0,<2.26.0',
'PySocks==1.7.1' 'PySocks==1.7.1'
] ]
@ -45,11 +45,11 @@ setup(
keywords='erepublik', keywords='erepublik',
name='eRepublik', name='eRepublik',
packages=find_packages(include=['erepublik']), packages=find_packages(include=['erepublik']),
python_requires='>=3.6, <4', python_requires='>=3.7, <4',
setup_requires=setup_requirements, setup_requires=setup_requirements,
test_suite='tests', test_suite='tests',
tests_require=test_requirements, tests_require=test_requirements,
url='https://github.com/eeriks/erepublik/', url='https://github.com/eeriks/erepublik/',
version='0.23.2.11', version='0.23.3.4',
zip_safe=False, zip_safe=False,
) )

18
tox.ini
View File

@ -1,18 +0,0 @@
[tox]
envlist = py37, py38, flake8
[travis]
python =
3.7: py37
3.8: py38
[testenv:flake8]
basepython = python
deps = flake8
commands = flake8 erepublik_script
[testenv]
setenv =
PYTHONPATH = {toxinidir}
commands = python setup.py test