def __init__(self, proxies: Dict[str, str] = None, user_agent: str = None): super().__init__() if proxies: self.proxies = proxies if user_agent is None: user_agent = random.choice(self.get_random_user_agent()) self.request_log_name = utils.get_file( utils.now().strftime("debug/requests_%Y-%m-%d.log")) self.last_time = utils.now() self.headers.update({"User-Agent": user_agent}) self.hooks["response"] = [self._log_response]
def do_init(self, chat_id: int, token: str = None, player_name: str = None): if token is None: token = "864251270:AAFzZZdjspI-kIgJVk4gF3TViGFoHnf8H4o" self.chat_id = chat_id self.api_url = f"https://api.telegram.org/bot{token}" self.player_name = player_name or "" self.__initialized = True self._last_time = utils.good_timedelta(utils.now(), datetime.timedelta(minutes=-5)) self._last_full_energy_report = utils.good_timedelta(utils.now(), datetime.timedelta(minutes=-30)) if self.__queue: self.send_message("Telegram initialized")
def _battle_monitor_air(player: Citizen): """Launch battles. Check every 5th minute (0,5,10...45,50,55) if any battle could be started on specified regions and after launching wait for 90 minutes before starting next attack so that all battles aren't launched at the same time. If player is allowed to fight, do 100 hits on the first round in players division. :param player: Logged in Citizen instance ":type player: Citizen """ global CONFIG finished_war_ids = {*[]} war_data = CONFIG.get('start_battles', {}) war_ids = {int(war_id) for war_id in war_data.keys()} next_attack_time = player.now next_attack_time = next_attack_time.replace( minute=next_attack_time.minute // 5 * 5, second=0) print("101", next_attack_time) new_battle_list = [] bh_watch_list = [] while not player.stop_threads.is_set(): try: player.update_war_info() battles = player.cus_sorted_battles_all_air() print(battles) utils.now() for id in battles: delta = utils.now() - player.all_battles[id].start time.sleep(1) print(delta) if (delta < timedelta(minutes=0)): print("found!") newbattleinfo = str(id) + ":" + str( player.all_battles[id].zone_id) print(newbattleinfo) if not newbattleinfo in new_battle_list: # message = 'find battle: ' + str(player.all_battles[id]) message2 = 'https://www.erepublik.com/en/military/battlefield/' + str( id) message3 = " new battle: " + str(delta) post(player.telegram.api_url, json=dict(chat_id=player.telegram.chat_id, text=message2, parse_mode="Markdown")) new_battle_list.append(newbattleinfo) # player.telegram.send_message('find battle: ' + str(player.all_battles[id])) continue print(battles) player.stop_threads.wait(utils.get_sleep_seconds(next_attack_time)) except: player.report_error("Task error: start_battles") ########################################################### next_attack_time = utils.good_timedelta(next_attack_time, timedelta(minutes=3)) print("133", next_attack_time) player.stop_threads.wait(utils.get_sleep_seconds(next_attack_time))
def __str__(self): time_now = utils.now() is_started = self.start < utils.now() if is_started: time_part = f" {time_now - self.start}" else: time_part = f"-{self.start - time_now}" return ( f"Battle {self.id} for {self.region_name[:16]:16} | " f"{self.invader} : {self.defender} | Round time {time_part} | {'R'+str(self.zone_id):>3}" )
def __send_messages(self): while self._next_time > utils.now(): if self.__thread_stopper.is_set(): break self.__thread_stopper.wait(utils.get_sleep_seconds(self._next_time)) message = "\n\n".join(self.__queue) if self.player_name: message = f"Player *{self.player_name}*\n\n" + message response = post(f"{self.api_url}/sendMessage", json=dict(chat_id=self.chat_id, text=message, parse_mode="Markdown")) self._last_time = utils.now() if response.json().get("ok"): self.__queue.clear() return True return False
def send_message(self, message: str) -> bool: self.__queue.append(message) if not self.__initialized: if self._last_time < utils.now(): self.__queue.clear() return True self._threads = [t for t in self._threads if t.is_alive()] self._next_time = utils.good_timedelta(utils.now(), datetime.timedelta(seconds=20)) if not self._threads: name = f"telegram_{f'{self.player_name}_' if self.player_name else ''}send" send_thread = threading.Thread(target=self.__send_messages, name=name) send_thread.start() self._threads.append(send_thread) return True
def register_account(self): if not self.__registered: r = self.__bot_update(dict(key=self.key, check=True, player_id=self.citizen_id)) if r: if not r.json().get("status"): self._req.post(f"{self.url}/bot/register", json=dict(name=self.name, email=self.email, player_id=self.citizen_id)) self.__registered = True self.allowed = True self.report_action("STARTED", value=utils.now().strftime("%F %T"))
class House: quality = None unactivated_count = 0 active_until = utils.good_timedelta(utils.now(), -datetime.timedelta(days=1)) def __init__(self, quality: int): if 0 < quality < 6: self.quality = quality @property def next_ot_point(self) -> datetime.datetime: return self.active_until
def _slow_down_requests(self): ltt = utils.good_timedelta(self.last_time, self.timeout) if ltt > utils.now(): seconds = (ltt - utils.now()).total_seconds() time.sleep(seconds if seconds > 0 else 0) self.last_time = utils.now()
def div_end(self) -> bool: return utils.now() >= self.end
def reference_time(self): if self.is_energy_full or self._recovery_time < utils.now(): ret = utils.now() else: ret = self._recovery_time return ret
def __init__(self, citizen): self._citizen = weakref.ref(citizen) self.holdings = dict() self._companies = weakref.WeakSet() self.next_ot_time = utils.now()
def report_full_energy(self, available: int, limit: int, interval: int): if (utils.now() - self._last_full_energy_report).total_seconds() >= 30 * 60: self._last_full_energy_report = utils.now() message = f"Full energy ({available}hp/{limit}hp +{interval}hp/6min)" self.send_message(message)
def __init__(self, stop_event: threading.Event = None): self._threads = [] self.__queue = [] self.__thread_stopper = threading.Event() if stop_event is None else stop_event self._last_full_energy_report = self._last_time = utils.good_timedelta(utils.now(), datetime.timedelta(hours=1)) self._next_time = utils.now()
def __init__(self): self._recovery_time = utils.now()
def _battle_monitor(player: Citizen): """Launch battles. Check every 5th minute (0,5,10...45,50,55) if any battle could be started on specified regions and after launching wait for 90 minutes before starting next attack so that all battles aren't launched at the same time. If player is allowed to fight, do 100 hits on the first round in players division. :param player: Logged in Citizen instance ":type player: Citizen """ global CONFIG finished_war_ids = {*[]} war_data = CONFIG.get('start_battles', {}) war_ids = {int(war_id) for war_id in war_data.keys()} next_attack_time = player.now next_attack_time = next_attack_time.replace( minute=next_attack_time.minute // 5 * 5, second=0) print("101", next_attack_time) new_battle_list = [] bh_watch_list = [] while not player.stop_threads.is_set(): try: player.update_war_info() battles = player.cus_sorted_battles() utils.now() for id in battles: print(player.all_battles[id]) delta = utils.now() - player.all_battles[id].start time.sleep(2) if (delta < timedelta(minutes=5) and delta > timedelta(minutes=-2)): print("found!") newbattleinfo = str(id) + ":" + str( player.all_battles[id].zone_id) print(newbattleinfo) if not newbattleinfo in new_battle_list: # message = 'find battle: ' + str(player.all_battles[id]) message2 = '/hit 2 https://www.erepublik.com/en/military/battlefield/' + str( id) + ' cn ' message3 = " new battle: " + str(delta) message4 = 'https://www.erepublik.com/en/military/battlefield/' + str( id) post(player.telegram.api_url, json=dict(chat_id=player.telegram.chat_id, text=message2, parse_mode="Markdown")) post(player.telegram.api_url, json=dict(chat_id=player.telegram.chat_id, text=message3, parse_mode="Markdown")) # post(player.telegram.api_url, # json=dict(chat_id=player.telegram.chat_id, text=message4, parse_mode="Markdown")) new_battle_list.append(newbattleinfo) # player.telegram.send_message('find battle: ' + str(player.all_battles[id])) continue if (delta > timedelta(minutes=61)): for i in range(1, 5): bh_watch = str(id) + ":" + str( player.all_battles[id].zone_id) + ":" + str(i) if bh_watch in bh_watch_list: continue place = player.get_my_status(id, div=i) if place > 1: print(bh_watch) if not bh_watch in bh_watch_list: message = 'https://www.erepublik.com/en/military/battlefield/' + str(id) \ + " check BH in Div: " + str(i) post(player.telegram.api_url, json=dict(chat_id=player.telegram.chat_id, text=message, parse_mode="Markdown")) print(message) bh_watch_list.append(bh_watch) else: print("check BH done: ", "div ", i, place) time.sleep(2) print(battles) player.stop_threads.wait(utils.get_sleep_seconds(next_attack_time)) except: player.report_error("Task error: start_battles") ########################################################### # over_time # player.update_job_info() # ot_time = player.my_companies.next_ot_time # delta = utils.now() - ot_time # print(" next overtime", delta) # if delta > timedelta(minutes=1): # player.work_ot() ################################################ next_attack_time = utils.good_timedelta(next_attack_time, timedelta(seconds=150)) print("149", next_attack_time) player.stop_threads.wait(utils.get_sleep_seconds(next_attack_time))
def has_started(self) -> bool: return self.start <= utils.now()