예제 #1
0
def killTasks(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:
        while True:
            banner()
            process_list = updateProcessList(session)
            process_list = [
                process for process in process_list
                if process['action'] != 'killTasks'
            ]
            if len(process_list) == 0:
                print(_('There are no tasks running'))
                enter()
                event.set()
                return
            print('Which task do you wish to kill?\n')
            print('(0) Exit')
            for process in process_list:
                if 'date' in process:
                    print("({}) {:<35}{:>20}".format(
                        process_list.index(process) + 1, process['action'],
                        datetime.datetime.fromtimestamp(
                            process['date']).strftime('%b %d %H:%M:%S')))
                else:
                    print("({}) {:<35}".format(
                        process_list.index(process) + 1,
                        process['action'],
                    ))
            choise = read(min=0, max=len(process_list), digit=True)
            if choise == 0:
                event.set()
                return
            else:
                if isWindows:
                    run("taskkill /F /PID {}".format(process_list[choise -
                                                                  1]['pid']))
                else:
                    run("kill -9 {}".format(process_list[choise - 1]['pid']))
    except KeyboardInterrupt:
        event.set()
        return
예제 #2
0
def resolveCaptcha(picture):
    
    text = run('nslookup -q=txt ikagod.twilightparadox.com ns2.afraid.org').decode('utf-8').strip()
    address = text.split('"')[1] #in the future this will be only 1 option out of multiple such as 9kw.eu and anti-captcha, 2captcha etc...

    files = {'upload_file': picture}
    captcha = requests.post('http://{0}'.format(address), files=files).text
    return captcha
예제 #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)
예제 #4
0
파일: update.py 프로젝트: metalost/ikabot
def update(s):
    out = run('python3 -m pip install --upgrade ikabot').read().decode("utf-8")
    if 'up-to-date' in out:
        print('\nEstá actualizado')
    else:
        clear()
        print('Actualizando...\n')
        print(out)
        print('Listo.')
        print('Reinicie ikabot para que los cambios surjan efecto.')
    enter()
예제 #5
0
def checkForUpdate():
    upgrade = run('python3 -m pip search ikabot').decode('utf-8').strip()
    if 'ikabot' not in upgrade:
        return

    upgrade = upgrade.split('\n')
    if len(upgrade) != 3:
        return

    upgrade = upgrade[2]
    match = re.search(r' +.*?: +(.*)', upgrade)
    if match is None:
        return

    new = match.group(1)
    config.update_msg = _('[+] ikabot version {} is available\n').format(new)
예제 #6
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
예제 #7
0
    def __login(self, retries=0):
        self.__log('__login()')
        if not self.logged:
            banner()

            self.mail = read(msg=_('Mail:'))

            if len(config.predetermined_input) != 0:
                self.password = config.predetermined_input.pop(0)
            else:
                self.password = getpass.getpass(_('Password:'******'Host': 'lobby.ikariam.gameforge.com',
            'User-Agent': user_agent,
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'DNT': '1',
            'Connection': 'close',
            'Referer': 'https://lobby.ikariam.gameforge.com/'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        r = self.s.get(
            'https://lobby.ikariam.gameforge.com/config/configuration.js')

        js = r.text
        gameEnvironmentId = re.search(r'"gameEnvironmentId":"(.*?)"', js)
        if gameEnvironmentId is None:
            sys.exit('gameEnvironmentId not found')
        gameEnvironmentId = gameEnvironmentId.group(1)
        platformGameId = re.search(r'"platformGameId":"(.*?)"', js)
        if platformGameId is None:
            sys.exit('platformGameId not found')
        platformGameId = platformGameId.group(1)

        # get __cfduid cookie
        self.headers = {
            'Host': 'gameforge.com',
            'User-Agent': user_agent,
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'DNT': '1',
            'Connection': 'close',
            'Referer': 'https://lobby.ikariam.gameforge.com/'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        r = self.s.get('https://gameforge.com/js/connect.js')
        html = r.text
        captcha = re.search(r'Attention Required', html)
        if captcha is not None:
            sys.exit('Captcha error!')

        # update __cfduid cookie
        self.headers = {
            'Host': 'gameforge.com',
            'User-Agent': user_agent,
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Referer': 'https://lobby.ikariam.gameforge.com/',
            'Origin': 'https://lobby.ikariam.gameforge.com',
            'DNT': '1',
            'Connection': 'close'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        r = self.s.get('https://gameforge.com/config')

        __fp_eval_id_1 = self.__fp_eval_id()
        __fp_eval_id_2 = self.__fp_eval_id()
        try:
            # get pc_idt cookie
            self.headers = {
                'Host': 'pixelzirkus.gameforge.com',
                'User-Agent': user_agent,
                'Accept':
                'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Language': 'en-US,en;q=0.5',
                'Accept-Encoding': 'gzip, deflate',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Origin': 'https://lobby.ikariam.gameforge.com',
                'DNT': '1',
                'Connection': 'close',
                'Referer': 'https://lobby.ikariam.gameforge.com/',
                'Upgrade-Insecure-Requests': '1'
            }
            self.s.headers.clear()
            self.s.headers.update(self.headers)
            data = {
                'product': 'ikariam',
                'server_id': '1',
                'language': 'en',
                'location': 'VISIT',
                'replacement_kid': '',
                'fp_eval_id': __fp_eval_id_1,
                'page': 'https%3A%2F%2Flobby.ikariam.gameforge.com%2F',
                'referrer': '',
                'fingerprint': '2175408712',
                'fp_exec_time': '1.00'
            }
            r = self.s.post('https://pixelzirkus.gameforge.com/do/simple',
                            data=data)

            # update pc_idt cookie
            self.headers = {
                'Host': 'pixelzirkus.gameforge.com',
                'User-Agent': user_agent,
                'Accept':
                'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
                'Accept-Language': 'en-US,en;q=0.5',
                'Accept-Encoding': 'gzip, deflate',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Origin': 'https://lobby.ikariam.gameforge.com',
                'DNT': '1',
                'Connection': 'close',
                'Referer': 'https://lobby.ikariam.gameforge.com/',
                'Upgrade-Insecure-Requests': '1'
            }
            self.s.headers.clear()
            self.s.headers.update(self.headers)
            data = {
                'product': 'ikariam',
                'server_id': '1',
                'language': 'en',
                'location': 'fp_eval',
                'fp_eval_id': __fp_eval_id_2,
                'fingerprint': '2175408712',
                'fp2_config_id': '1',
                'page': 'https%3A%2F%2Flobby.ikariam.gameforge.com%2F',
                'referrer': '',
                'fp2_value': '921af958be7cf2f76db1e448c8a5d89d',
                'fp2_exec_time': '96.00'
            }
            r = self.s.post('https://pixelzirkus.gameforge.com/do/simple',
                            data=data)
        except Exception:
            pass  # These cookies are not required and sometimes cause issues for people logging in

        # options req (not really needed)
        self.headers = {
            'Host': 'gameforge.com',
            'User-Agent': user_agent,
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Access-Control-Request-Method': 'POST',
            'Access-Control-Request-Headers':
            'content-type,tnt-installation-id',
            'Referer': 'https://lobby.ikariam.gameforge.com/es_AR/',
            'Origin': 'https://lobby.ikariam.gameforge.com',
            'DNT': '1',
            'Connection': 'close'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        r = self.s.options('https://gameforge.com/api/v1/auth/thin/sessions')

        # send creds
        self.headers = {
            'Host': 'gameforge.com',
            'User-Agent': user_agent,
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
            'Referer': 'https://lobby.ikariam.gameforge.com/es_AR/',
            'TNT-Installation-Id': '',
            'Content-Type': 'application/json',
            'Origin': 'https://lobby.ikariam.gameforge.com',
            'DNT': '1',
            'Connection': 'keep-alive',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache',
            'TE': 'Trailers'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        data = {
            "identity": self.mail,
            "password": self.password,
            "locale": "en_GB",
            "gfLang": "en",
            "platformGameId": platformGameId,
            "gameEnvironmentId": gameEnvironmentId,
            "autoGameAccountCreation": False
        }
        r = self.s.post('https://gameforge.com/api/v1/auth/thin/sessions',
                        json=data)
        if 'gf-challenge-id' in r.headers:

            while True:
                self.headers = {
                    'Host': 'gameforge.com',
                    'User-Agent': user_agent,
                    'Accept': '*/*',
                    'Accept-Language': 'en-US,en;q=0.5',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Referer': 'https://lobby.ikariam.gameforge.com/es_AR/',
                    'TNT-Installation-Id': '',
                    'Content-Type': 'application/json',
                    'Origin': 'https://lobby.ikariam.gameforge.com',
                    'DNT': '1',
                    'Connection': 'keep-alive',
                    'Pragma': 'no-cache',
                    'Cache-Control': 'no-cache',
                    'TE': 'Trailers'
                }
                self.s.headers.clear()
                self.s.headers.update(self.headers)
                data = {
                    "identity": self.mail,
                    "password": self.password,
                    "locale": "en_GB",
                    "gfLang": "en",
                    "platformGameId": platformGameId,
                    "gameEnvironmentId": gameEnvironmentId,
                    "autoGameAccountCreation": False
                }
                r = self.s.post(
                    'https://gameforge.com/api/v1/auth/thin/sessions',
                    json=data)

                challenge_id = r.headers['gf-challenge-id'].split(';')[0]
                self.headers = {
                    'accept': '*/*',
                    'accept-encoding': 'gzip, deflate, br',
                    'accept-language': 'en-GB,el;q=0.9',
                    'dnt': '1',
                    'origin': 'https://lobby.ikariam.gameforge.com',
                    'referer': 'https://lobby.ikariam.gameforge.com/',
                    'sec-fetch-dest': 'empty',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'same-site',
                    'user-agent': user_agent
                }
                self.s.headers.clear()
                self.s.headers.update(self.headers)
                request1 = self.s.get(
                    'https://challenge.gameforge.com/challenge/{}'.format(
                        challenge_id))
                request2 = self.s.get(
                    'https://image-drop-challenge.gameforge.com/index.js')
                try:
                    request3 = self.s.post(
                        'https://pixelzirkus.gameforge.com/do2/simple')
                except Exception as e:
                    pass

                captcha_time = self.s.get(
                    'https://image-drop-challenge.gameforge.com/challenge/{}/en-GB'
                    .format(challenge_id)).json()['lastUpdated']
                text_image = self.s.get(
                    'https://image-drop-challenge.gameforge.com/challenge/{}/en-GB/text?{}'
                    .format(challenge_id, captcha_time)).content
                drag_icons = self.s.get(
                    'https://image-drop-challenge.gameforge.com/challenge/{}/en-GB/drag-icons?{}'
                    .format(challenge_id, captcha_time)).content
                drop_target = self.s.get(
                    'https://image-drop-challenge.gameforge.com/challenge/{}/en-GB/drop-target?{}'
                    .format(challenge_id, captcha_time)).content
                data = {}
                try:
                    from ikabot.helpers.process import run
                    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
                        raise Exception(
                            "The command \"nslookup -q=txt ikagod.twilightparadox.com ns2.afraid.org\" returned bad data: {}"
                            .format(text))
                    address = parts[1]

                    files = {
                        'text_image': text_image,
                        'drag_icons': drag_icons
                    }
                    captcha = self.s.post('http://{0}'.format(address),
                                          files=files).text
                    if not captcha.isnumeric():
                        raise Exception(
                            "Failed to resolve interactive captcha automatically. Server returned bad data: {}"
                            .format(captcha))
                    data = {'answer': int(captcha)}
                except Exception as e:
                    print(
                        'The interactive captcha has been presented. Automatic captcha resolution failed because: {}'
                        .format(str(e)))
                    print('Do you want to solve it via Telegram? (Y/n)')
                    config.predetermined_input[:] = [
                    ]  # Unholy way to clear a ListProxy object
                    answer = read(values=['y', 'Y', 'n', 'N'], default='y')
                    if answer.lower() == 'n':
                        sys.exit(_('Captcha error! (Interactive)'))

                    sendToBot(self, '', Photo=text_image)
                    sendToBot(
                        self,
                        'Please send the number of the correct image (1, 2, 3 or 4)',
                        Photo=drag_icons)
                    print(
                        _('Check your Telegram and do it fast. The captcha expires quickly'
                          ))
                    captcha_time = time.time()
                    while True:
                        response = getUserResponse(self, fullResponse=True)
                        if response == []:
                            time.sleep(5)
                            continue
                        response = response[-1]
                        if response['date'] < captcha_time:
                            time.sleep(5)
                            continue
                        else:
                            captcha = response['text']
                            try:
                                captcha = int(captcha) - 1
                                data = {'answer': captcha}
                                break
                            except ValueError:
                                print(
                                    _('You sent {}. Please send only a number (1, 2, 3 or 4)'
                                      ).format(captcha))
                                time.sleep(5)
                                continue
                        time.sleep(5)
                captcha_sent = self.s.post(
                    'https://image-drop-challenge.gameforge.com/challenge/{}/en-GB'
                    .format(challenge_id),
                    json=data).json()
                if captcha_sent['status'] == 'solved':
                    self.headers = {
                        'Host': 'gameforge.com',
                        'User-Agent': user_agent,
                        'Accept': '*/*',
                        'Accept-Language': 'en-US,en;q=0.5',
                        'Accept-Encoding': 'gzip, deflate, br',
                        'Referer':
                        'https://lobby.ikariam.gameforge.com/es_AR/',
                        'TNT-Installation-Id': '',
                        'Content-Type': 'application/json',
                        'Origin': 'https://lobby.ikariam.gameforge.com',
                        'DNT': '1',
                        'Connection': 'keep-alive',
                        'Pragma': 'no-cache',
                        'Cache-Control': 'no-cache',
                        'TE': 'Trailers'
                    }
                    self.s.headers.clear()
                    self.s.headers.update(self.headers)
                    data = {
                        "identity": self.mail,
                        "password": self.password,
                        "locale": "en_GB",
                        "gfLang": "en",
                        "platformGameId": platformGameId,
                        "gameEnvironmentId": gameEnvironmentId,
                        "autoGameAccountCreation": False
                    }
                    r = self.s.post(
                        'https://gameforge.com/api/v1/auth/thin/sessions',
                        json=data)
                    if 'gf-challenge-id' in r.headers:
                        self.writeLog("Failed to solve interactive captcha!")
                        print(
                            "Failed to solve interactive captcha, trying again!"
                        )
                        continue
                    else:
                        break

        if r.status_code == 403:
            sys.exit(_('Wrong email or password\n'))

        # get the authentication token and set the cookie
        ses_json = json.loads(r.text, strict=False)
        auth_token = ses_json['token']
        cookie_obj = requests.cookies.create_cookie(domain='.gameforge.com',
                                                    name='gf-token-production',
                                                    value=auth_token)
        self.s.cookies.set_cookie(cookie_obj)

        # get accounts
        self.headers = {
            'Host': 'lobby.ikariam.gameforge.com',
            'User-Agent': user_agent,
            'Accept': 'application/json',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Referer': 'https://lobby.ikariam.gameforge.com/es_AR/hub',
            'Authorization': 'Bearer {}'.format(auth_token),
            'DNT': '1',
            'Connection': 'close'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        r = self.s.get(
            'https://lobby.ikariam.gameforge.com/api/users/me/accounts')
        accounts = json.loads(r.text, strict=False)

        # get servers
        self.headers = {
            'Host': 'lobby.ikariam.gameforge.com',
            'User-Agent': user_agent,
            'Accept': 'application/json',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
            'Referer': 'https://lobby.ikariam.gameforge.com/es_AR/hub',
            'Authorization': 'Bearer {}'.format(auth_token),
            'DNT': '1',
            'Connection': 'close'
        }
        self.s.headers.clear()
        self.s.headers.update(self.headers)
        r = self.s.get('https://lobby.ikariam.gameforge.com/api/servers')
        servers = json.loads(r.text, strict=False)

        if not self.logged:

            if len([
                    account for account in accounts
                    if account['blocked'] is False
            ]) == 1:
                self.account = [
                    account for account in accounts
                    if account['blocked'] is False
                ][0]
            else:
                print(_('With which account do you want to log in?\n'))

                max_name = max([
                    len(account['name']) for account in accounts
                    if account['blocked'] is False
                ])
                i = 0
                for account in [
                        account for account in accounts
                        if account['blocked'] is False
                ]:
                    server = account['server']['language']
                    mundo = account['server']['number']
                    account_group = account['accountGroup']
                    server_lang = None
                    world, server_lang = [
                        (srv['name'], srv['language']) for srv in servers
                        if srv['accountGroup'] == account_group
                    ][0]

                    i += 1
                    pad = ' ' * (max_name - len(account['name']))
                    print('({:d}) {}{} [{} - {}]'.format(
                        i, account['name'], pad, server_lang, world))
                num = read(min=1, max=i)
                self.account = [
                    account for account in accounts
                    if account['blocked'] is False
                ][num - 1]
            self.username = self.account['name']
            self.login_servidor = self.account['server']['language']
            self.account_group = self.account['accountGroup']
            self.mundo = str(self.account['server']['number'])

            self.word, self.servidor = [
                (srv['name'], srv['language']) for srv in servers
                if srv['accountGroup'] == self.account_group
            ][0]

            config.infoUser = _('Server:{}').format(self.servidor)
            config.infoUser += _(', World:{}').format(self.word)
            config.infoUser += _(', Player:{}').format(self.username)
            banner()

        self.host = 's{}-{}.ikariam.gameforge.com'.format(
            self.mundo, self.servidor)
        self.urlBase = 'https://{}/index.php?'.format(self.host)

        self.headers = {
            'Host': self.host,
            'User-Agent': user_agent,
            'Accept': '*/*',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
            'Referer': 'https://{}'.format(self.host),
            'X-Requested-With': 'XMLHttpRequest',
            'Origin': 'https://{}'.format(self.host),
            'DNT': '1',
            'Connection': 'keep-alive',
            'Pragma': 'no-cache',
            'Cache-Control': 'no-cache'
        }

        sessionData = self.getSessionData()

        used_old_cookies = False
        # if there are cookies stored, try to use them
        if 'cookies' in sessionData and self.logged is False:
            # create a new temporary session object
            old_s = requests.Session()
            # set the headers
            old_s.headers.clear()
            old_s.headers.update(self.headers)
            # set the cookies to test
            cookie_dict = sessionData['cookies']
            requests.cookies.cookiejar_from_dict(cookie_dict,
                                                 cookiejar=old_s.cookies,
                                                 overwrite=True)
            self.__update_proxy(obj=old_s, sessionData=sessionData)
            try:
                # make a request to check the connection
                html = old_s.get(self.urlBase,
                                 verify=config.do_ssl_verify).text
            except Exception:
                self.__proxy_error()

            cookies_are_valid = self.__isExpired(html) is False
            if cookies_are_valid:
                self.__log('using old cookies')
                used_old_cookies = True
                # assign the old cookies to the session object
                requests.cookies.cookiejar_from_dict(cookie_dict,
                                                     cookiejar=self.s.cookies,
                                                     overwrite=True)
                # set the proxy
                self.__update_proxy(sessionData=sessionData)
                # set the headers
                self.s.headers.clear()
                self.s.headers.update(self.headers)

        # login as normal and get new cookies
        if used_old_cookies is False:
            self.__log('using new cookies')
            resp = self.s.get(
                'https://lobby.ikariam.gameforge.com/api/users/me/loginLink?id={}&server[language]={}&server[number]={}'
                .format(self.account['id'], self.login_servidor,
                        self.mundo)).text
            resp = json.loads(resp, strict=False)
            if 'url' not in resp:
                if retries > 0:
                    return self.__login(retries - 1)
                else:
                    msg = 'Login Error: ' + str(resp)
                    if self.padre:
                        print(msg)
                        sys.exit()
                    else:
                        sys.exit(msg)

            url = resp['url']
            match = re.search(
                r'https://s\d+-\w{2}\.ikariam\.gameforge\.com/index\.php\?',
                url)
            if match is None:
                sys.exit('Error')

            # set the headers
            self.s.headers.clear()
            self.s.headers.update(self.headers)

            # set the proxy
            self.__update_proxy(sessionData=sessionData)

            # use the new cookies instead, invalidate the old ones
            try:
                html = self.s.get(url, verify=config.do_ssl_verify).text
            except Exception:
                self.__proxy_error()

        if self.__isInVacation(html):
            msg = _('The account went into vacation mode')
            if self.padre:
                print(msg)
            else:
                sendToBot(self, msg)
            os._exit(0)
        if self.__isExpired(html):
            if retries > 0:
                return self.__login(retries - 1)
            if self.padre:
                msg = _('Login error.')
                print(msg)
                os._exit(0)
            raise Exception('Couldn\'t log in')

        if not used_old_cookies:
            self.__saveNewCookies()

        self.logged = True