From a2447959e7bcc6c107ff4923be8912f6565c0f9f Mon Sep 17 00:00:00 2001 From: Eriks Karls Date: Sun, 5 Jan 2020 10:53:26 +0200 Subject: [PATCH] fight must receive battle id as int, added warnings support --- erepublik/citizen.py | 58 +++++++++++++++++++++++++------------------- erepublik/utils.py | 39 +++++++++++++++++++++++------ 2 files changed, 65 insertions(+), 32 deletions(-) diff --git a/erepublik/citizen.py b/erepublik/citizen.py index 96ecaf0..412065e 100644 --- a/erepublik/citizen.py +++ b/erepublik/citizen.py @@ -1,5 +1,6 @@ import re import sys +import warnings from collections import defaultdict from datetime import datetime, timedelta from itertools import product @@ -13,6 +14,7 @@ from requests import Response, RequestException from erepublik.classes import (CitizenAPI, Battle, Reporter, Config, Energy, Details, Politics, MyCompanies, TelegramBot, ErepublikException, BattleDivision, MyJSONEncoder) from erepublik.utils import * +from erepublik.utils import process_warning class Citizen(CitizenAPI): @@ -41,15 +43,15 @@ class Citizen(CitizenAPI): eday = 0 - energy: Energy - details: Details - politics: Politics - my_companies: MyCompanies - reporter: Reporter - stop_threads: Event - telegram: TelegramBot + energy: Energy = None + details: Details = None + politics: Politics = None + my_companies: MyCompanies = None + reporter: Reporter = None + stop_threads: Event = None + telegram: TelegramBot = None - r: Response + r: Response = None name = "Not logged in!" debug = False __registered = False @@ -712,35 +714,35 @@ class Citizen(CitizenAPI): # CS Battles elif self.details.citizenship in battle_sides: if battle.is_air: - cs_battles_ground.append(battle.id) - else: cs_battles_air.append(battle.id) + else: + cs_battles_ground.append(battle.id) # Current location battles: elif self.details.current_country in battle_sides: if battle.is_air: - deployed_battles_ground.append(battle.id) - else: deployed_battles_air.append(battle.id) + else: + deployed_battles_ground.append(battle.id) # Deployed battles and allied battles: elif self.details.current_country in battle.invader.allies + battle.defender.allies + battle_sides: if self.details.current_country in battle.invader.deployed + battle.defender.deployed: if battle.is_air: - deployed_battles_ground.append(battle.id) - else: deployed_battles_air.append(battle.id) + else: + deployed_battles_ground.append(battle.id) # Allied battles: else: if battle.is_air: - ally_battles_ground.append(battle.id) - else: ally_battles_air.append(battle.id) + else: + ally_battles_ground.append(battle.id) else: if battle.is_air: - other_battles_ground.append(battle.id) - else: other_battles_air.append(battle.id) + else: + other_battles_ground.append(battle.id) ret_battles += (cs_battles_air + cs_battles_ground + deployed_battles_air + deployed_battles_ground + @@ -814,7 +816,7 @@ class Citizen(CitizenAPI): self.collect_weekly_reward() break - def fight(self, battle_id: int, side_id: int = None, count: int = None): + def fight(self, battle_id: int, side_id: int = None, count: int = None) -> int: """Fight in a battle. Will auto activate booster and travel if allowed to do it and @@ -824,6 +826,10 @@ class Citizen(CitizenAPI): :param count: How many hits to do, if not specified self.should_fight() is called. :return: None if no errors while fighting, otherwise error count. """ + if not isinstance(battle_id, int): + self.report_error(f"WARNINNG! Parameter battle_id should be 'int', but it is '{type(battle_id).__name__}'") + battle_id = int(battle_id) + battle = self.all_battles[battle_id] zone_id = battle.div[11 if battle.is_air else self.division].battle_zone_id if not battle.is_air and self.config.boosters: @@ -852,8 +858,7 @@ class Citizen(CitizenAPI): if total_damage: self.reporter.report_action("FIGHT", dict(battle=battle_id, side=side_id, dmg=total_damage, air=battle.is_air, hits=total_hits)) - if error_count: - return error_count + return error_count def _shoot(self, battle_id: int, inv_side: bool, zone_id: int): battle = self.all_battles[battle_id] @@ -1142,7 +1147,7 @@ class Citizen(CitizenAPI): return self._do_wam_and_employee_work(wam_holding_id, employee_companies) else: msg = "I was not able to wam and or employ because:\n{}".format(response) - self.reporter.report_action("WORK_WAM_EMPLOYEES", value=msg) + self.reporter.report_action("WORK_WAM_EMPLOYEES", response, msg) self.write_log(msg) wam_count = self.my_companies.get_total_wam_count() if wam_count: @@ -1882,7 +1887,7 @@ class Citizen(CitizenAPI): r'class="join" title="Join">Join', html): battle_id = re.search(r'Join', html).group(1) - ret.update(can_attack=False, battle_id=battle_id) + ret.update(can_attack=False, battle_id=int(battle_id)) elif re.search(r'This war is no longer active.', html): ret.update(can_attack=False, ended=True) else: @@ -2038,8 +2043,11 @@ class Citizen(CitizenAPI): r = self._post_main_country_post_create(message, max(post_to_wall_as, key=int) if post_to_wall_as else 0) return r.json() - def report_error(self, msg: str = ""): - process_error(msg, self.name, sys.exc_info(), self, self.commit_id, False) + def report_error(self, msg: str = "", is_warning: bool = False): + if is_warning: + process_warning(msg, self.name, sys.exc_info(), self, self.commit_id, None) + else: + process_error(msg, self.name, sys.exc_info(), self, self.commit_id, None) def get_battle_top_10(self, battle_id: int) -> Dict[int, List[Tuple[int, int]]]: return {} diff --git a/erepublik/utils.py b/erepublik/utils.py index 9b3f92d..f3199da 100644 --- a/erepublik/utils.py +++ b/erepublik/utils.py @@ -8,7 +8,7 @@ import time import traceback import unicodedata from pathlib import Path -from typing import Union, Any, List, NoReturn, Mapping +from typing import Union, Any, List, NoReturn, Mapping, Optional import pytz import requests @@ -17,7 +17,7 @@ __all__ = ["FOOD_ENERGY", "COMMIT_ID", "COUNTRIES", "erep_tz", 'COUNTRY_LINK', "now", "localize_dt", "localize_timestamp", "good_timedelta", "eday_from_date", "date_from_eday", "get_sleep_seconds", "interactive_sleep", "silent_sleep", "write_silent_log", "write_interactive_log", "get_file", "write_file", - "send_email", "normalize_html_json", "process_error", 'report_promo', 'calculate_hit'] + "send_email", "normalize_html_json", "process_error", "process_warning", 'report_promo', 'calculate_hit'] FOOD_ENERGY = dict(q1=2, q2=4, q3=6, q4=8, q5=10, q6=12, q7=20) COMMIT_ID = "7b92e19" @@ -288,7 +288,7 @@ def normalize_html_json(js: str) -> str: def process_error(log_info: str, name: str, exc_info: tuple, citizen=None, commit_id: str = None, - interactive: bool = False): + interactive: Optional[bool] = None): """ Process error logging and email sending to developer :param interactive: Should print interactively @@ -299,19 +299,44 @@ def process_error(log_info: str, name: str, exc_info: tuple, citizen=None, commi :param commit_id: Code's version by commit id """ type_, value_, traceback_ = exc_info - bugtrace = [] if not commit_id else ["Commit id: %s" % commit_id, ] - bugtrace += [str(value_), str(type_), ''.join(traceback.format_tb(traceback_))] + content = [log_info] + if commit_id: + content += ["Commit id: %s" % commit_id] + content += [str(value_), str(type_), ''.join(traceback.format_tb(traceback_))] if interactive: write_interactive_log(log_info) - else: + elif interactive is not None: write_silent_log(log_info) trace = inspect.trace() if trace: trace = trace[-1][0].f_locals else: trace = dict() - send_email(name, bugtrace, citizen, local_vars=trace) + send_email(name, content, citizen, local_vars=trace) + + +def process_warning(log_info: str, name: str, exc_info: tuple, citizen=None, commit_id: str = None): + """ + Process error logging and email sending to developer + :param log_info: String to be written in output + :param name: String Instance name + :param exc_info: tuple output from sys.exc_info() + :param citizen: Citizen instance + :param commit_id: Code's version by commit id + """ + type_, value_, traceback_ = exc_info + content = [log_info] + if commit_id: + content += ["Commit id: %s" % commit_id] + content += [str(value_), str(type_), ''.join(traceback.format_tb(traceback_))] + + trace = inspect.trace() + if trace: + trace = trace[-1][0].f_locals + else: + trace = dict() + send_email(name, content, citizen, local_vars=trace) def report_promo(kind: str, time_untill: datetime.datetime) -> NoReturn: