Compare commits

..

35 Commits

Author SHA1 Message Date
d6e161d815 Bump version: 0.15.2 → 0.15.3 2019-08-24 15:44:22 +03:00
1285e95cec Inventory usage bugfixes 2019-08-24 10:48:04 +03:00
324db2c136 Fix new division numbering 2019-08-24 10:27:31 +03:00
1c6b41e41b Inventory updates and booster usage updates 2019-08-24 10:03:52 +03:00
a52552afb7 Use MyJSONEncoder from classes 2019-08-22 14:33:45 +03:00
28bfdc7b20 Use country ids from constant in utils 2019-08-22 14:33:07 +03:00
de1b734728 Don't check levelup when eating 2019-08-22 14:32:32 +03:00
fa5646ecfd Receive daily order 2019-08-22 14:32:00 +03:00
339392cfb0 Regex bugfix 2019-08-13 15:44:07 +03:00
7ebba458cb Max time timezones 2019-08-12 14:19:52 +03:00
4f436292af Organisation account fetcher - UNSTABLE 2019-08-12 12:54:58 +03:00
416c391d21 Improved levelup energy management 2019-08-11 01:45:49 +03:00
66c53ef985 Typo 2019-08-11 01:44:45 +03:00
3fa7d097fe Found awards switch to ASCII friendlier multiplier char - ✕ -> x
Localize max div end time
2019-08-05 11:55:39 +03:00
6af9675c39 Added gameTokensMarket endpoint 2019-08-05 10:20:36 +03:00
2343a6c6c8 WeeklyChallange end energy saver tweaks 2019-08-05 10:20:19 +03:00
7e56f01a38 Added gameTokensMarket endpoint 2019-08-05 10:13:48 +03:00
e14cbc18e9 Bump version: 0.15.1 → 0.15.2 2019-08-01 17:24:07 +03:00
048ce798dd All battle div div containing dicts where reference to the same object 2019-08-01 17:23:24 +03:00
e5b7cde044 Bump version: 0.15.0 → 0.15.1 2019-08-01 15:06:34 +03:00
6bbc7a1f64 Typehinting and battle/war stuff - last battle, attackable regions if CP, etc 2019-08-01 15:05:44 +03:00
4eccb339bb Deploy bombs 2019-08-01 15:04:16 +03:00
dbeb6e9ba5 Market scraper updates 2019-08-01 09:37:26 +03:00
9c9bb5ae40 Region attacking post updated 2019-08-01 09:37:08 +03:00
d8eb69f82a Travel bugfix and market scraper fixup 2019-07-31 22:39:54 +03:00
42c430213f Minor updates 2019-07-31 21:41:24 +03:00
39dbcaa27d Continuing work on return Response free Citizen class 2019-07-31 21:41:08 +03:00
8911adb81c Traveling improved for Citizen class 2019-07-31 21:38:34 +03:00
7927c162f8 More precise type hint 2019-07-31 21:37:29 +03:00
92b7c45a7d Report promos to erep.lv 2019-07-31 21:36:57 +03:00
53257487d8 Write on country wall update 2019-07-30 18:32:12 +03:00
8690c4d3f2 minor fix 2019-07-30 11:10:35 +03:00
43c6bce160 minor fix 2019-07-30 11:10:09 +03:00
c4f598c1ba Bump version: 0.14.7 → 0.15.0 2019-07-30 10:22:38 +03:00
c48d90dec3 First step towards removing manual response parsing in Citizen class 2019-07-30 10:22:29 +03:00
8 changed files with 674 additions and 494 deletions

View File

@ -2,13 +2,20 @@
History History
======= =======
0.1.0 (2019-07-19)
------------------
* First release on PyPI. 0.15.0 (2019-07-30)
-------------------
* CitizenAPI class methods renamed to "private", they are intended to be used internally.
* TODO: None of the Citizen class's methods should return Response object - CitizenAPI is meant for that.
0.14.4 (2019-07-23) 0.14.4 (2019-07-23)
------------------- -------------------
* Wall post comment endpoints updated with comment create endpoints * Wall post comment endpoints updated with comment create endpoints.
0.1.0 (2019-07-19)
------------------
* First release on PyPI.

View File

@ -6,8 +6,8 @@ eRepublik script
.. image:: https://img.shields.io/pypi/v/erepublik.svg .. image:: https://img.shields.io/pypi/v/erepublik.svg
:target: https://pypi.python.org/pypi/erepublik :target: https://pypi.python.org/pypi/erepublik
.. image:: https://readthedocs.org/projects/erepublik/badge/?version=latest .. image:: https://readthedocs.org/projects/erepublik_script/badge/?version=latest
:target: https://erepublik.readthedocs.io/en/latest/?badge=latest :target: https://erepublik_script.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status :alt: Documentation Status

View File

