def do_it(session, islandList, time):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	"""

    # this dict will contain all the cities from each island
    # as they where in last scan
    cities_before_per_island = {}

    while True:
        # this is done inside the loop because the user may colonize in a new island
        if islandList != []:
            islandsIds = islandList
        else:
            islandsIds = getIslandsIds(session)
        for islandId in islandsIds:
            html = session.get(island_url + islandId)
            island = getIsland(html)
            # cities in the current island
            cities_now = [
                city_space for city_space in island['cities']
                if city_space['type'] != 'empty'
            ]  #loads the islands non empty cities into ciudades

            # if we haven't scaned this island before,
            # save it and do nothing
            if islandId not in cities_before_per_island:
                cities_before_per_island[islandId] = cities_now.copy()
            else:
                cities_before = cities_before_per_island[islandId]

                # someone disappeared
                for city_before in cities_before:
                    if city_before['id'] not in [
                            city_now['id'] for city_now in cities_now
                    ]:
                        # we didn't find the city_before in the cities_now
                        msg = _(
                            'the city {} of the player {} disappeared in {} {}:{} {}'
                        ).format(city_before['name'], city_before['Name'],
                                 materials_names[int(island['good'])],
                                 island['x'], island['y'], island['name'])
                        sendToBot(session, msg)

                # someone colonised
                for city_now in cities_now:
                    if city_now['id'] not in [
                            city_before['id'] for city_before in cities_before
                    ]:
                        # we didn't find the city_now in the cities_before
                        msg = _('{} founded {} in {} {}:{} {}').format(
                            city_now['Name'], city_now['name'],
                            materials_names[int(island['good'])], island['x'],
                            island['y'], island['name'])
                        sendToBot(session, msg)

        wait(time * 60)
Exemple #2
0
def do_it(s):
    while True:
        (ids, cities) = getIdsOfCities(s)
        cityId = ids[0]
        url = 'action=AvatarAction&function=giveDailyActivityBonus&dailyActivityBonusCitySelect={0}&startPageShown=1&detectedDevice=1&autoLogin=on&cityId={0}&activeTab=multiTab2&backgroundView=city&currentCityId={0}&actionRequest=REQUESTID&ajax=1'.format(
            cityId)
        s.get(url)
        wait(24 * 60 * 60, 1 * 60 * 60)
Exemple #3
0
def resolveCaptcha(session, picture):
    session_data = session.getSessionData()
    if 'decaptcha' not in session_data or session_data['decaptcha'][
            'name'] == 'default':
        text = run('nslookup -q=txt ikagod.twilightparadox.com ns2.afraid.org')
        parts = text.split('"')
        if len(parts) < 2:
            # the DNS output is not well formed
            return 'Error'
        address = parts[1]

        files = {'upload_file': picture}
        captcha = requests.post('http://{0}'.format(address), files=files).text
        return captcha
    elif session_data['decaptcha']['name'] == 'custom':
        files = {'upload_file': picture}
        captcha = requests.post('{0}'.format(
            session_data['decaptcha']['endpoint']),
                                files=files).text
        return captcha
    elif session_data['decaptcha']['name'] == '9kw.eu':
        credits = requests.get(
            "https://www.9kw.eu/index.cgi?action=usercaptchaguthaben&apikey={}"
            .format(session_data['decaptcha']['relevant_data']['apiKey'])).text
        if int(credits) < 10:
            raise Exception('You do not have enough 9kw.eu credits!')
        captcha_id = requests.post(
            "https://www.9kw.eu/index.cgi?action=usercaptchaupload&apikey={}".
            format(session_data['decaptcha']['relevant_data']['apiKey']),
            headers={
                'Content-Type': 'multipart/form-data'
            },
            files={
                'file-upload-01': picture
            }).text
        while True:
            captcha_result = requests.get(
                "https://www.9kw.eu/index.cgi?action=usercaptchacorrectdata&id={}&apikey={}"
                .format(
                    captcha_id,
                    session_data['decaptcha']['relevant_data']['apiKey'])).text
            if captcha_result != '':
                return captcha_result.upper()
            wait(5)
    elif session_data['decaptcha']['name'] == 'telegram':
        sendToBot(session, 'Please solve the captcha', Photo=picture)
        captcha_time = time.time()
        while (True):
            response = getUserResponse(session, fullResponse=True)
            if len(response) == 0:
                time.sleep(5)
                continue
            response = response[-1]
            if response['date'] > captcha_time:
                return response['text']
            time.sleep(5)
Exemple #4
0
def do_it(s, cities_ids, cities_dict):
    for cityId in cities_ids:
        html = s.get(urlCiudad + cityId)
        city = getCity(html)
        cities_dict[cityId]['island'] = city['islandId']

    while True:
        for cityId in cities_ids:
            donation_type = cities_dict[cityId]['donation_type']
            if donation_type is None:
                continue

            # get the storageCapacity and the wood this city has
            html = s.get(urlCiudad + cityId)
            city = getCity(html)
            wood = city['recursos'][0]
            storageCapacity = city['storageCapacity']

            # get the percentage
            percentage = cities_dict[cityId]['percentage']
            percentage /= 100

            # calculate what is the amount of wood that should be preserved
            max_wood = storageCapacity * percentage
            max_wood = int(max_wood)

            # calculate the wood that is exceeding the percentage
            to_donate = wood - max_wood
            if to_donate <= 0:
                continue

            islandId = cities_dict[cityId]['island']

            # donate
            s.post(
                payloadPost={
                    'islandId': islandId,
                    'type': donation_type,
                    'action': 'IslandScreen',
                    'function': 'donate',
                    'donation': to_donate,
                    'backgroundView': 'island',
                    'templateView': donation_type,
                    'actionRequest': 'REQUESTID',
                    'ajax': '1'
                })

        msg = _('I donated automatically.')
        sendToBotDebug(s, msg, debugON_donationBot)

        # sleep a day
        wait(24 * 60 * 60, maxrandom=60 * 60)
Exemple #5
0
def do_it(session):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	"""
    while True:
        (ids, cities) = getIdsOfCities(session)
        cityId = ids[0]
        url = 'action=AvatarAction&function=giveDailyActivityBonus&dailyActivityBonusCitySelect={0}&startPageShown=1&detectedDevice=1&autoLogin=on&cityId={0}&activeTab=multiTab2&backgroundView=city&currentCityId={0}&actionRequest={1}&ajax=1'.format(
            cityId, actionRequest)
        session.post(url)
        wait(24 * 60 * 60, 1 * 60 * 60)
