async def idle(self): # work cooldown time work_c = 600 war_c, is_traveling, _ = await self.check_overview() await self.do_perks_upgrade() if is_traveling: await self.sleep(600) return await self.do_storage_supply() if war_c == 0: await self.do_military_training() work_c = await self.do_work() war_c, _, _ = await self.check_overview() perk_c = await self.calculate_perks_time() gold, money = Status.check_str_money(await self.get_soup()) LOG.info(f"Your property: {money} $ {gold} G") await self.sleep(min(perk_c, war_c, work_c))
async def save_cookies(self): cookies = await self.browser.cookies('https://rivalregions.com/', 'https://www.facebook.com/', 'https://accounts.google.com/', 'https://oauth.vk.com/') pickle.dump(cookies, open("{}.pkl".format(self.profile), "wb")) LOG.info("Cookies saved!")
def decision(rushee, decision_type): rushee = Rushee.query.filter(Rushee.id == rushee)[0] rushee.decided = decision_type db.session.commit() LOG.info("Wrote %s to %s list" % (rushee.name, decision_type)) flash('Successfully added %s to %s list' % (rushee.name, decision_type)) return redirect(request.referrer)
def initLog(profile, DEBUG=False): logging.basicConfig( level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M', handlers=[ logging.StreamHandler(), handlers.RotatingFileHandler('{}.log'.format(profile), "w", 1024 * 1024 * 100, 3, "utf-8") ] ) LOG.setLevel(logging.DEBUG if DEBUG else logging.INFO)
async def do_perks_upgrade(self) -> int: LOG.debug("Do perks upgrade") await self.click(Overview.selector(), wait_for='#chat input[name=name]') t = await self.calculate_perks_time() LOG.debug(f'countdown {t/3600:.2f} hours') if t == 0: perk = Perks.perk_strategy(**self.perks) await self.upgrade(perk) return 600 else: return t
async def main(): parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) parser.add_argument("-l", "--login_method", help="登入選項: 'GOOGLE'、'FB'、'VK'", dest='login_method') parser.add_argument( "-u", "--use_to_upgrade", help='''升級道具: 'RRCash'、'GOLD'、'GOLD1' 預設使用 RRCash 1. 'GOLD' 當GOLD小於4320將會改用RRCash 2. 'GOLD1' 同1,並且對於upgrade_strategy中的最小值會使用RRCash升級 例如: "2:1:1" STR將會使用GOLD, EDU, END將會使用RRCash 也就是窮人的選擇''', default='RRCash', dest='use_to_upgrade' ) parser.add_argument("-p", "--profile", help="帳戶profile: 預設為'default', 修改可更換帳戶", default='default', dest='profile') parser.add_argument("--poor", help="你是窮人, 你買不起高級會員, 你必須手動挖礦、軍演, 可憐哪 我來幫你", action="store_true") parser.add_argument("--headless", help="確定使用者有登入成功後可開啟 將瀏覽器GUI關閉節省資源", action="store_true", dest='headless') parser.add_argument("--proxy", help="正確格式如下: socks5://localhost:1080, https://localhost:1080", dest='proxy') parser.add_argument( "--upgrade_strategy", help="三圍100後將按照時間比例來升級 default '2:1:1'", default='2:1:1', dest="upgrade_strategy" ) parser.add_argument("--debug", help="開啟Debug mod", action="store_true") args = parser.parse_args() if (args.login_method is None): parser.print_help() else: initLog(args.profile, DEBUG=args.debug) while (True): try: r = None if args.poor is True: from app.poorbot import PoorBot r = await PoorBot(**vars(args)) else: from app.rrbot import RRBot r = await RRBot(**vars(args)) await r.start() break except Exception as err: LOG.debug('Bot detect error: {}'.format(err)) # Due to "browser.close" sometime not working, use kill child processes instead. kill_child_processes(os.getpid()) if r: await r.quit() LOG.info('Restarting...')
def add(): form = RusheeForm() if form.validate_on_submit(): LOG.info(form.pic.data) rushee = Rushee(form.name.data, form.computing_id.data, form.year.data, form.dorm.data, form.pic.data) db.session.add(rushee) db.session.commit() flash('Thanks for checking in') LOG.info("Successfully logged: %s (%s)" % (form.name.data, form.computing_id.data)) return redirect(url_for('add')) else: flash_errors(form) return render_template('add.html', form=form)
async def idle(self): await self.refresh() await self.check_login() await self.do_perks_upgrade() await self.do_storage_supply() _, _, (energy, energy_cooldown_time) = await self.check_overview() if (energy >= 20) and energy_cooldown_time == 0: LOG.warn( "There is no gold in your area or automatic working expires") time = await self.calculate_perks_time() if time: gold, money = Status.check_str_money(await self.get_soup()) LOG.info(f"Your property: {money} $ {gold} G") await self.sleep(3600 if time >= 3600 else time)
async def __init__(self, login_method="GOOGLE", use_to_upgrade="RRCash", profile="default", upgrade_strategy="2:1:1", proxy=None, headless=None, poor=None, debug=False): self.profile = profile self.uri = "https://rivalregions.com" self.headless = headless if proxy: proxy = "--proxy-server={}".format(proxy) self.browser = await Browser(headless, proxy, dumpio=True) self.browser.set_default_navigation_timeout(30000) self.login_method = login_method if use_to_upgrade not in ['RRCash', 'GOLD', 'GOLD1']: self.use_to_upgrade = 'RRCash' else: self.use_to_upgrade = use_to_upgrade LOG.info(f"Will use {self.use_to_upgrade} upgrade perks.") try: self.upgrade_strategy = [ int(x) for x in upgrade_strategy.split(':') ] assert len(self.upgrade_strategy) == 3 except Exception: LOG.error("--upgrade_strategy invalid") self.perks = {'strategy': self.upgrade_strategy} await self.load_cookies() await self.browser.goto(self.uri, waitUntil='networkidle0') await self.check_login()
async def check_login(self): LOG.debug("check login") try: await self.browser.wait_for('() => {return c_html;}', timeout=10000) LOG.debug("check login successed") except Exception: LOG.debug("check login failed") await self.login()
async def upgrade(self, perk): selector = None gold, _ = Status.check_money(await self.get_soup()) minimal_strategy = [ i for i, v in enumerate(self.upgrade_strategy) if v == min(self.upgrade_strategy) ] if len(minimal_strategy) == 3: minimal_strategy = [] if self.upgrade_strategy == 'RRCash' or gold <= 4320: upgrade_selector = "#perk_target_4 > div[url='1'] > div > div" elif self.use_to_upgrade == "GOLD" or (self.use_to_upgrade == "GOLD1" and perk.value not in minimal_strategy): upgrade_selector = "#perk_target_4 > div[url='2'] > div > div" else: upgrade_selector = "#perk_target_4 > div[url='1'] > div > div" if perk == Perks.STR: selector = ".perk_item[perk='1']" elif perk == Perks.EDU: selector = ".perk_item[perk='2']" elif perk == Perks.END: selector = ".perk_item[perk='3']" else: raise Exception("Perk not found") await self.click(selector, 3) await self.click(upgrade_selector, 3) LOG.info("Upgrading {}: {} -> {}".format(perk.name, self.perks[perk.name][0], self.perks[perk.name][0] + 1))
async def do_storage_supply(self): LOG.debug("Do storage supply") await self.click(Storage.selector(), wait_for="span[action='leader/storage']") soup = BeautifulSoup((await self.browser.content()), "html5lib") # Produce energy drink if int( soup.find("span", { "urlbar": str(Storage.Energydrink.value) }).text.replace('.', '')) <= 3600: await self.click(Storage.selector(Storage.Energydrink.value), 3) gold, _ = Status.check_money(await self.get_soup()) # 6 hours ~ 24 hours amount = random.randrange(10800, 43200, 1000) if gold < amount / 10: amount = gold * 10 if amount > 300: await self.type('.storage_produce_ammount', str(amount)) await self.click('.storage_produce_button', 3) LOG.info('Produced: energy drink {} pcs.'.format(amount)) need_products = [(Storage.Bombers, 10000), (Storage.Moontanks, 10000), (Storage.Spacestations, 1280)] # Buy products for pair in need_products: product, number = pair if int( soup.find("span", { "urlbar": str(product.value) }).text.replace('.', '')) < number: await self.buy_product(product, number)
async def buy_product(self, product, amount): """ Must be #storage page : product (Storage): Storage.Bombers、..... : amount (int) """ await self.click(Storage.selector(product.value), 3) price, num = Storage.check_product_price(await self.get_soup()) _, money = Status.check_money(await self.get_soup()) # Reserve 1 billion(1kkk) for upgrade perk money -= 1000000000 if money < price: return amount = amount if num >= amount else num if price * amount > money: amount = money // price await self.type('.storage_buy_input', str(amount)) await self.click('.storage_buy_button', 3) LOG.info("Market purchase: {}, {} pcs, total {}.".format( product.name, amount, price * amount))
async def load_cookies(self): try: cookies = pickle.load(open("{}.pkl".format(self.profile), "rb")) for cookie in cookies: await self.browser.set_cookie(cookie) LOG.info("Cookies loaded!") except Exception: LOG.info('First Login') if self.headless: LOG.error('Please do not use headless mode!')
async def do_military_training(self) -> int: try: await self.click(War.selector(), 1) await self.click(War.military_training_selector(), 1) await self.click(War.send_ok_selector(), 1) await self.click(utils.close_selector(), 2) LOG.info("Military training completed") except Exception as err: LOG.debug(err) LOG.error("Military training failed") return 3598
async def login(self): LOG.debug("Login") await self.browser.goto(self.uri, waitUntil='networkidle0') selectors = { 'FB': '.sa_link[href*="facebook.com"]', 'GOOGLE': '.sa_link[href*="google.com"]', 'VK': '.sa_link[href*="vk.com"]' } try: LOG.debug("Try login") await self.browser.click(selectors[self.login_method]) await self.browser.wait_for_response('https://rivalregions.com/', timeout=240000) await self.browser.wait_for('#chat input[name=name]', timeout=10000) name = await self.browser.query_selector_eval( '#chat input[name=name]', 'node => node.value') LOG.info("Login success {}".format(name)) await self.save_cookies() except Exception as err: LOG.debug(err) await self.check_login()
def add_error_to_logs(message, user): """ Method to important error messages to app logs. """ print(message, "User: {}".format(user)) LOG.error(message + " User: {}".format(user))
async def refresh(self): LOG.debug("refresh") await self.browser.reload(waitUntil='networkidle0')
async def do_work(self) -> int: await self.click(Work.selector(), 3) await self.browser.wait_for(".imp.yellow.tip") soup = await self.get_soup() energy, energy_cooldown_time = Status.check_energy(soup) gold = Work.check_region_gold(soup) if not Work.can_work(soup): LOG.info("Working is not possible") return 600 if gold > 0 and energy >= 10: try: await self.click(Work.work_selector(), 3) await self.click(utils.close_selector(), 3) LOG.info("Work is completed {} energys use to work".format(energy)) except Exception as err: LOG.debug(err) LOG.error("Can not work, maybe the factory owner doesn't have enough money?") return 600 elif gold > 0 and energy_cooldown_time == 0 and int(self.perks['END'][0]) >= 50: await self.click(Status.energy_bar_selector(), 3) else: if int(self.perks['END'][0]) < 50: return 600 elif gold == 0: LOG.info("Region lack of gold") return 600 elif energy >= 10 or energy_cooldown_time == 0: LOG.error("Some error occurred in work") return 600 return energy_cooldown_time return await self.do_work()
async def start(self): LOG.info('Bot start') while (True): await self.idle() await self.sleep(5)
def add_to_logs(message, user): """ Method to important info messages to different logs. """ print(message, "User: {}".format(user)) LOG.info(message + " User: {}".format(user))
async def sleep(self, sec=randint(10, 30)): if (sec >= 120): LOG.info("Wait for {:.1f} minutes".format(sec / 60.0)) await asyncio.sleep(sec)