@ -4,7 +4,7 @@
__author__ = """Eriks Karls""" __author__ = """Eriks Karls"""
__email__ = 'eriks@72.lv' __email__ = 'eriks@72.lv'
__version__ = '__version__ = '0.14.7'' __version__ = '0.15.3'
from erepublik import classes, utils from erepublik import classes, utils
from erepublik.citizen import Citizen from erepublik.citizen import Citizen

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@ import random
import time import time
from collections import deque from collections import deque
from json import JSONDecodeError, loads, JSONEncoder from json import JSONDecodeError, loads, JSONEncoder
from typing import Any, Dict, List, Union from typing import Any, Dict, List, Union, Mapping, Iterable
from requests import Response, Session from requests import Response, Session
@ -26,11 +26,13 @@ class ErepublikNetworkException(Exception):
class MyCompanies: class MyCompanies:
work_units: int = 0 work_units: int = 0
next_ot_time: datetime.datetime next_ot_time: datetime.datetime
holdings: Dict[int, Dict] = dict() holdings: Dict[int, Dict] = None
companies: Dict[int, Dict] = dict() companies: Dict[int, Dict] = None
ff_lockdown: int = 0 ff_lockdown: int = 0
def __init__(self): def __init__(self):
self.holdings = dict()
self.companies = dict()
self.next_ot_time = utils.now() self.next_ot_time = utils.now()
def prepare_holdings(self, holdings: dict): def prepare_holdings(self, holdings: dict):
@ -41,7 +43,7 @@ class MyCompanies:
template = dict(id=0, num_factories=0, region_id=0, companies=[]) template = dict(id=0, num_factories=0, region_id=0, companies=[])
for holding_id, holding in holdings.items(): for holding_id, holding in holdings.items():
tmp: Dict[str, Union[List[Any], Any]] = {} tmp: Dict[str, Union[Iterable[Any], Any]] = {}
for key in template: for key in template:
if key == 'companies': if key == 'companies':
tmp.update({key: []}) tmp.update({key: []})
@ -441,6 +443,9 @@ class CitizenAPI:
token: str = "" token: str = ""
def __init__(self): def __init__(self):
"""
Class for unifying eRepublik known endpoints and their required/optional parameters
"""
self._req = SlowRequests() self._req = SlowRequests()
def post(self, url: str, *args, **kwargs) -> Response: def post(self, url: str, *args, **kwargs) -> Response:
@ -449,111 +454,126 @@ class CitizenAPI:
def get(self, url: str, **kwargs) -> Response: def get(self, url: str, **kwargs) -> Response:
return self._req.get(url, **kwargs) return self._req.get(url, **kwargs)
def get_article_json(self, article_id: int) -> Response: def _get_article_json(self, article_id: int) -> Response:
return self.get("{}/main/articleJson/{}".format(self.url, article_id)) return self.get("{}/main/articleJson/{}".format(self.url, article_id))
def get_battlefield_choose_side(self, battle: int, side: int) -> Response: def _get_battlefield_choose_side(self, battle: int, side: int) -> Response:
return self.get("{}/military/battlefield-choose-side/{}/{}".format(self.url, battle, side)) return self.get("{}/military/battlefield-choose-side/{}/{}".format(self.url, battle, side))
def get_candidate_party(self, party_slug: str) -> Response: def _get_candidate_party(self, party_slug: str) -> Response:
return self.post("{}/candidate/{}".format(self.url, party_slug)) return self.post("{}/candidate/{}".format(self.url, party_slug))
def get_citizen_hovercard(self, citizen: int) -> Response: def _get_citizen_hovercard(self, citizen: int) -> Response:
return self.get("{}/main/citizen-hovercard/{}".format(self.url, citizen)) return self.get("{}/main/citizen-hovercard/{}".format(self.url, citizen))
def get_citizen_profile(self, player_id: int): def _get_citizen_profile(self, player_id: int) -> Response:
return self.get("{}/main/citizen-profile-json/{}".format(self.url, player_id)) return self.get("{}/main/citizen-profile-json/{}".format(self.url, player_id))
def get_citizen_daily_assistant(self): def _get_citizen_daily_assistant(self) -> Response:
return self.get("{}/main/citizenDailyAssistant".format(self.url)) return self.get("{}/main/citizenDailyAssistant".format(self.url))
def get_city_data_residents(self, city: int, page: int = 1, params: Dict[str, Any] = None): def _get_city_data_residents(self, city: int, page: int = 1, params: Mapping[str, Any] = None) -> Response:
if params is None: if params is None:
params = {} params = {}
return self.get("{}/main/city-data/{}/residents".format(self.url, city), params={"currentPage": page, **params}) return self.get("{}/main/city-data/{}/residents".format(self.url, city), params={"currentPage": page, **params})
def get_country_military(self, country: str) -> Response: def _get_country_military(self, country: str) -> Response:
return self.get("{}/country/military/{}".format(self.url, country)) return self.get("{}/country/military/{}".format(self.url, country))
def get_economy_inventory_items(self) -> Response: def _get_economy_citizen_accounts(self, organisation_id: int) -> Response:
return self.get("{}/economy/citizen-accounts/{}".format(self.url, organisation_id))
def _get_economy_inventory_items(self) -> Response:
return self.get("{}/economy/inventory-items/".format(self.url)) return self.get("{}/economy/inventory-items/".format(self.url))
def get_economy_job_market_json(self, country: int) -> Response: def _get_economy_job_market_json(self, country: int) -> Response:
return self.get("{}/economy/job-market-json/{}/1/desc".format(self.url, country)) return self.get("{}/economy/job-market-json/{}/1/desc".format(self.url, country))
def get_economy_my_companies(self) -> Response: def _get_economy_my_companies(self) -> Response:
return self.get("{}/economy/myCompanies".format(self.url)) return self.get("{}/economy/myCompanies".format(self.url))
def get_economy_my_market_offers(self) -> Response: def _get_economy_my_market_offers(self) -> Response:
return self.get("{}/economy/myMarketOffers".format(self.url)) return self.get("{}/economy/myMarketOffers".format(self.url))
def get_job_data(self) -> Response: def _get_job_data(self) -> Response:
return self.get("{}/main/job-data".format(self.url)) return self.get("{}/main/job-data".format(self.url))
def get_leaderboards_damage_aircraft_rankings(self, country: int, weeks: int = 0, mu: int = 0) -> Response: def _get_leaderboards_damage_aircraft_rankings(self, country: int, weeks: int = 0, mu: int = 0) -> Response:
data = (country, weeks, mu) data = (country, weeks, mu)
return self.get("{}/main/leaderboards-damage-aircraft-rankings/{}/{}/{}/0".format(self.url, *data)) return self.get("{}/main/leaderboards-damage-aircraft-rankings/{}/{}/{}/0".format(self.url, *data))
def get_leaderboards_damage_rankings(self, country: int, weeks: int = 0, mu: int = 0, div: int = 0) -> Response: def _get_leaderboards_damage_rankings(self, country: int, weeks: int = 0, mu: int = 0, div: int = 0) -> Response:
data = (country, weeks, mu, div) data = (country, weeks, mu, div)
return self.get("{}/main/leaderboards-damage-rankings/{}/{}/{}/{}".format(self.url, *data)) return self.get("{}/main/leaderboards-damage-rankings/{}/{}/{}/{}".format(self.url, *data))
def get_leaderboards_kills_aircraft_rankings(self, country: int, weeks: int = 0, mu: int = 0) -> Response: def _get_leaderboards_kills_aircraft_rankings(self, country: int, weeks: int = 0, mu: int = 0) -> Response:
data = (country, weeks, mu) data = (country, weeks, mu)
return self.get("{}/main/leaderboards-kills-aircraft-rankings/{}/{}/{}/0".format(self.url, *data)) return self.get("{}/main/leaderboards-kills-aircraft-rankings/{}/{}/{}/0".format(self.url, *data))
def get_leaderboards_kills_rankings(self, country: int, weeks: int = 0, mu: int = 0, div: int = 0) -> Response: def _get_leaderboards_kills_rankings(self, country: int, weeks: int = 0, mu: int = 0, div: int = 0) -> Response:
data = (country, weeks, mu, div) data = (country, weeks, mu, div)
return self.get("{}/main/leaderboards-kills-rankings/{}/{}/{}/{}".format(self.url, *data)) return self.get("{}/main/leaderboards-kills-rankings/{}/{}/{}/{}".format(self.url, *data))
def get_main(self): def _get_main(self) -> Response:
return self.get(self.url) return self.get(self.url)
def get_message_alerts(self, page: int = 1) -> Response: def _get_messages(self, page: int = 1) -> Response:
return self.get_message_alerts(page) return self.get("{}/main/messages-paginated/{}".format(self.url, page))
def get_military_campaigns(self) -> Response: def _get_military_campaigns(self) -> Response:
return self.get("{}/military/campaigns-new/".format(self.url)) return self.get("{}/military/campaigns-new/".format(self.url))
def get_military_unit_data(self, unit_id: int, **kwargs) -> Response: def _get_military_unit_data(self, unit_id: int, **kwargs) -> Response:
params = {"groupId": unit_id, "panel": "members", **kwargs} params = {"groupId": unit_id, "panel": "members", **kwargs}
return self.get("{}/military/military-unit-data/".format(self.url), params=params) return self.get("{}/military/military-unit-data/".format(self.url), params=params)
def get_money_donation_accept(self, donation_id: int) -> Response: def _get_money_donation_accept(self, donation_id: int) -> Response:
return self.get("{}/main/money-donation/accept/{}".format(self.url, donation_id), params={"_token": self.token}) return self.get("{}/main/money-donation/accept/{}".format(self.url, donation_id), params={"_token": self.token})
def get_money_donation_reject(self, donation_id: int) -> Response: def _get_money_donation_reject(self, donation_id: int) -> Response:
return self.get("{}/main/money-donation/reject/{}".format(self.url, donation_id), params={"_token": self.token}) return self.get("{}/main/money-donation/reject/{}".format(self.url, donation_id), params={"_token": self.token})
def get_party_members(self, party: int) -> Response: def _get_notifications_ajax_community(self, page: int = 1) -> Response:
return self.get("{}/main/notificationsAjax/community/{}".format(self.url, page))
def _get_notifications_ajax_system(self, page: int = 1) -> Response:
return self.get("{}/main/notificationsAjax/system/{}".format(self.url, page))
def _get_notifications_ajax_report(self, page: int = 1) -> Response:
return self.get("{}/main/notificationsAjax/report/{}".format(self.url, page))
def _get_party_members(self, party: int) -> Response:
return self.get("{}/main/party-members/{}".format(self.url, party)) return self.get("{}/main/party-members/{}".format(self.url, party))
def get_rankings_parties(self, country: int) -> Response: def _get_rankings_parties(self, country: int) -> Response:
return self.get("{}/main/rankings-parties/1/{}".format(self.url, country)) return self.get("{}/main/rankings-parties/1/{}".format(self.url, country))
def get_training_grounds_json(self) -> Response: def _get_training_grounds_json(self) -> Response:
return self.get("{}/main/training-grounds-json".format(self.url)) return self.get("{}/main/training-grounds-json".format(self.url))
def get_weekly_challenge_data(self) -> Response: def _get_weekly_challenge_data(self) -> Response:
return self.get("{}/main/weekly-challenge-data".format(self.url)) return self.get("{}/main/weekly-challenge-data".format(self.url))
def post_activate_battle_effect(self, battle: int, kind: str, citizen_id: int) -> Response: def _get_wars_show(self, war_id: int) -> Response:
return self.get("{}/wars/show/{}".format(self.url, war_id))
def _post_activate_battle_effect(self, battle: int, kind: str, citizen_id: int) -> Response:
data = dict(battleId=battle, citizenId=citizen_id, type=kind, _token=self.token) data = dict(battleId=battle, citizenId=citizen_id, type=kind, _token=self.token)
return self.post("{}/main/fight-activateBattleEffect".format(self.url), data=data) return self.post("{}/main/fight-activateBattleEffect".format(self.url), data=data)
def post_article_comments(self, article: int, page: int = 1) -> Response: def _post_article_comments(self, article: int, page: int = 1) -> Response:
data = dict(_token=self.token, articleId=article, page=page) data = dict(_token=self.token, articleId=article, page=page)
if page: if page:
data.update({'page': page}) data.update({'page': page})
return self.post("{}/main/articleComments".format(self.url), data=data) return self.post("{}/main/articleComments".format(self.url), data=data)
def post_article_comments_create(self, message: str, article: int, parent: int = 0) -> Response: def _post_article_comments_create(self, message: str, article: int, parent: int = 0) -> Response:
data = dict(_token=self.token, message=message, articleId=article) data = dict(_token=self.token, message=message, articleId=article)
if parent: if parent:
data.update({"parentId": parent}) data.update({"parentId": parent})
return self.post("{}/main/articleComments/create".format(self.url), data=data) return self.post("{}/main/articleComments/create".format(self.url), data=data)
def post_battle_console(self, battle: int, zone: int, round_id: int, division: int, page: int, def _post_battle_console(self, battle: int, zone: int, round_id: int, division: int, page: int,
damage: bool) -> Response: damage: bool) -> Response:
data = dict(battleId=battle, zoneId=zone, action="battleStatistics", round=round_id, division=division, data = dict(battleId=battle, zoneId=zone, action="battleStatistics", round=round_id, division=division,
leftPage=page, rightPage=page, _token=self.token) leftPage=page, rightPage=page, _token=self.token)
@ -564,15 +584,15 @@ class CitizenAPI:
return self.post("{}/military/battle-console".format(self.url), data=data) return self.post("{}/military/battle-console".format(self.url), data=data)
def post_buy_gold_items(self, currency: str, item: str, amount: int) -> Response: def _post_buy_gold_items(self, currency: str, item: str, amount: int) -> Response:
data = dict(itemId=item, currency=currency, amount=amount, _token=self.token) data = dict(itemId=item, currency=currency, amount=amount, _token=self.token)
return self.post("{}/main/buyGoldItems".format(self.url), data=data) return self.post("{}/main/buyGoldItems".format(self.url), data=data)
def post_candidate_for_congress(self, presentation: str = "") -> Response: def _post_candidate_for_congress(self, presentation: str = "") -> Response:
data = dict(_token=self.token, presentation=presentation) data = dict(_token=self.token, presentation=presentation)
return self.post("{}/candidate-for-congress".format(self.url), data=data) return self.post("{}/candidate-for-congress".format(self.url), data=data)
def post_citizen_add_remove_friend(self, citizen: int, add: bool) -> Response: def _post_citizen_add_remove_friend(self, citizen: int, add: bool) -> Response:
data = dict(_token=self.token, citizenId=citizen, url="//www.erepublik.com/en/main/citizen-addRemoveFriend") data = dict(_token=self.token, citizenId=citizen, url="//www.erepublik.com/en/main/citizen-addRemoveFriend")
if add: if add:
data.update({"action": "addFriend"}) data.update({"action": "addFriend"})
@ -580,69 +600,79 @@ class CitizenAPI:
data.update({"action": "removeFriend"}) data.update({"action": "removeFriend"})
return self.post("{}/main/citizen-addRemoveFriend".format(self.url), data=data) return self.post("{}/main/citizen-addRemoveFriend".format(self.url), data=data)
def post_collect_anniversary_reward(self) -> Response: def _post_collect_anniversary_reward(self) -> Response:
return self.post("{}/main/collect-anniversary-reward".format(self.url), data={"_token": self.token}) return self.post("{}/main/collect-anniversary-reward".format(self.url), data={"_token": self.token})
def post_country_donate(self, country: int, action: str, value: Union[int, float], quality: int = None): def _post_country_donate(self, country: int, action: str, value: Union[int, float],
quality: int = None) -> Response:
json = dict(countryId=country, action=action, _token=self.token, value=value, quality=quality) json = dict(countryId=country, action=action, _token=self.token, value=value, quality=quality)
return self.post("{}/main/country-donate".format(self.url), data=json, return self.post("{}/main/country-donate".format(self.url), data=json,
headers={"Referer": "{}/country/economy/Latvia".format(self.url)}) headers={"Referer": "{}/country/economy/Latvia".format(self.url)})
def post_daily_task_reward(self) -> Response: def _post_daily_task_reward(self) -> Response:
return self.post("{}/main/daily-tasks-reward".format(self.url), data=dict(_token=self.token)) return self.post("{}/main/daily-tasks-reward".format(self.url), data=dict(_token=self.token))
def post_delete_message(self, msg_id: list) -> Response: def _post_delete_message(self, msg_id: list) -> Response:
data = {"_token": self.token, "delete_message[]": msg_id} data = {"_token": self.token, "delete_message[]": msg_id}
return self.post("{}/main/messages-delete".format(self.url), data) return self.post("{}/main/messages-delete".format(self.url), data)
def post_eat(self, color: str) -> Response: def _post_eat(self, color: str) -> Response:
data = dict(_token=self.token, buttonColor=color) data = dict(_token=self.token, buttonColor=color)
return self.post("{}/main/eat".format(self.url), params=data) return self.post("{}/main/eat".format(self.url), params=data)
def post_economy_activate_house(self, quality: int) -> Response: def _post_economy_activate_booster(self, quality: int, duration: int, kind: str) -> Response:
data = dict(type=kind, quality=quality, duration=duration, fromInventory=True)
return self.post("{}/economy/activateBooster".format(self.url), data=data)
def _post_economy_activate_house(self, quality: int) -> Response:
data = {"action": "activate", "quality": quality, "type": "house", "_token": self.token} data = {"action": "activate", "quality": quality, "type": "house", "_token": self.token}
return self.post("{}/economy/activateHouse".format(self.url), data=data) return self.post("{}/economy/activateHouse".format(self.url), data=data)
def post_economy_assign_to_holding(self, factory: int, holding: int) -> Response: def _post_economy_assign_to_holding(self, factory: int, holding: int) -> Response:
data = dict(_token=self.token, factoryId=factory, action="assign", holdingCompanyId=holding) data = dict(_token=self.token, factoryId=factory, action="assign", holdingCompanyId=holding)
return self.post("{}/economy/assign-to-holding".format(self.url), data=data) return self.post("{}/economy/assign-to-holding".format(self.url), data=data)
def post_economy_create_company(self, industry: int, building_type: int = 1) -> Response: def _post_economy_create_company(self, industry: int, building_type: int = 1) -> Response:
data = {"_token": self.token, "company[industry_id]": industry, "company[building_type]": building_type} data = {"_token": self.token, "company[industry_id]": industry, "company[building_type]": building_type}
return self.post("{}/economy/create-company".format(self.url), data=data, return self.post("{}/economy/create-company".format(self.url), data=data,
headers={"Referer": "{}/economy/create-company".format(self.url)}) headers={"Referer": "{}/economy/create-company".format(self.url)})
def post_economy_donate_items_action(self, citizen: int, amount: int, industry: int, def _post_economy_donate_items_action(self, citizen: int, amount: int, industry: int,
quality: int) -> Response: quality: int) -> Response:
data = dict(citizen_id=citizen, amount=amount, industry_id=industry, quality=quality, _token=self.token) data = dict(citizen_id=citizen, amount=amount, industry_id=industry, quality=quality, _token=self.token)
return self.post("{}/economy/donate-items-action".format(self.url), data=data, return self.post("{}/economy/donate-items-action".format(self.url), data=data,
headers={"Referer": "{}/economy/donate-items/{}".format(self.url, citizen)}) headers={"Referer": "{}/economy/donate-items/{}".format(self.url, citizen)})
def post_economy_donate_money_action(self, citizen: int, amount: float = 0.0, def _post_economy_donate_money_action(self, citizen: int, amount: float = 0.0,
currency: int = 62) -> Response: currency: int = 62) -> Response:
data = dict(citizen_id=citizen, _token=self.token, currency_id=currency, amount=amount) data = dict(citizen_id=citizen, _token=self.token, currency_id=currency, amount=amount)
return self.post("{}/economy/donate-money-action".format(self.url), data=data, return self.post("{}/economy/donate-money-action".format(self.url), data=data,
headers={"Referer": "{}/economy/donate-money/{}".format(self.url, citizen)}) headers={"Referer": "{}/economy/donate-money/{}".format(self.url, citizen)})
def post_economy_exchange_purchase(self, amount: float, currency: int, offer: int) -> Response: def _post_economy_exchange_purchase(self, amount: float, currency: int, offer: int) -> Response:
data = dict(_token=self.token, amount=amount, currencyId=currency, offerId=offer) data = dict(_token=self.token, amount=amount, currencyId=currency, offerId=offer)
return self.post("{}/economy/exchange/purchase/".format(self.url), data=data) return self.post("{}/economy/exchange/purchase/".format(self.url), data=data)
def post_economy_exchange_retrieve(self, personal: bool, page: int, currency: int) -> Response: def _post_economy_exchange_retrieve(self, personal: bool, page: int, currency: int) -> Response:
data = dict(_token=self.token, personalOffers=int(personal), page=page, currencyId=currency) data = dict(_token=self.token, personalOffers=int(personal), page=page, currencyId=currency)
return self.post("{}/economy/exchange/retrieve/".format(self.url), data=data) return self.post("{}/economy/exchange/retrieve/".format(self.url), data=data)
def post_economy_job_market_apply(self, citizen: int, salary: int) -> Response: def _post_economy_game_tokens_market(self, action: str) -> Response:
assert action in ['retrieve', ]
data = dict(_token=self.token, action=action)
return self.post("{}/economy/gameTokensMarketAjax".format(self.url), data=data)
def _post_economy_job_market_apply(self, citizen: int, salary: int) -> Response:
data = dict(_token=self.token, citizenId=citizen, salary=salary) data = dict(_token=self.token, citizenId=citizen, salary=salary)
return self.post("{}/economy/job-market-apply".format(self.url), data=data) return self.post("{}/economy/job-market-apply".format(self.url), data=data)
def post_economy_marketplace(self, country: int, industry: int, quality: int, def _post_economy_marketplace(self, country: int, industry: int, quality: int,
order_asc: bool = True) -> Response: order_asc: bool = True) -> Response:
data = dict(countryId=country, industryId=industry, quality=quality, ajaxMarket=1, data = dict(countryId=country, industryId=industry, quality=quality, ajaxMarket=1,
orderBy="price_asc" if order_asc else "price_desc", _token=self.token) orderBy="price_asc" if order_asc else "price_desc", _token=self.token)
return self.post("{}/economy/marketplaceAjax".format(self.url), data=data) return self.post("{}/economy/marketplaceAjax".format(self.url), data=data)
def post_economy_marketplace_actions(self, amount: int, buy: bool = False, **kwargs) -> Response: def _post_economy_marketplace_actions(self, amount: int, buy: bool = False, **kwargs) -> Response:
if buy: if buy:
data = dict(_token=self.token, offerId=kwargs['offer'], amount=amount, orderBy="price_asc", currentPage=1, data = dict(_token=self.token, offerId=kwargs['offer'], amount=amount, orderBy="price_asc", currentPage=1,
buyAction=1) buyAction=1)
@ -651,12 +681,12 @@ class CitizenAPI:
industryId=kwargs["industry"], quality=kwargs["quality"], amount=amount, sellAction='postOffer') industryId=kwargs["industry"], quality=kwargs["quality"], amount=amount, sellAction='postOffer')
return self.post("{}/economy/marketplaceActions".format(self.url), data=data) return self.post("{}/economy/marketplaceActions".format(self.url), data=data)
def post_economy_resign(self) -> Response: def _post_economy_resign(self) -> Response:
return self.post("{}/economy/resign".format(self.url), return self.post("{}/economy/resign".format(self.url),
headers={"Content-Type": "application/x-www-form-urlencoded"}, headers={"Content-Type": "application/x-www-form-urlencoded"},
data={"_token": self.token, "action_type": "resign"}) data={"_token": self.token, "action_type": "resign"})
def post_economy_sell_company(self, factory: int, pin: int = None, sell: bool = True) -> Response: def _post_economy_sell_company(self, factory: int, pin: int = None, sell: bool = True) -> Response:
url = "{}/economy/sell-company/{}".format(self.url, factory) url = "{}/economy/sell-company/{}".format(self.url, factory)
data = dict(_token=self.token, pin="" if pin is None else pin) data = dict(_token=self.token, pin="" if pin is None else pin)
if sell: if sell:
@ -665,10 +695,10 @@ class CitizenAPI:
data.update({"dissolve": factory}) data.update({"dissolve": factory})
return self.post(url, data=data, headers={"Referer": url}) return self.post(url, data=data, headers={"Referer": url})
def post_economy_train(self, tg_ids: List[int]) -> Response: def _post_economy_train(self, tg_ids: List[int]) -> Response:
data: Dict[str, Union[int, str]] = {} data: Dict[str, Union[int, str]] = {}
if not tg_ids: if not tg_ids:
return self.get_training_grounds_json() return self._get_training_grounds_json()
else: else:
for idx, tg_id in enumerate(tg_ids): for idx, tg_id in enumerate(tg_ids):
data["grounds[%i][id]" % idx] = tg_id data["grounds[%i][id]" % idx] = tg_id
@ -677,11 +707,11 @@ class CitizenAPI:
data['_token'] = self.token data['_token'] = self.token
return self.post("{}/economy/train".format(self.url), data=data) return self.post("{}/economy/train".format(self.url), data=data)
def post_economy_upgrade_company(self, factory: int, level: int, pin: str = None) -> Response: def _post_economy_upgrade_company(self, factory: int, level: int, pin: str = None) -> Response:
data = dict(_token=self.token, type="upgrade", companyId=factory, level=level, pin="" if pin is None else pin) data = dict(_token=self.token, type="upgrade", companyId=factory, level=level, pin="" if pin is None else pin)
return self.post("{}/economy/upgrade-company".format(self.url), data=data) return self.post("{}/economy/upgrade-company".format(self.url), data=data)
def post_economy_work(self, action_type: str, wam: List[int] = None, employ: Dict[int, int] = None): def _post_economy_work(self, action_type: str, wam: List[int] = None, employ: Dict[int, int] = None) -> Response:
""" """
:return: requests.Response or None :return: requests.Response or None
""" """
@ -690,87 +720,91 @@ class CitizenAPI:
if wam is None: if wam is None:
wam = [] wam = []
data: Dict[str, Union[int, str]] = dict(action_type=action_type, _token=self.token) data: Dict[str, Union[int, str]] = dict(action_type=action_type, _token=self.token)
if action_type == "work": if action_type == "production":
return self.post("{}/economy/work".format(self.url), data=data)
elif action_type == "production":
max_idx = 0 max_idx = 0
for idx, company_id in enumerate(sorted(wam or [])): for company_id in sorted(wam or []):
data.update({ data.update({
"companies[%i][id]" % idx: company_id, "companies[%i][id]" % max_idx: company_id,
"companies[%i][employee_works]" % idx: employ.pop(company_id, 0), "companies[%i][employee_works]" % max_idx: employ.pop(company_id, 0),
"companies[%i][own_work]" % idx: 1 "companies[%i][own_work]" % max_idx: 1
}) })
max_idx = idx + 1 max_idx += 1
for idx, company_id in enumerate(sorted(employ or [])): for company_id in sorted(employ or []):
idx_ = idx + max_idx
data.update({ data.update({
"companies[%i][id]" % idx_: company_id, "companies[%i][id]" % max_idx: company_id,
"companies[%i][employee_works]" % idx_: employ.pop(company_id), "companies[%i][employee_works]" % max_idx: employ.pop(company_id),
"companies[%i][own_work]" % idx_: 0 "companies[%i][own_work]" % max_idx: 0
}) })
max_idx += 1
return self.post("{}/economy/work".format(self.url), data=data) return self.post("{}/economy/work".format(self.url), data=data)
else:
return
def post_economy_work_overtime(self) -> Response: def _post_economy_work_overtime(self) -> Response:
data = dict(action_type="workOvertime", _token=self.token) data = dict(action_type="workOvertime", _token=self.token)
return self.post("{}/economy/workOvertime".format(self.url), data=data) return self.post("{}/economy/workOvertime".format(self.url), data=data)
def post_forgot_password(self, email: str) -> Response: def _post_forgot_password(self, email: str) -> Response:
data = dict(_token=self.token, email=email, commit="Reset password") data = dict(_token=self.token, email=email, commit="Reset password")
return self.post("{}/forgot-password".format(self.url), data=data) return self.post("{}/forgot-password".format(self.url), data=data)
def post_fight_activate_booster(self, battle: int, quality: int, duration: int, kind: str) -> Response: def _post_fight_activate_booster(self, battle: int, quality: int, duration: int, kind: str) -> Response:
data = dict(type=kind, quality=quality, duration=duration, battleId=battle, _token=self.token) data = dict(type=kind, quality=quality, duration=duration, battleId=battle, _token=self.token)
return self.post("{}/military/fight-activateBooster".format(self.url), data=data) return self.post("{}/military/fight-activateBooster".format(self.url), data=data)
def post_login(self, email: str, password: str) -> Response: def _post_login(self, email: str, password: str) -> Response:
data = dict(csrf_token=self.token, citizen_email=email, citizen_password=password, remember='on') data = dict(csrf_token=self.token, citizen_email=email, citizen_password=password, remember='on')
return self.post("{}/login".format(self.url), data=data) return self.post("{}/login".format(self.url), data=data)
def post_messages_alert(self, notification_ids: list) -> Response: def _post_messages_alert(self, notification_ids: List[int]) -> Response:
data = {"_token": self.token, "delete_alerts[]": notification_ids, "deleteAllAlerts": "1", "delete": "Delete"} data = {"_token": self.token, "delete_alerts[]": notification_ids, "deleteAllAlerts": "1", "delete": "Delete"}
return self.post("{}/main/messages-alerts/1".format(self.url), data=data) return self.post("{}/main/messages-alerts/1".format(self.url), data=data)
def post_messages_compose(self, subject: str, body: str, citizens: List[int]) -> Response: def _post_messages_compose(self, subject: str, body: str, citizens: List[int]) -> Response:
url_pk = 0 if len(citizens) > 1 else str(citizens[0]) url_pk = 0 if len(citizens) > 1 else str(citizens[0])
data = dict(citizen_name=",".join([str(x) for x in citizens]), data = dict(citizen_name=",".join([str(x) for x in citizens]),
citizen_subject=subject, _token=self.token, citizen_message=body) citizen_subject=subject, _token=self.token, citizen_message=body)
return self.post("{}/main/messages-compose/{}}".format(self.url, url_pk), data=data) return self.post("{}/main/messages-compose/{}".format(self.url, url_pk), data=data)
def post_military_battle_console(self, battle_id: int, round_id: int, division: int) -> Response: def _post_military_battle_console(self, battle_id: int, action: str, page: int = 1, **kwargs) -> Response:
data = dict(battleId=battle_id, zoneId=round_id, action="battleStatistics", round=round_id, division=division, data = dict(battleId=battle_id, action=action, _token=self.token)
type="damage", leftPage=1, rightPage=1, _token=self.token) if action == "battleStatistics":
return self.post("{}/military/battle-console".format(self.url, battle_id), data=data) data.update(round=kwargs["round_id"], zoneId=kwargs["round_id"], leftPage=page, rightPage=page,
division=kwargs["division"], type=kwargs.get("type", 'damage'),)
elif action == "warList":
data.update(page=page)
return self.post("{}/military/battle-console".format(self.url), data=data)
def post_military_fight_air(self, battle_id: int, side_id: int) -> Response: def _post_military_deploy_bomb(self, battle_id: int, bomb_id: int) -> Response:
data = dict(battleId=battle_id, bombId=bomb_id, _token=self.token)
return self.post("{}/military/deploy-bomb".format(self.url), data=data)
def _post_military_fight_air(self, battle_id: int, side_id: int) -> Response:
data = dict(sideId=side_id, battleId=battle_id, _token=self.token) data = dict(sideId=side_id, battleId=battle_id, _token=self.token)
return self.post("{}/military/fight-shoooot/{}".format(self.url, battle_id), data=data) return self.post("{}/military/fight-shoooot/{}".format(self.url, battle_id), data=data)
def post_military_fight_ground(self, battle_id: int, side_id: int) -> Response: def _post_military_fight_ground(self, battle_id: int, side_id: int) -> Response:
data = dict(sideId=side_id, battleId=battle_id, _token=self.token) data = dict(sideId=side_id, battleId=battle_id, _token=self.token)
return self.post("{}/military/fight-shooot/{}".format(self.url, battle_id), data=data) return self.post("{}/military/fight-shooot/{}".format(self.url, battle_id), data=data)
def post_military_group_missions(self) -> Response: def _post_military_group_missions(self) -> Response:
data = dict(action="check", _token=self.token) data = dict(action="check", _token=self.token)
return self.post("{}/military/group-missions".format(self.url), data=data) return self.post("{}/military/group-missions".format(self.url), data=data)
def post_travel(self, check: str, **kwargs) -> Response: def _post_travel(self, check: str, **kwargs) -> Response:
data = dict(_token=self.token, check=check, **kwargs) data = dict(_token=self.token, check=check, **kwargs)
return self.post("{}/main/travel".format(self.url), data=data) return self.post("{}/main/travel".format(self.url), data=data)
def post_travel_data(self, **kwargs) -> Response: def _post_travel_data(self, **kwargs) -> Response:
return self.post("{}/main/travelData".format(self.url), data=dict(_token=self.token, **kwargs)) return self.post("{}/main/travelData".format(self.url), data=dict(_token=self.token, **kwargs))
def post_wars_attack_region(self, war: int, region: int) -> Response: def _post_wars_attack_region(self, war_id: int, region_id: int, region_name: str) -> Response:
data = dict(_token=self.token) data = {'_token': self.token, 'warId': war_id, 'regionName': region_name, 'regionNameConfirm': region_name}
return self.post("{}/wars/attack-region/{}/{}".format(self.url, war, region), data=data) return self.post('{}/wars/attack-region/{}/{}'.format(self.url, war_id, region_id), data=data)
def post_weekly_challenge_reward(self, reward_id: int) -> Response: def _post_weekly_challenge_reward(self, reward_id: int) -> Response:
data = dict(_token=self.token, rewardId=reward_id) data = dict(_token=self.token, rewardId=reward_id)
return self.post("{}/main/weekly-challenge-collect-reward".format(self.url), data=data) return self.post("{}/main/weekly-challenge-collect-reward".format(self.url), data=data)
def post_write_article(self, title: str, content: str, location: int, kind: int) -> Response: def _post_write_article(self, title: str, content: str, location: int, kind: int) -> Response:
data = dict(_token=self.token, article_name=title, article_body=content, article_location=location, data = dict(_token=self.token, article_name=title, article_body=content, article_location=location,
article_category=kind) article_category=kind)
return self.post("{}/main/write-article".format(self.url), data=data) return self.post("{}/main/write-article".format(self.url), data=data)
@ -778,73 +812,73 @@ class CitizenAPI:
# Wall Posts # Wall Posts
# ## Country # ## Country
def post_country_comment_retrieve(self, post_id: int): def _post_country_comment_retrieve(self, post_id: int) -> Response:
data = {"_token": self.token, "postId": post_id} data = {"_token": self.token, "postId": post_id}
return self.post("{}/main/country-comment/retrieve/json".format(self.url), data=data) return self.post("{}/main/country-comment/retrieve/json".format(self.url), data=data)
def post_country_comment_create(self, post_id: int, comment_message: str): def _post_country_comment_create(self, post_id: int, comment_message: str) -> Response:
data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message} data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message}
return self.post("{}/main/country-comment/create/json".format(self.url), data=data) return self.post("{}/main/country-comment/create/json".format(self.url), data=data)
def post_country_post_create(self, body: str, post_as: int): def _post_country_post_create(self, body: str, post_as: int) -> Response:
data = {"_token": self.token, "post_message": body, "post_as": post_as} data = {"_token": self.token, "post_message": body, "post_as": post_as}
return self.post("{}/main/country-post/create/json".format(self.url), data=data) return self.post("{}/main/country-post/create/json".format(self.url), data=data)
def post_country_post_retrieve(self): def _post_country_post_retrieve(self) -> Response:
data = {"_token": self.token, "page": 1, "switchedFrom": False} data = {"_token": self.token, "page": 1, "switchedFrom": False}
return self.post("{}/main/country-post/retrieve/json".format(self.url), data=data) return self.post("{}/main/country-post/retrieve/json".format(self.url), data=data)
# ## Military Unit # ## Military Unit
def post_military_unit_comment_retrieve(self, post_id: int): def _post_military_unit_comment_retrieve(self, post_id: int) -> Response:
data = {"_token": self.token, "postId": post_id} data = {"_token": self.token, "postId": post_id}
return self.post("{}/main/military-unit-comment/retrieve/json".format(self.url), data=data) return self.post("{}/main/military-unit-comment/retrieve/json".format(self.url), data=data)
def post_military_unit_comment_create(self, post_id: int, comment_message: str): def _post_military_unit_comment_create(self, post_id: int, comment_message: str) -> Response:
data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message} data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message}
return self.post("{}/main/military-unit-comment/create/json".format(self.url), data=data) return self.post("{}/main/military-unit-comment/create/json".format(self.url), data=data)
def post_military_unit_post_create(self, body: str, post_as: int): def _post_military_unit_post_create(self, body: str, post_as: int) -> Response:
data = {"_token": self.token, "post_message": body, "post_as": post_as} data = {"_token": self.token, "post_message": body, "post_as": post_as}
return self.post("{}/main/military-unit-post/create/json".format(self.url), data=data) return self.post("{}/main/military-unit-post/create/json".format(self.url), data=data)
def post_military_unit_post_retrieve(self): def _post_military_unit_post_retrieve(self) -> Response:
data = {"_token": self.token, "page": 1, "switchedFrom": False} data = {"_token": self.token, "page": 1, "switchedFrom": False}
return self.post("{}/main/military-unit-post/retrieve/json".format(self.url), data=data) return self.post("{}/main/military-unit-post/retrieve/json".format(self.url), data=data)
# ## Party # ## Party
def post_party_comment_retrieve(self, post_id: int): def _post_party_comment_retrieve(self, post_id: int) -> Response:
data = {"_token": self.token, "postId": post_id} data = {"_token": self.token, "postId": post_id}
return self.post("{}/main/party-comment/retrieve/json".format(self.url), data=data) return self.post("{}/main/party-comment/retrieve/json".format(self.url), data=data)
def post_party_comment_create(self, post_id: int, comment_message: str): def _post_party_comment_create(self, post_id: int, comment_message: str) -> Response:
data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message} data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message}
return self.post("{}/main/party-comment/create/json".format(self.url), data=data) return self.post("{}/main/party-comment/create/json".format(self.url), data=data)
def post_party_post_create(self, body: str): def _post_party_post_create(self, body: str) -> Response:
data = {"_token": self.token, "post_message": body} data = {"_token": self.token, "post_message": body}
return self.post("{}/main/party-post/create/json".format(self.url), data=data) return self.post("{}/main/party-post/create/json".format(self.url), data=data)
def post_party_post_retrieve(self): def _post_party_post_retrieve(self) -> Response:
data = {"_token": self.token, "page": 1, "switchedFrom": False} data = {"_token": self.token, "page": 1, "switchedFrom": False}
return self.post("{}/main/party-post/retrieve/json".format(self.url), data=data) return self.post("{}/main/party-post/retrieve/json".format(self.url), data=data)
# ## Friend's Wall # ## Friend's Wall
def post_wall_comment_retrieve(self, post_id: int): def _post_wall_comment_retrieve(self, post_id: int) -> Response:
data = {"_token": self.token, "postId": post_id} data = {"_token": self.token, "postId": post_id}
return self.post("{}/main/wall-comment/retrieve/json".format(self.url), data=data) return self.post("{}/main/wall-comment/retrieve/json".format(self.url), data=data)
def post_wall_comment_create(self, post_id: int, comment_message: str): def _post_wall_comment_create(self, post_id: int, comment_message: str) -> Response:
data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message} data = {"_token": self.token, "postId": post_id, 'comment_message': comment_message}
return self.post("{}/main/wall-comment/create/json".format(self.url), data=data) return self.post("{}/main/wall-comment/create/json".format(self.url), data=data)
def post_wall_post_create(self, body: str): def _post_wall_post_create(self, body: str) -> Response:
data = {"_token": self.token, "post_message": body} data = {"_token": self.token, "post_message": body}
return self.post("{}/main/wall-post/create/json".format(self.url), data=data) return self.post("{}/main/wall-post/create/json".format(self.url), data=data)
def post_wall_post_retrieve(self): def _post_wall_post_retrieve(self) -> Response:
data = {"_token": self.token, "page": 1, "switchedFrom": False} data = {"_token": self.token, "page": 1, "switchedFrom": False}
return self.post("{}/main/wall-post/retrieve/json".format(self.url), data=data) return self.post("{}/main/wall-post/retrieve/json".format(self.url), data=data)
@ -950,8 +984,8 @@ class MyJSONEncoder(JSONEncoder):
class BattleSide: class BattleSide:
id: int id: int
points: int points: int
deployed: List[int] = list() deployed: List[int] = None
allies: List[int] = list() allies: List[int] = None
def __init__(self, country_id: int, points: int, allies: List[int], deployed: List[int]): def __init__(self, country_id: int, points: int, allies: List[int], deployed: List[int]):
self.id = country_id self.id = country_id
@ -963,8 +997,8 @@ class BattleSide:
class BattleDivision: class BattleDivision:
end: datetime.datetime end: datetime.datetime
epic: bool epic: bool
dom_pts: Dict[str, int] = dict() dom_pts: Dict[str, int] = None
wall: Dict[str, Union[int, float]] = dict() wall: Dict[str, Union[int, float]] = None
@property @property
def div_end(self) -> bool: def div_end(self) -> bool:
@ -973,8 +1007,8 @@ class BattleDivision:
def __init__(self, end: datetime.datetime, epic: bool, inv_pts: int, def_pts: int, wall_for: int, wall_dom: float): def __init__(self, end: datetime.datetime, epic: bool, inv_pts: int, def_pts: int, wall_for: int, wall_dom: float):
self.end = end self.end = end
self.epic = epic self.epic = epic
self.dom_pts.update({"inv": inv_pts, "def": def_pts}) self.dom_pts = dict({"inv": inv_pts, "def": def_pts})
self.wall.update({"for": wall_for, "dom": wall_dom}) self.wall = dict({"for": wall_for, "dom": wall_dom})
class Battle(object): class Battle(object):
@ -986,13 +1020,13 @@ class Battle(object):
start: datetime.datetime = None start: datetime.datetime = None
invader: BattleSide = None invader: BattleSide = None
defender: BattleSide = None defender: BattleSide = None
div: Dict[int, BattleDivision] = dict() div: Dict[int, BattleDivision] = None
@property @property
def is_air(self) -> bool: def is_air(self) -> bool:
return not bool(self.zone_id % 4) return not bool(self.zone_id % 4)
def __init__(self, battle: dict): def __init__(self, battle: Dict[str, Any]):
self.id = int(battle.get('id', 0)) self.id = int(battle.get('id', 0))
self.war_id = int(battle.get('war_id', 0)) self.war_id = int(battle.get('war_id', 0))
self.zone_id = int(battle.get('zone_id', 0)) self.zone_id = int(battle.get('zone_id', 0))
@ -1009,12 +1043,13 @@ class Battle(object):
[row.get('id') for row in battle.get('def', {}).get('ally_list')], [row.get('id') for row in battle.get('def', {}).get('ally_list')],
[row.get('id') for row in battle.get('def', {}).get('ally_list') if row['deployed']]) [row.get('id') for row in battle.get('def', {}).get('ally_list') if row['deployed']])
self.div = {}
for div, data in battle.get('div', {}).items(): for div, data in battle.get('div', {}).items():
div = int(div) div = int(data.get('div'))
if data.get('end'): if data.get('end'):
end = datetime.datetime.fromtimestamp(data.get('end'), tz=utils.erep_tz) end = datetime.datetime.fromtimestamp(data.get('end'), tz=utils.erep_tz)
else: else:
end = datetime.datetime.max end = utils.localize_dt(datetime.datetime.max - datetime.timedelta(days=1))
battle_div = BattleDivision( battle_div = BattleDivision(
end=end, epic=data.get('epic_type') in [1, 5], end=end, epic=data.get('epic_type') in [1, 5],

View File

@ -7,16 +7,11 @@ import sys
import time import time
import traceback import traceback
import unicodedata import unicodedata
from collections import deque
from decimal import Decimal
from json import JSONEncoder
from pathlib import Path from pathlib import Path
from typing import Union from typing import Union, Any, List, NoReturn, Mapping
import pytz import pytz
import requests import requests
from requests import Response
__all__ = ["FOOD_ENERGY", "COMMIT_ID", "COUNTRIES", "erep_tz", __all__ = ["FOOD_ENERGY", "COMMIT_ID", "COUNTRIES", "erep_tz",
"now", "localize_dt", "localize_timestamp", "good_timedelta", "eday_from_date", "date_from_eday", "now", "localize_dt", "localize_timestamp", "good_timedelta", "eday_from_date", "date_from_eday",
@ -24,7 +19,6 @@ __all__ = ["FOOD_ENERGY", "COMMIT_ID", "COUNTRIES", "erep_tz",
"write_silent_log", "write_interactive_log", "get_file", "write_file", "write_silent_log", "write_interactive_log", "get_file", "write_file",
"send_email", "normalize_html_json", "process_error", ] "send_email", "normalize_html_json", "process_error", ]
FOOD_ENERGY = dict(q1=2, q2=4, q3=6, q4=8, q5=10, q6=12, q7=20) FOOD_ENERGY = dict(q1=2, q2=4, q3=6, q4=8, q5=10, q6=12, q7=20)
COMMIT_ID = "7b92e19" COMMIT_ID = "7b92e19"
@ -85,40 +79,37 @@ COUNTRIES = {1: 'Romania', 9: 'Brazil', 10: 'Italy', 11: 'France', 12: 'Germany'
82: 'Cyprus', 83: 'Belarus', 84: 'New Zealand', 164: 'Saudi Arabia', 165: 'Egypt', 82: 'Cyprus', 83: 'Belarus', 84: 'New Zealand', 164: 'Saudi Arabia', 165: 'Egypt',
166: 'United Arab Emirates', 167: 'Albania', 168: 'Georgia', 169: 'Armenia', 170: 'Nigeria', 171: 'Cuba'} 166: 'United Arab Emirates', 167: 'Albania', 168: 'Georgia', 169: 'Armenia', 170: 'Nigeria', 171: 'Cuba'}
COUNTRY_LINK = {1: 'Romania', 9: 'Brazil', 11: 'France', 12: 'Germany', 13: 'Hungary', 82: 'Cyprus', 168: 'Georgia',
class MyJSONEncoder(JSONEncoder): 15: 'Spain', 23: 'Canada', 26: 'Mexico', 27: 'Argentina', 28: 'Venezuela', 80: 'Montenegro', 24: 'USA',
def default(self, o): 29: 'United-Kingdom', 50: 'Australia', 47: 'South-Korea', 171: 'Cuba',
if isinstance(o, Decimal): 79: 'Republic-of-Macedonia-FYROM',
return float("{:.02f}".format(o)) 30: 'Switzerland', 31: 'Netherlands', 32: 'Belgium', 33: 'Austria', 34: 'Czech-Republic', 35: 'Poland',
elif isinstance(o, datetime.datetime): 36: 'Slovakia', 37: 'Norway', 38: 'Sweden', 39: 'Finland', 40: 'Ukraine', 41: 'Russia', 42: 'Bulgaria',
return dict(__type__='datetime', year=o.year, month=o.month, day=o.day, hour=o.hour, minute=o.minute, 43: 'Turkey', 44: 'Greece', 45: 'Japan', 48: 'India', 49: 'Indonesia', 78: 'Colombia', 68: 'Singapore',
second=o.second, microsecond=o.microsecond) 51: 'South Africa', 52: 'Republic-of-Moldova', 53: 'Portugal', 54: 'Ireland', 55: 'Denmark', 56: 'Iran',
elif isinstance(o, datetime.date): 57: 'Pakistan', 58: 'Israel', 59: 'Thailand', 61: 'Slovenia', 63: 'Croatia', 64: 'Chile', 65: 'Serbia',
return dict(__type__='date', year=o.year, month=o.month, day=o.day) 66: 'Malaysia', 67: 'Philippines', 70: 'Estonia', 165: 'Egypt', 14: 'China', 77: 'Peru', 10: 'Italy',
elif isinstance(o, datetime.timedelta): 71: 'Latvia', 72: 'Lithuania', 73: 'North-Korea', 74: 'Uruguay', 75: 'Paraguay', 76: 'Bolivia',
return dict(__type__='timedelta', days=o.days, seconds=o.seconds, 81: 'Republic-of-China-Taiwan', 166: 'United-Arab-Emirates', 167: 'Albania', 69: 'Bosnia-Herzegovina',
microseconds=o.microseconds, total_seconds=o.total_seconds()) 169: 'Armenia', 83: 'Belarus', 84: 'New-Zealand', 164: 'Saudi-Arabia', 170: 'Nigeria', }
elif isinstance(o, Response):
return dict(headers=o.headers.__dict__, url=o.url, text=o.text)
elif hasattr(o, '__dict__'):
return o.__dict__
elif isinstance(o, deque):
return list(o)
return super().default(o)
def now(): def now() -> datetime.datetime:
return datetime.datetime.now(erep_tz).replace(microsecond=0) return datetime.datetime.now(erep_tz).replace(microsecond=0)
def localize_timestamp(timestamp: int): def localize_timestamp(timestamp: int) -> datetime.datetime:
return datetime.datetime.fromtimestamp(timestamp, erep_tz) return datetime.datetime.fromtimestamp(timestamp, erep_tz)
def localize_dt(dt: Union[datetime.date, datetime.datetime]): def localize_dt(dt: Union[datetime.date, datetime.datetime]) -> datetime.datetime:
if isinstance(dt, datetime.date): try:
dt = datetime.datetime.combine(dt, datetime.time(0, 0, 0)) try:
return erep_tz.localize(dt) return erep_tz.localize(dt)
except AttributeError:
return erep_tz.localize(datetime.datetime.combine(dt, datetime.time(0, 0, 0)))
except ValueError:
return dt.astimezone(erep_tz)
def good_timedelta(dt: datetime.datetime, td: datetime.timedelta) -> datetime.datetime: def good_timedelta(dt: datetime.datetime, td: datetime.timedelta) -> datetime.datetime:
@ -237,7 +228,10 @@ def write_request(response: requests.Response, is_error: bool = False):
"mimetype": "application/json" if ext == "json" else "text/html"} "mimetype": "application/json" if ext == "json" else "text/html"}
def send_email(name: str, content: list, player=None, local_vars=dict, promo: bool = False, captcha: bool = False): def send_email(name: str, content: List[Any], player=None, local_vars: Mapping[Any, Any] = None,
promo: bool = False, captcha: bool = False):
if local_vars is None:
local_vars = {}
from erepublik import Citizen from erepublik import Citizen
file_content_template = "<html><head><title>{title}</title></head><body>{body}</body></html>" file_content_template = "<html><head><title>{title}</title></head><body>{body}</body></html>"
@ -277,6 +271,7 @@ def send_email(name: str, content: list, player=None, local_vars=dict, promo: bo
if local_vars: if local_vars:
if "state_thread" in local_vars: if "state_thread" in local_vars:
local_vars.pop('state_thread', None) local_vars.pop('state_thread', None)
from erepublik.classes import MyJSONEncoder
files.append(('file', ("local_vars.json", json.dumps(local_vars, indent=2, files.append(('file', ("local_vars.json", json.dumps(local_vars, indent=2,
cls=MyJSONEncoder, sort_keys=True), "application/json"))) cls=MyJSONEncoder, sort_keys=True), "application/json")))
if isinstance(player, Citizen): if isinstance(player, Citizen):
@ -319,7 +314,11 @@ def process_error(log_info: str, name: str, exc_info: tuple, citizen=None, commi
send_email(name, bugtrace, citizen, local_vars=trace) send_email(name, bugtrace, citizen, local_vars=trace)
def slugify(value, allow_unicode=False): def report_promo(kind: str, time_untill: datetime.datetime) -> NoReturn:
requests.post('https://api.erep.lv/promos/add/', data=dict(kind=kind, time_untill=time_untill))
def slugify(value, allow_unicode=False) -> str:
""" """
Function copied from Django2.2.1 django.utils.text.slugify Function copied from Django2.2.1 django.utils.text.slugify
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.

View File

@ -1,5 +1,5 @@
[bumpversion] [bumpversion]
current_version = 0.14.7 current_version = 0.15.3
commit = True commit = True
tag = True tag = True

View File

@ -42,6 +42,6 @@ setup(
test_suite='tests', test_suite='tests',
tests_require=test_requirements, tests_require=test_requirements,
url='https://github.com/eeriks/erepublik_script', url='https://github.com/eeriks/erepublik_script',
version='0.14.7', version='0.15.3',
zip_safe=False, zip_safe=False,
) )