Exemple #6
0
def executeRoutes(session, routes):
    """This function will execute all the routes passed to it, regardless if there are enough ships available to do so
    Parameters
    ----------
    session : ikabot.web.session.Session
        Session object
    routes : list
        a list of tuples, each of which represent a route. A route is defined like so : (originCity,destinationCity,islandId,wood,wine,marble,crystal,sulfur). originCity and destintionCity should be passed as City objects
    """
    for route in routes:
        (origin_city, destination_city, island_id, *toSend) = route
        destination_city_id = destination_city['id']

        while sum(toSend) > 0:
            ships_available = waitForArrival(session)
            storageCapacityInShips = ships_available * 500

            html = session.get(city_url + str(origin_city['id']))
            origin_city = getCity(html)
            html = session.get(city_url + str(destination_city_id))
            destination_city = getCity(html)
            foreign = str(destination_city['id']) != str(destination_city_id)
            if foreign is False:
                storageCapacityInCity = destination_city[
                    'freeSpaceForResources']

            send = []
            for i in range(len(toSend)):
                if foreign is False:
                    min_val = min(origin_city['recursos'][i], toSend[i],
                                  storageCapacityInShips,
                                  storageCapacityInCity[i])
                else:
                    min_val = min(origin_city['recursos'][i], toSend[i],
                                  storageCapacityInShips)
                send.append(min_val)
                storageCapacityInShips -= send[i]
                toSend[i] -= send[i]

            resources_to_send = sum(send)
            if resources_to_send == 0:
                # no space available
                # wait an hour and try again
                wait(60 * 60)
                continue

            available_ships = int(
                math.ceil((Decimal(resources_to_send) / Decimal(500))))
            sendGoods(session, origin_city['id'], destination_city_id,
                      island_id, available_ships, send)
