def attackBarbarians(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: banner() island = choose_island(session) if island is None: event.set() return babarians_info = get_barbarians_lv(session, island) banner() print(_('The barbarians have:')) for name, amount in babarians_info['troops']: print(_('{} units of {}').format(amount, name)) print('') banner() print(_('From which city do you want to attack?')) city = chooseCity(session) plan = plan_attack(session, city, babarians_info) if plan is None: event.set() return banner() print( _('The barbarians in [{}:{}] will be attacked.').format( island['x'], island['y'])) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI attack the barbarians in [{}:{}]\n').format( island['x'], island['y']) setInfoSignal(session, info) try: do_it(session, island, city, babarians_info, plan) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def searchForIslandSpaces(s, e, fd): sys.stdin = os.fdopen(fd) try: if checkTelegramData(s) is False: e.set() return banner() print(_('I will search for new spaces each hour.')) enter() except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nI search for new spaces each hour\n') setInfoSignal(s, info) try: do_it(s) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def alertLowWine(s, e, fd): sys.stdin = os.fdopen(fd) try: if checkTelegramData(s) is False: e.set() return banner() hours = read(msg=_( 'How many hours should be left until the wine runs out in a city so that it\'s alerted?' ), min=1) print( _('It will be alerted when the wine runs out in less than {:d} hours in any city' ).format(hours)) enter() except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nI alert if the wine runs out in less than {:d} hours\n' ).format(hours) setInfoSignal(s, info) try: do_it(s, hours) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def createOffer(session, my_offering_market_city, resource_type, event): """ Parameters ---------- session : ikabot.web.session.Session my_offering_market_city : dict resource_type : int event : multiprocessing.Event """ banner() html = getMarketInfo(session, my_offering_market_city) sell_market_capacity = storageCapacityOfMarket(html) total_available_amount_of_resource = my_offering_market_city['recursos'][ resource_type] print( _('How much do you want to sell? [max = {}]').format( addThousandSeparator(total_available_amount_of_resource))) amount_to_sell = read(min=0, max=total_available_amount_of_resource) if amount_to_sell == 0: event.set() return price_max, price_min = re.findall(r'\'upper\': (\d+),\s*\'lower\': (\d+)', html)[resource_type] price_max = int(price_max) price_min = int(price_min) print( _('\nAt what price? [min = {:d}, max = {:d}]').format( price_min, price_max)) price = read(min=price_min, max=price_max) print( _('\nI will sell {} of {} at {}: {}').format( addThousandSeparator(amount_to_sell), materials_names[resource_type], addThousandSeparator(price), addThousandSeparator(price * amount_to_sell))) print(_('\nProceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return set_child_mode(session) event.set() info = _('\nI sell {} of {} in {}\n').format( addThousandSeparator(amount_to_sell), materials_names[resource_type], my_offering_market_city['name']) setInfoSignal(session, info) try: do_it2(session, amount_to_sell, price, resource_type, sell_market_capacity, my_offering_market_city) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def donationBot(s, e, fd): sys.stdin = os.fdopen(fd) try: banner() (cities_ids, cities) = getIdsOfCities(s) cities_dict = {} initials = [material_name[0] for material_name in materials_names] for cityId in cities_ids: tradegood = cities[cityId]['tradegood'] initial = initials[int(tradegood)] print( _('In {} ({}), Do you wish to donate to the forest, to the trading good or neither? [f/t/n]' ).format(cities[cityId]['name'], initial)) f = _('f') t = _('t') n = _('n') rta = read(values=[f, f.upper(), t, t.upper(), n, n.upper()]) if rta.lower() == f: donation_type = 'resource' elif rta.lower() == t: donation_type = 'tradegood' else: donation_type = None percentage = None if donation_type is not None: print( _('What is the maximum percentage of your storage capacity that you whish to keep occupied? (the resources that exceed it, will be donated) (default: 80%)' )) percentage = read(min=0, max=100, empty=True) if percentage == '': percentage = 80 elif percentage == 100: # if the user is ok with the storage beeing totally full, don't donate at all donation_type = None cities_dict[cityId] = { 'donation_type': donation_type, 'percentage': percentage } print(_('I will donate every day.')) enter() except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nI donate every day\n') setInfoSignal(s, info) try: do_it(s, cities_ids, cities_dict) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def searchForIslandSpaces(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) try: if checkTelegramData(session) is False: event.set() return banner() print(_('I will search for new spaces each hour.')) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI search for new spaces each hour\n') setInfoSignal(session, info) try: do_it(session) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def alertAttacks(s,e,fd): sys.stdin = os.fdopen(fd) try: if checkTelegramData(s) is False: e.set() return banner() default = 20 minutes = read(msg=_('How often should I search for attacks?(min:3, default: {:d}): ').format(default), min=3, empty=True) if minutes == '': minutes = default print(_('I will check for attacks every {:d} minutes').format(minutes)) enter() except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nI check for attacks every {:d} minutes\n').format(minutes) setInfoSignal(s, info) try: do_it(s, minutes) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def loginDaily(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: banner() print(_('I will enter every day.')) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI enter every day\n') setInfoSignal(session, info) try: do_it(session) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def createOffer(s, city, resource, e): banner() html = getStoreInfo(s, city) sell_store_capacity = storageCapacityOfStore(html) recurso_disp = city['recursos'][resource] print( _('How much do you want to sell? [max = {}]').format( addDot(recurso_disp))) amount_to_sell = read(min=0, max=recurso_disp) if amount_to_sell == 0: e.set() return price_max, price_min = re.findall(r'\'upper\': (\d+),\s*\'lower\': (\d+)', html)[resource] price_max = int(price_max) price_min = int(price_min) print( _('\nAt what price? [min = {:d}, max = {:d}]').format( price_min, price_max)) price = read(min=price_min, max=price_max) print( _('\nI will sell {} of {} at {}: {}').format( addDot(amount_to_sell), materials_names[resource], addDot(price), addDot(price * amount_to_sell))) print(_('\nProceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': e.set() return set_child_mode(s) e.set() info = _('\nI sell {} of {} in {}\n').format(addDot(amount_to_sell), materials_names[resource], city['name']) setInfoSignal(s, info) try: do_it2(s, amount_to_sell, price, resource, sell_store_capacity, city) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def alertAttacks(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: if checkTelegramData(session) is False: event.set() return banner() default = 20 minutes = read(msg=_( 'How often should I search for attacks?(min:3, default: {:d}): '). format(default), min=3, default=default) # min_units = read(msg=_('Attacks with less than how many units should be ignored? (default: 0): '), digit=True, default=0) print(_('I will check for attacks every {:d} minutes').format(minutes)) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI check for attacks every {:d} minutes\n').format(minutes) setInfoSignal(session, info) try: do_it(session, minutes) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def alertLowWine(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: if checkTelegramData(session) is False: event.set() return banner() hours = read(msg=_( 'How many hours should be left until the wine runs out in a city so that it\'s alerted?' ), min=1) print( _('It will be alerted when the wine runs out in less than {:d} hours in any city' ).format(hours)) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI alert if the wine runs out in less than {:d} hours\n' ).format(hours) setInfoSignal(session, info) try: do_it(session, hours) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def alertAttacks(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) try: if checkTelegramData(session) is False: event.set() return banner() default = 20 minutes = read(msg=_( 'How often should I search for attacks?(min:3, default: {:d}): '). format(default), min=3, empty=True) if minutes == '': minutes = default print(_('I will check for attacks every {:d} minutes').format(minutes)) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI check for attacks every {:d} minutes\n').format(minutes) setInfoSignal(session, info) try: do_it(session, minutes) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def loginDaily(s, e, fd): sys.stdin = os.fdopen(fd) try: banner() print(_('I will enter every day.')) enter() except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nI enter every day\n') setInfoSignal(s, info) try: do_it(s) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def distributeResources(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) try: banner() print(_('What resource do you want to distribute?')) print(_('(0) Exit')) for i in range(len(materials_names)): print('({:d}) {}'.format(i + 1, materials_names[i])) resource = read(min=0, max=5) if resource == 0: event.set() #give main process control before exiting return resource -= 1 if resource == 0: evenly = True else: print('\nHow do you want to distribute the resources?') print('1) From cities that produce them to cities that do not') print('2) Distribute them evenly among all cities') type_distribution = read(min=1, max=2) evenly = type_distribution == 2 if evenly: routes = distribute_evenly(session, resource) else: routes = distribute_unevenly(session, resource) if routes is None: event.set() return banner() print(_('\nThe following shipments will be made:\n')) for route in routes: print('{} -> {} : {} {}'.format(route[0]['name'], route[1]['name'], route[resource + 3], materials_names[resource]) ) #displays all routes to be executed in console print(_('\nProceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() #this is where we give back control to main process info = _('\nDistribute {}\n').format(materials_names[resource]) setInfoSignal(session, info) try: executeRoutes(session, routes) #plan trips for all the routes except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) #sends message to telegram bot finally: session.logout()
def trainArmy(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: banner() print(_('Do you want to train troops (1) or ships (2)?')) rta = read(min=1, max=2) trainTroops = rta == 1 banner() if trainTroops: print(_('In what city do you want to train the troops?')) else: print(_('In what city do you want to train the fleet?')) city = chooseCity(session) banner() lookfor = 'barracks' if trainTroops else 'shipyard' for i in range(len(city['position'])): if city['position'][i]['building'] == lookfor: city['pos'] = str(i) break else: if trainTroops: print(_('Barracks not built.')) else: print(_('Shipyard not built.')) enter() event.set() return data = getBuildingInfo(session, city, trainTroops) units_info = data[2][1] units = generateArmyData(units_info) maxSize = max([len(unit['local_name']) for unit in units]) tranings = [] while True: units = generateArmyData(units_info) print(_('Train:')) for unit in units: pad = ' ' * (maxSize - len(unit['local_name'])) amount = read(msg='{}{}:'.format(pad, unit['local_name']), min=0, empty=True) if amount == '': amount = 0 unit['cantidad'] = amount # calculate costs cost = [0] * (len(materials_names_english) + 3) for unit in units: for i in range(len(materials_names_english)): material_name = materials_names_english[i].lower() if material_name in unit['costs']: cost[i] += unit['costs'][material_name] * unit['cantidad'] if 'citizens' in unit['costs']: cost[len(materials_names_english)+0] += unit['costs']['citizens'] * unit['cantidad'] if 'upkeep' in unit['costs']: cost[len(materials_names_english)+1] += unit['costs']['upkeep'] * unit['cantidad'] if 'completiontime' in unit['costs']: cost[len(materials_names_english)+2] += unit['costs']['completiontime'] * unit['cantidad'] print(_('\nTotal cost:')) for i in range(len(materials_names_english)): if cost[i] > 0: print('{}: {}'.format(materials_names_english[i], addThousandSeparator(cost[i]))) if cost[len(materials_names_english)+0] > 0: print(_('Citizens: {}').format(addThousandSeparator(cost[len(materials_names_english)+0]))) if cost[len(materials_names_english)+1] > 0: print(_('Maintenance: {}').format(addThousandSeparator(cost[len(materials_names_english)+1]))) if cost[len(materials_names_english)+2] > 0: print(_('Duration: {}').format(daysHoursMinutes(int(cost[len(materials_names_english)+2])))) print(_('\nProceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return tranings.append(units) if trainTroops: print(_('\nDo you want to train more troops when you finish? [y/N]')) else: print(_('\nDo you want to train more fleets when you finish? [y/N]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'y': banner() continue else: break # calculate if the city has enough resources resourcesAvailable = city['recursos'].copy() resourcesAvailable.append(city['ciudadanosDisp']) for training in tranings: for unit in training: for i in range(len(materials_names_english)): material_name = materials_names_english[i].lower() if material_name in unit['costs']: resourcesAvailable[i] -= unit['costs'][material_name] * unit['cantidad'] if 'citizens' in unit['costs']: resourcesAvailable[len(materials_names_english)] -= unit['costs']['citizens'] * unit['cantidad'] not_enough = [elem for elem in resourcesAvailable if elem < 0] != [] if not_enough: print(_('\nThere are not enough resources:')) for i in range(len(materials_names_english)): if resourcesAvailable[i] < 0: print('{}:{}'.format(materials_names[i], addThousandSeparator(resourcesAvailable[i]*-1))) if resourcesAvailable[len(materials_names_english)] < 0: print(_('Citizens:{}').format(addThousandSeparator(resourcesAvailable[len(materials_names_english)]*-1))) print(_('\nProceed anyway? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return if trainTroops: print(_('\nThe selected troops will be trained.')) else: print(_('\nThe selected fleet will be trained.')) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() if trainTroops: info = _('\nI train troops in {}\n').format(city['cityName']) else: info = _('\nI train fleets in {}\n').format(city['cityName']) setInfoSignal(session, info) try: planTrainings(session, city, tranings, trainTroops) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def activateMiracle(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: banner() islands = obtainMiraclesAvailable(session) if islands == []: print(_('There are no miracles available.')) enter() event.set() return island = chooseIsland(islands) if island is None: event.set() return if island['available']: print( _('\nThe miracle {} will be activated').format( island['wonderName'])) print(_('Proceed? [Y/n]')) activate_miracle_input = read(values=['y', 'Y', 'n', 'N', '']) if activate_miracle_input.lower() == 'n': event.set() return miracle_activation_result = activateMiracleHttpCall( session, island) if miracle_activation_result[1][1][0] == 'error': print( _('The miracle {} could not be activated.').format( island['wonderName'])) enter() event.set() return data = miracle_activation_result[2][1] for elem in data: if 'countdown' in data[elem]: enddate = data[elem]['countdown']['enddate'] currentdate = data[elem]['countdown']['currentdate'] break wait_time = enddate - currentdate print( _('The miracle {} was activated.').format( island['wonderName'])) enter() banner() while True: print( _('Do you wish to activate it again when it is finished? [y/N]' )) reactivate_again_input = read(values=['y', 'Y', 'n', 'N', '']) if reactivate_again_input.lower() != 'y': event.set() return iterations = read(msg=_('How many times?: '), digit=True, min=0) if iterations == 0: event.set() return duration = wait_time * iterations print( _('It will finish in:{}').format( daysHoursMinutes(duration))) print(_('Proceed? [Y/n]')) reactivate_again_input = read(values=['y', 'Y', 'n', 'N', '']) if reactivate_again_input.lower() == 'n': banner() continue break else: print( _('\nThe miracle {} will be activated in {}').format( island['wonderName'], daysHoursMinutes(island['available_in']))) print(_('Proceed? [Y/n]')) user_confirm = read(values=['y', 'Y', 'n', 'N', '']) if user_confirm.lower() == 'n': event.set() return wait_time = island['available_in'] iterations = 1 print(_('\nThe mirable will be activated.')) enter() banner() while True: print( _('Do you wish to activate it again when it is finished? [y/N]' )) reactivate_again_input = read(values=['y', 'Y', 'n', 'N', '']) again = reactivate_again_input.lower() == 'y' if again is True: try: iterations = read(msg=_('How many times?: '), digit=True, min=0) except KeyboardInterrupt: iterations = 1 break if iterations == 0: iterations = 1 break iterations += 1 duration = wait_time * iterations print( _('It is not possible to calculate the time of finalization. (at least: {})' ).format(daysHoursMinutes(duration))) print(_('Proceed? [Y/n]')) try: activate_input = read(values=['y', 'Y', 'n', 'N', '']) except KeyboardInterrupt: iterations = 1 break if activate_input.lower() == 'n': iterations = 1 banner() continue break except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI activate the miracle {} {:d} times\n').format( island['wonderName'], iterations) setInfoSignal(session, info) try: do_it(session, island, iterations) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def buyResources(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) try: banner() # get all the cities with a store commercial_cities = getCommercialCities(session) if len(commercial_cities) == 0: print(_('There is no store build')) enter() event.set() return # choose which city to buy from if len(commercial_cities) == 1: city = commercial_cities[0] else: city = chooseCommertialCity(commercial_cities) banner() # choose resource to buy resource = chooseResource(session, city) banner() # get all the offers of the chosen resource from the chosen city offers = getOffers(session, city) if len(offers) == 0: print(_('There are no offers available.')) event.set() return # display offers to the user total_price = 0 total_amount = 0 for offer in offers: amount = offer['amountAvailable'] price = offer['precio'] cost = amount * price print(_('amount:{}').format(addDot(amount))) print(_('price :{:d}').format(price)) print(_('cost :{}').format(addDot(cost))) print('') total_price += cost total_amount += amount # ask how much to buy print( _('Total amount available to purchase: {}, for {}').format( addDot(total_amount), addDot(total_price))) available = city['freeSpaceForResources'][resource] if available < total_amount: print( _('You just can buy {} due to storing capacity').format( addDot(available))) total_amount = available print('') amount_to_buy = read(msg=_('How much do you want to buy?: '), min=0, max=total_amount) if amount_to_buy == 0: event.set() return # calculate the total cost gold = getGold(session, city) total_cost = calculateCost(offers, amount_to_buy) print( _('\nCurrent gold: {}.\nTotal cost : {}.\nFinal gold : {}.' ).format(addDot(gold), addDot(total_cost), addDot(gold - total_cost))) print(_('Proceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return print(_('It will be purchased {}').format(addDot(amount_to_buy))) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI will buy {} from {} to {}\n').format( addDot(amount_to_buy), materials_names[resource], city['cityName']) setInfoSignal(session, info) try: do_it(session, city, offers, amount_to_buy) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def constructionList(s, e, fd): sys.stdin = os.fdopen(fd) try: global expand global sendResources expand = True sendResources = True banner() wait_resources = False print(_('In which city do you want to expand a building?')) city = chooseCity(s) cityId = city['id'] building = getBuildingToExpand(s, cityId) if building is None: e.set() return current_level = building['level'] if building['isBusy']: current_level += 1 final_level = building['upgradeTo'] # calculate the resources that are needed resourcesNeeded = getResourcesNeeded(s, city, building, current_level, final_level) if -1 in resourcesNeeded: e.set() return # calculate the resources that are missing missing = [0] * len(materials_names) for i in range(len(materials_names)): if city['recursos'][i] < resourcesNeeded[i]: missing[i] = resourcesNeeded[i] - city['recursos'][i] # show missing resources to the user if sum(missing) > 0: print(_('\nMissing:')) for i in range(len(materials_names)): if missing[i] == 0: continue name = materials_names[i].lower() print(_('{} of {}').format(addDot(missing[i]), name)) print('') # if the user wants, send the resources from the selected cities print(_('Automatically transport resources? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': print(_('Proceed anyway? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': e.set() return else: wait_resources = True sendResourcesMenu(s, cityId, missing) else: print(_('\nYou have enough materials')) print(_('Proceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': e.set() return except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nUpgrade building\n') info = info + _('City: {}\nBuilding: {}. From {:d}, to {:d}').format( city['cityName'], building['name'], current_level, final_level) setInfoSignal(s, info) try: if expand: expandBuilding(s, cityId, building, wait_resources) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()
def constructionList(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: global expand global sendResources expand = True sendResources = True banner() wait_resources = False print(_('In which city do you want to expand a building?')) city = chooseCity(session) cityId = city['id'] building = getBuildingToExpand(session, cityId) if building is None: event.set() return current_level = building['level'] if building['isBusy']: current_level += 1 final_level = building['upgradeTo'] # calculate the resources that are needed resourcesNeeded = getResourcesNeeded(session, city, building, current_level, final_level) if -1 in resourcesNeeded: event.set() return print('\nMaterials needed:') for i, name in enumerate(materials_names): amount = resourcesNeeded[i] if amount == 0: continue print('- {}: {}'.format(name, addThousandSeparator(amount))) print('') # calculate the resources that are missing missing = [0] * len(materials_names) for i in range(len(materials_names)): if city['recursos'][i] < resourcesNeeded[i]: missing[i] = resourcesNeeded[i] - city['recursos'][i] # show missing resources to the user if sum(missing) > 0: print(_('\nMissing:')) for i in range(len(materials_names)): if missing[i] == 0: continue name = materials_names[i].lower() print( _('{} of {}').format(addThousandSeparator(missing[i]), name)) print('') # if the user wants, send the resources from the selected cities print(_('Automatically transport resources? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': print(_('Proceed anyway? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return else: wait_resources = True sendResourcesMenu(session, cityId, missing) else: print(_('\nYou have enough materials')) print(_('Proceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nUpgrade building\n') info = info + _('City: {}\nBuilding: {}. From {:d}, to {:d}').format( city['cityName'], building['name'], current_level, final_level) setInfoSignal(session, info) try: if expand: expandBuilding(session, cityId, building, wait_resources) elif thread: thread.join() except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def sellToOffers(session, city_to_buy_from, resource_type, event): """ Parameters ---------- session : ikabot.web.session.Session city_to_buy_from : dict resource_type : int event : multiprocessing.Event """ banner() offers = getOffers(session, city_to_buy_from, resource_type) if len(offers) == 0: print(_('No offers available.')) enter() event.set() return print(_('Which offers do you want to sell to?\n')) chosen_offers = [] total_amount = 0 profit = 0 for offer in offers: cityname, username, amount, price, dist, destination_city_id = offer cityname = cityname.strip() amount = amount.replace(',', '').replace('.', '') amount = int(amount) price = int(price) msg = _('{} ({}): {} at {:d} each ({} in total) [Y/n]').format( cityname, username, addThousandSeparator(amount), price, addThousandSeparator(price * amount)) rta = read(msg=msg, values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': continue chosen_offers.append(offer) total_amount += amount profit += amount * price if len(chosen_offers) == 0: event.set() return available = city_to_buy_from['recursos'][resource_type] amount_to_sell = min(available, total_amount) banner() print( _('\nHow much do you want to sell? [max = {}]').format( addThousandSeparator(amount_to_sell))) amount_to_sell = read(min=0, max=amount_to_sell) if amount_to_sell == 0: event.set() return left_to_sell = amount_to_sell profit = 0 for offer in chosen_offers: cityname, username, amount, price, dist, destination_city_id = offer cityname = cityname.strip() amount = amount.replace(',', '').replace('.', '') amount = int(amount) price = int(price) sell = min(amount, left_to_sell) left_to_sell -= sell profit += sell * price print( _('\nSell {} of {} for a total of {}? [Y/n]').format( addThousandSeparator(amount_to_sell), materials_names[resource_type], addThousandSeparator(profit))) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return set_child_mode(session) event.set() info = _('\nI sell {} of {} in {}\n').format( addThousandSeparator(amount_to_sell), materials_names[resource_type], city_to_buy_from['name']) setInfoSignal(session, info) try: do_it1(session, amount_to_sell, chosen_offers, resource_type, city_to_buy_from) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def sendResources(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: routes = [] while True: banner() print(_('Origin city:')) try: cityO = chooseCity(session) except KeyboardInterrupt: if routes: print(_('Send shipment? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'n': break event.set() return banner() print(_('Destination city')) cityD = chooseCity(session, foreign=True) idIsland = cityD['islandId'] if cityO['id'] == cityD['id']: continue resources_left = cityO['recursos'] for route in routes: (origin_city, destination_city, __, *toSend) = route if origin_city['id'] == cityO['id']: for i in range(len(materials_names)): resources_left[i] -= toSend[i] # the destination city might be from another player if cityD['propia'] and destination_city['id'] == cityD['id']: for i in range(len(materials_names)): cityD['freeSpaceForResources'][i] -= toSend[i] banner() # the destination city might be from another player if cityD['propia']: msg = '' for i in range(len(materials_names)): if resources_left[i] > cityD['freeSpaceForResources'][i]: msg += '{} more {}\n'.format( addThousandSeparator( cityD['freeSpaceForResources'][i]), materials_names[i].lower()) if len(msg) > 0: print(_('You can store just:\n{}').format(msg)) print(_('Available:')) for i in range(len(materials_names)): print('{}:{} '.format(materials_names[i], addThousandSeparator(resources_left[i])), end='') print('') print(_('Send:')) try: max_name = max([len(material) for material in materials_names]) send = [] for i in range(len(materials_names)): material_name = materials_names[i] pad = ' ' * (max_name - len(material_name)) val = askForValue(_('{}{}:'.format(pad, material_name)), resources_left[i]) send.append(val) except KeyboardInterrupt: continue if sum(send) == 0: continue banner() print( _('About to send from {} to {}').format( cityO['cityName'], cityD['cityName'])) for i in range(len(materials_names)): if send[i] > 0: print('{}:{} '.format(materials_names[i], addThousandSeparator(send[i])), end='') print('') print(_('Proceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'n': route = (cityO, cityD, idIsland, *send) routes.append(route) print(_('Create another shipment? [y/N]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'y': break except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nSend resources\n') setInfoSignal(session, info) try: executeRoutes(session, routes) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def donationBot(session, event, stdin_fd, predetermined_input): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int predetermined_input : multiprocessing.managers.SyncManager.list """ sys.stdin = os.fdopen(stdin_fd) config.predetermined_input = predetermined_input try: banner() (cities_ids, cities) = getIdsOfCities(session) cities_dict = {} initials = [material_name[0] for material_name in materials_names] print( 'Enter how often you want to donate in minutes. (min = 1, default = 1 day)' ) waiting_time = read(min=1, digit=True, default=1 * 24 * 60) print( 'Enter a maximum additional random waiting time between donations in minutes. (min = 0, default = 1 hour)' ) max_random_waiting_time = read(min=0, digit=True, default=1 * 60) for cityId in cities_ids: tradegood = cities[cityId]['tradegood'] initial = initials[int(tradegood)] print( _('In {} ({}), Do you wish to donate to the forest, to the trading good or neither? [f/t/n]' ).format(cities[cityId]['name'], initial)) f = _('f') t = _('t') n = _('n') rta = read(values=[f, f.upper(), t, t.upper(), n, n.upper()]) if rta.lower() == f: donation_type = 'resource' elif rta.lower() == t: donation_type = 'tradegood' else: donation_type = None percentage = None if donation_type is not None: print( _('What is the maximum percentage of your storage capacity that you whish to keep occupied? (the resources that exceed it, will be donated) (default: 80%)' )) percentage = read(min=0, max=100, empty=True) if percentage == '': percentage = 80 elif percentage == 100: # if the user is ok with the storage beeing totally full, don't donate at all donation_type = None cities_dict[cityId] = { 'donation_type': donation_type, 'percentage': percentage } print(_('I will donate every {} minutes.'.format(waiting_time))) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI donate every {} minutes\n'.format(waiting_time)) setInfoSignal(session, info) try: do_it(session, cities_ids, cities_dict, waiting_time, max_random_waiting_time) except Exception as e: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def searchForIslandSpaces(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) try: if checkTelegramData(session) is False: event.set() return banner() print( 'Do you want to search for spaces on your islands or a specific set of islands?' ) print('(0) Exit') print('(1) Search all islands I have colonised') print('(2) Search a specific set of islands') choice = read(min=0, max=2) islandList = [] if choice == 0: event.set() return elif choice == 2: banner() print( 'Insert the coordinates of each island you want searched like so: X1:Y1, X2:Y2, X3:Y3...' ) coords_string = read() coords_string = coords_string.replace(' ', '') coords = coords_string.split(',') for coord in coords: coord = '&xcoord=' + coord coord = coord.replace(':', '&ycoord=') html = session.get('view=island' + coord) island = getIsland(html) islandList.append(island['id']) else: pass banner() print( 'How frequently should the islands be searched in minutes (minimum is 3)?' ) time = read(min=3, digit=True) banner() print(_('I will search for changes in the selected islands')) enter() except KeyboardInterrupt: event.set() return set_child_mode(session) event.set() info = _('\nI search for new spaces each hour\n') setInfoSignal(session, info) try: do_it(session, islandList, time) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(session, msg) finally: session.logout()
def activateMiracle(s, e, fd): sys.stdin = os.fdopen(fd) try: banner() islands = obtainMiraclesAvailable(s) if islands == []: print(_('There are no miracles available.')) enter() e.set() return island = chooseIsland(islands) if island is None: e.set() return if island['available']: print( _('\nThe miracle {} will be activated').format( island['wonderName'])) print(_('Proceed? [Y/n]')) r = read(values=['y', 'Y', 'n', 'N', '']) if r.lower() == 'n': e.set() return rta = activateMiracleImpl(s, island) if rta[1][1][0] == 'error': print( _('The miracle {} could not be activated.').format( island['wonderName'])) enter() e.set() return data = rta[2][1] for elem in data: if 'countdown' in data[elem]: enddate = data[elem]['countdown']['enddate'] currentdate = data[elem]['countdown']['currentdate'] break wait_time = enddate - currentdate print( _('The miracle {} was activated.').format( island['wonderName'])) enter() banner() while True: print( _('Do you wish to activate it again when it is finished? [y/N]' )) r = read(values=['y', 'Y', 'n', 'N', '']) if r.lower() != 'y': e.set() return iterations = read(msg=_('How many times?: '), digit=True, min=0) if iterations == 0: e.set() return duration = wait_time * iterations print( _('It will finish in:{}').format( daysHoursMinutes(duration))) print(_('Proceed? [Y/n]')) r = read(values=['y', 'Y', 'n', 'N', '']) if r.lower() == 'n': banner() continue break else: print( _('\nThe miracle {} will be activated in {}').format( island['wonderName'], daysHoursMinutes(island['available_in']))) print(_('Proceed? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': e.set() return wait_time = island['available_in'] iterations = 1 print(_('\nThe mirable will be activated.')) enter() banner() while True: print( _('Do you wish to activate it again when it is finished? [y/N]' )) r = read(values=['y', 'Y', 'n', 'N', '']) again = r.lower() == 'y' if again is True: try: iterations = read(msg=_('How many times?: '), digit=True, min=0) except KeyboardInterrupt: iterations = 1 break if iterations == 0: iterations = 1 break iterations += 1 duration = wait_time * iterations print( _('It is not possible to calculate the time of finalization. (at least: {})' ).format(daysHoursMinutes(duration))) print(_('Proceed? [Y/n]')) try: r = read(values=['y', 'Y', 'n', 'N', '']) except KeyboardInterrupt: iterations = 1 break if r.lower() == 'n': iterations = 1 banner() continue break except KeyboardInterrupt: e.set() return set_child_mode(s) e.set() info = _('\nI activate the miracle {} {:d} times\n').format( island['wonderName'], iterations) setInfoSignal(s, info) try: do_it(s, island, iterations) except: msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc()) sendToBot(s, msg) finally: s.logout()