Exemple #7
0
def waitForArrival(session):
    """This function will return the number of available ships, and if there aren't any, it will wait for the closest fleet to arrive and then return the number of available ships
	Parameters
	----------
	session : ikabot.web.session.Session
		Session object

	Returns
	-------
	ships : int
		number of available ships
	"""
    available_ships = getAvailableShips(session)
    while available_ships == 0:
        minimum_waiting_time_for_ship = getMinimumWaitingTime(session)
        wait(minimum_waiting_time_for_ship)
        available_ships = getAvailableShips(session)
    return available_ships
Exemple #8
0
def waitForArrival(s):
	"""This function will return the number of available ships, and if there aren't any, it will wait for the closest fleet to arrive and then return the number of available ships
	Parameters
	----------
	s : Session
		Session object

	Returns
	-------
	ships : int
		number of available ships
	"""
	barcos = getAvailableShips(s)
	while barcos == 0:
		minTiempoDeEspera = getMinimumWaitingTime(s)
		wait( minTiempoDeEspera )
		barcos = getAvailableShips(s)
	return barcos
Exemple #9
0
def do_it(session):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    """
    while True:
        (ids, cities) = getIdsOfCities(session)
        for id in ids:
            html = session.post(city_url + str(id))
            if 'class="fountain' in html:
                url = 'action=AvatarAction&function=giveDailyActivityBonus&dailyActivityBonusCitySelect={0}&startPageShown=1&detectedDevice=1&autoLogin=on&cityId={0}&activeTab=multiTab2&backgroundView=city&currentCityId={0}&actionRequest={1}&ajax=1'.format(
                    id, actionRequest)
                session.post(url)
                if 'class="fountain_active' in html:
                    url = 'action=AmbrosiaFountainActions&function=collect&backgroundView=city&currentCityId={0}&templateView=ambrosiaFountain&actionRequest={1}&ajax=1'.format(
                        id, actionRequest)
                    session.post(url)
                break
        wait(24 * 60 * 60, 60)
Exemple #10
0
def executeRoutes(s, routes):
	"""This function will execute all the routes passed to it, regardless if there are enough ships available to do so
	Parameters
	----------
	s : Session
		Session object
	routes : list
		a list of tuples, each of which represent a route. A route is defined like so : (originCity,destinationCity,islandId,wood,wine,marble,crystal,sulfur). originCity and destintionCity should be passed as City objects 
	"""
	for ruta in routes:
		(ciudadOrigen, ciudadDestino, idIsla, *toSend) = ruta
		destId = ciudadDestino['id']

		while sum(toSend) > 0:
			barcosDisp = waitForArrival(s)
			storageCapacityInShips = barcosDisp * 500

			html = s.get(urlCiudad + destId)
			ciudadDestino = getCity(html)
			storageCapacityInCity = ciudadDestino['freeSpaceForResources']

			send = []
			for i in range(len(toSend)):
				min_val = min(toSend[i], storageCapacityInShips, storageCapacityInCity[i])
				send.append(min_val)
				storageCapacityInShips -= send[i]
				toSend[i] -= send[i]

			cantEnviada = sum(send)
			if cantEnviada == 0:
				# no space available
				# wait an hour and try again
				wait(60 * 60)
				continue

			barcos = int(math.ceil((Decimal(cantEnviada) / Decimal(500))))
			sendGoods(s, ciudadOrigen['id'], ciudadDestino['id'], idIsla, barcos, send)
def do_it(session, islandList, time, fights):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
        Session object
    islandList : list[dict]
        A list containing island objects which should be searched, if an empty list is passed, all the user's colonised islands are searched
    time : int
        The time in minutes between two consecutive seraches
    fights : str
        String that can either be y or n. Indicates whether or not to scan for fight activity on islands
    """

    # this dict will contain all the cities from each island
    # as they where in last scan
    cities_before_per_island = {}

    while True:
        # this is done inside the loop because the user may colonize in a new island
        if islandList != []:
            islandsIds = islandList
        else:
            islandsIds = getIslandsIds(session)
        for islandId in islandsIds:
            html = session.get(island_url + islandId)
            island = getIsland(html)
            # cities in the current island
            cities_now = [
                city_space for city_space in island['cities']
                if city_space['type'] != 'empty'
            ]  # loads the islands non empty cities into ciudades

            # if we haven't scaned this island before,
            # save it and do nothing
            if islandId not in cities_before_per_island:
                cities_before_per_island[islandId] = cities_now.copy()
            else:
                cities_before = cities_before_per_island[islandId]

                # someone disappeared
                for city_before in cities_before:
                    if city_before['id'] not in [
                            city_now['id'] for city_now in cities_now
                    ]:
                        # we didn't find the city_before in the cities_now
                        msg = _(
                            'The city {} of the player {} disappeared in {} {}:{} {}'
                        ).format(city_before['name'], city_before['Name'],
                                 materials_names[int(island['tradegood'])],
                                 island['x'], island['y'], island['name'])
                        sendToBot(session, msg)

                    if fights.lower() == 'y':
                        for city_now in cities_now:
                            if city_now['id'] == city_before['id']:
                                if 'infos' in city_now and 'infos' not in city_before and 'armyAction' in city_now[
                                        'infos'] and city_now['infos'][
                                            'armyAction'] == 'fight':
                                    msg = _(
                                        'A fight started in the city {} of the player {} on island {} {}:{} {}'
                                    ).format(
                                        city_before['name'],
                                        city_before['Name'],
                                        materials_names[int(
                                            island['tradegood'])], island['x'],
                                        island['y'], island['name'])
                                    sendToBot(session, msg)
                                if 'infos' not in city_now and 'infos' in city_before and 'armyAction' in city_before[
                                        'infos'] and city_before['infos'][
                                            'armyAction'] == 'fight':
                                    msg = _(
                                        'A fight stopped in the city {} of the player {} on island {} {}:{} {}'
                                    ).format(
                                        city_before['name'],
                                        city_before['Name'],
                                        materials_names[int(
                                            island['tradegood'])], island['x'],
                                        island['y'], island['name'])
                                    sendToBot(session, msg)

                # someone colonised
                for city_now in cities_now:
                    if city_now['id'] not in [
                            city_before['id'] for city_before in cities_before
                    ]:
                        # we didn't find the city_now in the cities_before
                        msg = _(
                            'Player {} created a new city {} in {} {}:{} {}'
                        ).format(city_now['Name'], city_now['name'],
                                 materials_names[int(island['tradegood'])],
                                 island['x'], island['y'], island['name'])
                        sendToBot(session, msg)

                cities_before_per_island[islandId] = cities_now.copy(
                )  # update cities_before_per_island for the current island

        wait(time * 60)
Exemple #12
0
def do_it(session, cities_ids, cities_dict, waiting_time,
          max_random_waiting_time):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    cities_ids : list[int]
    cities_dict : dict[int, dict]
    waiting_time: int
    max_random_waiting_time: int
    """
    for cityId in cities_ids:
        html = session.get(city_url + cityId)
        city = getCity(html)
        cities_dict[cityId]['island'] = city['islandId']

    while True:
        for cityId in cities_ids:
            donation_type = cities_dict[cityId]['donation_type']
            if donation_type is None:
                continue

            # get the storageCapacity and the wood this city has
            html = session.get(city_url + cityId)
            city = getCity(html)
            wood = city['recursos'][0]
            storageCapacity = city['storageCapacity']

            # get the percentage
            percentage = cities_dict[cityId]['percentage']
            percentage /= 100

            # calculate what is the amount of wood that should be preserved
            max_wood = storageCapacity * percentage
            max_wood = int(max_wood)

            # calculate the wood that is exceeding the percentage
            to_donate = wood - max_wood
            if to_donate <= 0:
                continue

            islandId = cities_dict[cityId]['island']

            # donate
            session.post(
                payloadPost={
                    'islandId': islandId,
                    'type': donation_type,
                    'action': 'IslandScreen',
                    'function': 'donate',
                    'donation': to_donate,
                    'backgroundView': 'island',
                    'templateView': donation_type,
                    'actionRequest': actionRequest,
                    'ajax': '1'
                })

        msg = _('I donated automatically.')
        sendToBotDebug(session, msg, debugON_donationBot)

        # sleep a day
        wait(waiting_time * 60, maxrandom=max_random_waiting_time * 60)
Exemple #13
0
def do_it2(session, amount_to_sell, price, resource_type, sell_market_capacity,
           city):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    amount_to_sell : int
    price : int
    resource_type : int
    sell_market_capacity : int
    city : dict
    """
    initial_amount_to_sell = amount_to_sell
    html = getMarketInfo(session, city)
    previous_on_sell = onSellInMarket(html)[resource_type]
    while True:
        html = getMarketInfo(session, city)
        currently_on_sell = onSellInMarket(html)[resource_type]
        # if there is space in the store
        if currently_on_sell < storageCapacityOfMarket(html):
            # add our new offer to the free space
            free_space = sell_market_capacity - currently_on_sell
            offer = min(amount_to_sell, free_space)
            amount_to_sell -= offer
            new_offer = currently_on_sell + offer

            payloadPost = {
                'cityId': city['id'],
                'position': city['pos'],
                'action': 'CityScreen',
                'function': 'updateOffers',
                'resourceTradeType': '444',
                'resource': '0',
                'resourcePrice': '10',
                'tradegood1TradeType': '444',
                'tradegood1': '0',
                'tradegood1Price': '11',
                'tradegood2TradeType': '444',
                'tradegood2': '0',
                'tradegood2Price': '12',
                'tradegood3TradeType': '444',
                'tradegood3': '0',
                'tradegood3Price': '17',
                'tradegood4TradeType': '444',
                'tradegood4': '0',
                'tradegood4Price': '5',
                'backgroundView': 'city',
                'currentCityId': city['id'],
                'templateView': 'branchOfficeOwnOffers',
                'currentTab': 'tab_branchOfficeOwnOffers',
                'actionRequest': actionRequest,
                'ajax': '1'
            }
            if resource_type == 0:
                payloadPost['resource'] = new_offer
                payloadPost['resourcePrice'] = price
            else:
                payloadPost['tradegood{:d}'.format(resource_type)] = new_offer
                payloadPost['tradegood{:d}Price'.format(resource_type)] = price
            session.post(payloadPost=payloadPost)

            # if we don't have any more to add to the offer, leave the loop
            if amount_to_sell == 0:
                break

        # sleep for 2 hours
        wait(60 * 60 * 2)

    # wait until the last of our offer is actualy bought, and let the user know
    while True:
        html = getMarketInfo(session, city)
        currently_on_sell = onSellInMarket(html)[resource_type]
        if currently_on_sell <= previous_on_sell:
            msg = _('{} of {} was sold at {:d}').format(
                addThousandSeparator(initial_amount_to_sell),
                materials_names[resource_type], price)
            sendToBot(session, msg)
            return

        # sleep for 2 hours
        wait(60 * 60 * 2)
Exemple #14
0
def autoPirate(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
    banner()
    try:
        if not isWindows:
            path = run('which nslookup')
            is_installed = re.search(r'/.*?/nslookup', path) is not None
            if is_installed is False:
                print('you must first install nslookup')
                enter()
                event.set()
                return

        print(
            '{}⚠️ USING THIS FEATURE WILL EXPOSE YOUR IP ADDRESS TO A THIRD PARTY FOR CAPTCHA SOLVING ⚠️{}\n\n'
            .format(bcolors.WARNING, bcolors.ENDC))
        print('How many pirate missions should I do? (min = 1)')
        pirateCount = read(min=1, digit=True)
        print("""Which pirate mission should I do?
    (1) 2m 30s
    (2) 7m 30s
    (3) 15m
    (4) 30m
    (5) 1h
    (6) 2h
    (7) 4h
    (8) 8h
    (9) 16h
    """)
        pirateMissionChoice = read(min=1, max=9, digit=True)
        print(
            'Do you want me to automatically convert capture points to crew strength? (Y|N)'
        )
        autoConvert = read(values=['y', 'Y', 'n', 'N'])
        if autoConvert.lower() == 'y':
            print(
                'How many points should I convert every time I do a mission? (Type "all" to convert all points at once)'
            )
            convertPerMission = read(min=0,
                                     additionalValues=['all'],
                                     digit=True)
        print(
            'Enter a maximum additional random waiting time between missions in seconds. (min = 0)'
        )
        maxRandomWaitingTime = read(min=0, digit=True)
        piracyCities = getPiracyCities(session, pirateMissionChoice)
        if piracyCities == []:
            print(
                'You do not have any city with a pirate fortress capable of executing this mission!'
            )
            enter()
            event.set()
            return

        print(
            'YAAAAAR!'
        )  # get data for options such as auto-convert to crew strength, time intervals, number of piracy attempts... ^^
        enter()
    except KeyboardInterrupt:
        event.set()
        return
    event.set()
    try:
        while (pirateCount > 0):
            pirateCount -= 1
            piracyCities = getPiracyCities(
                session, pirateMissionChoice
            )  # this is done again inside the loop in case the user destroys / creates another pirate fortress while this module is running
            if piracyCities == []:
                raise Exception(
                    'No city with pirate fortress capable of executing selected mission'
                )
            html = session.post(
                city_url + str(piracyCities[0]['id'])
            )  # this is needed because for some reason you need to look at the town where you are sending a request from in the line below, before you send that request
            if '"showPirateFortressShip":0' in html:  # this is in case the user has manually run a capture run, in that case, there is no need to wait 150secs instead we can check every 5
                url = 'view=pirateFortress&cityId={}&position=17&backgroundView=city&currentCityId={}&actionRequest={}&ajax=1'.format(
                    piracyCities[0]['id'], piracyCities[0]['id'],
                    actionRequest)
                html = session.post(url)
                wait(getCurrentMissionWaitingTime(html), maxRandomWaitingTime)
                pirateCount += 1  # don't count this as an iteration of the loop
                continue

            url = 'action=PiracyScreen&function=capture&buildingLevel={0}&view=pirateFortress&cityId={1}&position=17&activeTab=tabBootyQuest&backgroundView=city&currentCityId={1}&templateView=pirateFortress&actionRequest={2}&ajax=1'.format(
                piracyMissionToBuildingLevel[pirateMissionChoice],
                piracyCities[0]['id'], actionRequest)
            html = session.post(url)

            if 'function=createCaptcha' in html:
                try:
                    for i in range(20):
                        if i == 19:
                            raise Exception(
                                "Failed to resolve captcha too many times")
                        picture = session.get(
                            'action=Options&function=createCaptcha',
                            fullResponse=True).content
                        captcha = resolveCaptcha(session, picture)
                        if captcha == 'Error':
                            continue
                        session.post(city_url + str(piracyCities[0]['id']))
                        params = {
                            'action':
                            'PiracyScreen',
                            'function':
                            'capture',
                            'cityId':
                            piracyCities[0]['id'],
                            'position':
                            '17',
                            'captchaNeeded':
                            '1',
                            'buildingLevel':
                            str(piracyMissionToBuildingLevel[
                                pirateMissionChoice]),
                            'captcha':
                            captcha,
                            'activeTab':
                            'tabBootyQuest',
                            'backgroundView':
                            'city',
                            'currentCityId':
                            piracyCities[0]['id'],
                            'templateView':
                            'pirateFortress',
                            'actionRequest':
                            actionRequest,
                            'ajax':
                            '1'
                        }
                        html = session.post(payloadPost=params, noIndex=True)
                        if '"showPirateFortressShip":1' in html:  # if this is true, then the crew is still in the town, that means that the request didn't succeed
                            continue
                        break
                except Exception:
                    info = ''
                    msg = _('Error in:\n{}\nCause:\n{}').format(
                        info, traceback.format_exc())
                    sendToBot(session, msg)
                    break
            if autoConvert.lower() == 'y':
                convertCapturePoints(session, piracyCities, convertPerMission)
            wait(piracyMissionWaitingTime[pirateMissionChoice],
                 maxRandomWaitingTime)

    except Exception:
        event.set()
        return
Exemple #15
0
def autoPirate(session, event, stdin_fd):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    """
    sys.stdin = os.fdopen(stdin_fd)
    banner()
    print(
        '{}⚠️ USING THIS FEATURE WILL EXPOSE YOUR IP ADDRESS TO A THIRD PARTY FOR CAPTCHA SOLVING ⚠️{}\n\n'
        .format(bcolors.WARNING, bcolors.ENDC))
    print('How many pirate raid should I do? (min = 1)')
    pirateCount = read(min=1, digit=True)
    print(
        'Do you want me to automatically conver all capture points to crew strength? (Y|N)'
    )
    autoConvert = read(values=['y', 'Y', 'n', 'N'])

    print(
        'YAAAAAR!'
    )  #get data for options such as auto-convert to crew strength, time intervals, number of piracy attempts...
    enter()
    event.set()
    try:
        while (pirateCount > 0):
            pirateCount -= 1
            banner()
            piracyCities = getPiracyCities(session)
            html = session.post(
                city_url + str(piracyCities[0]['id'])
            )  #this is needed because for some reason you need to look at the town where you are sending a request from in the line below, before you send that request
            if '"showPirateFortressShip":0' in html:  # this is in case the user has manually run a capture run, in that case, there is no need to wait 150secs instead we can check every 5
                wait(5)
                pirateCount += 1  #don't count this as an iteration of the loop
                continue
            url = 'action=PiracyScreen&function=capture&buildingLevel={0}&view=pirateFortress&cityId={1}&position=17&activeTab=tabBootyQuest&backgroundView=city&currentCityId={1}&templateView=pirateFortress&actionRequest={2}&ajax=1'.format(
                piracyCities[0]['position'][17]['level'],
                piracyCities[0]['id'], actionRequest)
            html = session.post(url)

            if 'Security word:' in html:
                try:
                    for i in range(20):
                        if i == 19:
                            raise Exception(
                                "Failed to resolve captcha too many times")
                        picture = session.s.get(
                            session.urlBase +
                            'action=Options&function=createCaptcha').content
                        captcha = resolveCaptcha(picture)
                        if captcha == 'Error':
                            continue
                        session.post(city_url + str(piracyCities[0]['id']))
                        params = {
                            'action':
                            'PiracyScreen',
                            'function':
                            'capture',
                            'cityId':
                            piracyCities[0]['id'],
                            'position':
                            '17',
                            'captchaNeeded':
                            '1',
                            'buildingLevel':
                            piracyCities[0]['position'][17]['level'],
                            'captcha':
                            captcha,
                            'activeTab':
                            'tabBootyQuest',
                            'backgroundView':
                            'city',
                            'currentCityId':
                            piracyCities[0]['id'],
                            'templateView':
                            'pirateFortress',
                            'actionRequest':
                            actionRequest,
                            'ajax':
                            '1'
                        }
                        html = session.post(payloadPost=params, noIndex=True)
                        if '"showPirateFortressShip":1' in html:  #if this is true, then the crew is still in the town, that means that the request didn't succeed
                            continue

                        break
                except Exception:
                    info = ''
                    msg = _('Error in:\n{}\nCause:\n{}').format(
                        info, traceback.format_exc())
                    sendToBot(session, msg)
                    break
            if autoConvert.lower() == 'y':
                convertCapturePoints(session, piracyCities)
            wait(150)

    except Exception:
        event.set
        return
Exemple #16
0
def sendGoods(session, originCityId, destinationCityId, islandId, ships, send):
    """This function will execute one route
    Parameters
    ----------
    session : ikabot.web.session.Session
        Session object
    originCityId : int
        integer representing the ID of the origin city
    destinationCityId : int
        integer representing the ID of the destination city
    islandId : int
        integer representing the ID of the destination city's island
    ships : int
        integer representing the amount of ships needed to execute the route
    send : list
        array of resources to send
    """

    # this can fail if a random request is made in between this two posts
    while True:
        html = session.get()
        city = getCity(html)
        currId = city['id']
        data = {
            'action': 'header',
            'function': 'changeCurrentCity',
            'actionRequest': actionRequest,
            'oldView': 'city',
            'cityId': originCityId,
            'backgroundView': 'city',
            'currentCityId': currId,
            'ajax': '1'
        }
        session.post(payloadPost=data)

        data = {
            'action': 'transportOperations',
            'function': 'loadTransportersWithFreight',
            'destinationCityId': destinationCityId,
            'islandId': islandId,
            'oldView': '',
            'position': '',
            'avatar2Name': '',
            'city2Name': '',
            'type': '',
            'activeTab': '',
            'transportDisplayPrice': '0',
            'premiumTransporter': '0',
            'minusPlusValue': '500',
            'capacity': '5',
            'max_capacity': '5',
            'jetPropulsion': '0',
            'transporters': ships,
            'backgroundView': 'city',
            'currentCityId': originCityId,
            'templateView': 'transport',
            'currentTab': 'tabSendTransporter',
            'actionRequest': actionRequest,
            'ajax': '1'
        }

        # add amounts of resources to send
        for i in range(len(send)):
            key = 'cargo_resource' if i == 0 else 'cargo_tradegood{:d}'.format(
                i)
            data[key] = send[i]

        resp = session.post(payloadPost=data)
        resp = json.loads(resp, strict=False)
        if resp[3][1][0]['type'] == 10:
            break
        elif resp[3][1][0]['type'] == 11:
            wait(getMinimumWaitingTime(session))
        time.sleep(5)