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 activarMilagro(s): banner() islas = obtenerMilagrosDisponibles(s) if islas == []: print(_('No existen milagros disponibles.')) enter() return print(_('¿Qué milagro quiere activar?')) i = 0 print(_('(0) Salir')) for isla in islas: i += 1 print('({:d}) {}'.format(i, isla['wonderName'])) index = read(min=0, max=i) if index == 0: return isla = islas[index - 1] print(_('\nSe activará el milagro {}').format(isla['wonderName'])) print(_('¿Proceder? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return rta = activarMilagroImpl(s, isla) if rta[1][1][0] == 'error': print( _('No se pudo activar el milagro {}.').format(isla['wonderName'])) else: print(_('Se activó el milagro {}.').format(isla['wonderName'])) enter()
def sellResources(s, e, fd): sys.stdin = os.fdopen(fd) try: banner() commertial_cities = getCommertialCities(s) if len(commertial_cities) == 0: print(_('There is no store built')) enter() e.set() return if len(commertial_cities) == 1: city = commertial_cities[0] else: city = chooseComertialCity(commertial_cities) banner() print(_('What resource do you want to sell?')) for index, material_name in enumerate(materials_names): print('({:d}) {}'.format(index + 1, material_name)) choise = read(min=1, max=len(materials_names)) resource = choise - 1 banner() print( _('Do you want to sell to existing offers (1) or do you want to make your own offer (2)?' )) choise = read(min=1, max=2) [sellToOffers, createOffer][choise - 1](s, city, resource, e) except KeyboardInterrupt: e.set() return
def getSesion(): banner() html = normal_get('https://es.ikariam.gameforge.com/?').text servidores = re.findall( r'<a href="(?:https:)?//(\w{2})\.ikariam\.gameforge\.com/\?kid=[\d\w-]*" target="_top" rel="nofollow" class="mmoflag mmo_\w{2}">(.+)</a>', html) i = 0 for server in servidores: i += 1 print('({:d}) {}'.format(i, server[1])) servidor = read(msg='Servidor:', min=1, max=len(servidores)) srv = servidores[servidor - 1][0] config.infoUser = '******'.format(servidores[servidor - 1][1]) banner() if srv != 'es': html = normal_get( 'https://{}.ikariam.gameforge.com/?'.format(srv)).text html = re.search(r'registerServer[\s\S]*registerServerServerInfo', html).group() mundos = re.findall( r'mobileUrl="s(\d{1,3})-\w{2}\.ikariam\.gameforge\.com"(?:\s*cookieName="")?\s*>\s*([\w\s]+?)\s*</option>', html) i = 0 for mundo in mundos: i += 1 print('({:d}) {}'.format(i, mundo[1])) mundo = read(msg='Mundo:', min=1, max=len(mundos)) mundo = mundos[mundo - 1] config.infoUser += ', Mundo:{}'.format(mundo[1]) urlBase = 'https://s{}-{}.ikariam.gameforge.com/index.php?'.format( mundo[0], srv) uni_url = 's{}-{}.ikariam.gameforge.com'.format(mundo[0], srv) banner() usuario = read(msg='Usuario:') password = getpass.getpass('Contraseña:') headers = { 'Host': uni_url, 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding': 'gzip, deflate, br', 'Content-Type': 'application/x-www-form-urlencoded', 'Referer': urlBase } payload = { 'uni_url': uni_url, 'name': usuario, 'password': password, 'pwat_uid': '', 'pwat_checksum': '', 'startPageShown': '1', 'detectedDevice': '1', 'kid': '' } config.infoUser += ', Jugador:{}'.format(usuario) return Sesion(urlBase, payload, headers)
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 importExportCookie(session, event, stdin_fd): """ Parameters ---------- session : ikabot.web.session.Session event : multiprocessing.Event stdin_fd: int """ sys.stdin = os.fdopen(stdin_fd) banner() try: print('Do you want to import or export the cookie?') print('(0) Exit') print('(1) Import') print('(2) Export') action = read(min=0, max=2) if action == 1: importCookie(session) elif action == 2: exportCookie(session) event.set() except KeyboardInterrupt: event.set() return
def menu(s): banner() menu_actions = [ subirEdificios, menuRutaComercial, enviarVino, getStatus, donar, buscarEspacios, entrarDiariamente, alertarAtaques, botDonador, alertarPocoVino, comprarRecursos, update ] mnu = """ (0) Salir (1) Lista de construcción (2) Enviar recursos (3) Enviar vino (4) Estado de la cuenta (5) Donar (6) Buscar espacios nuevos (7) Entrar diariamente (8) Alertar ataques (9) Bot donador (10) Alertar poco vino (11) Comprar recursos (12) Actualizar Ikabot""" print(mnu) entradas = len(menu_actions) eleccion = read(min=0, max=entradas) if eleccion != 0: try: menu_actions[eleccion - 1](s) except KeyboardInterrupt: pass menu(s) else: clear()
def checkTelegramData(s): """This function doesn't actually check any data itself, that is done by the ``telegramDataIsValid`` function. This function returns ``True`` if there is any Telegram data in the .ikabot file, and if there is none, it will ask the user to input it. Parameters ---------- s : Session Session object Returns ------- valid : bool a boolean indicating whether or not there is valid Telegram data in the .ikabot file. """ if telegramDataIsValid(s): return True else: banner() print( _('You must provide valid credentials to communicate by telegram.') ) print( _('You require the token of the bot you are going to use and your chat_id' )) print( _('For more information about how to obtain them read the readme at https://github.com/physics-sp/ikabot' )) rta = read(msg=_('Will you provide the credentials now? [y/N]'), values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'y': return False else: return updateTelegramData(s)
def vacationMode(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(_('Activate vacation mode? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': event.set() return activateVacationMode(session) print(_('Vacation mode has been activated.')) enter() event.set() clear() sys.exit() except KeyboardInterrupt: event.set() return
def asignarRecursoBuscado(s, ciudad): print(_('¿Qué recurso quiere comprar?')) for indice, bien in enumerate(tipoDeBien): print('({:d}) {}'.format(indice + 1, bien)) eleccion = read(min=1, max=5) recurso = eleccion - 1 if recurso == 0: recurso = 'resource' data = { 'cityId': ciudad['id'], 'position': ciudad['pos'], 'view': 'branchOffice', 'activeTab': 'bargain', 'type': 444, 'searchResource': recurso, 'range': ciudad['rango'], 'backgroundView': 'city', 'currentCityId': ciudad['id'], 'templateView': 'branchOffice', 'currentTab': 'bargain', 'actionRequest': s.token(), 'ajax': 1 } rta = s.post(payloadPost=data) return eleccion, recurso
def menu(s): banner() menu_actions = [ subirEdificios, menuRutaComercial, repartirRecurso, getStatus, donar, buscarEspacios, entrarDiariamente, alertarAtaques, botDonador, alertarPocoVino, comprarRecursos, modoVacaciones, activarMilagro, entrenarTropas, movimientosNavales, update ] print(_('(0) Salir')) print(_('(1) Lista de construcción')) print(_('(2) Enviar recursos')) print(_('(3) Repartir recurso')) print(_('(4) Estado de la cuenta')) print(_('(5) Donar')) print(_('(6) Buscar espacios nuevos')) print(_('(7) Entrar diariamente')) print(_('(8) Alertar ataques')) print(_('(9) Bot donador')) print(_('(10) Alertar poco vino')) print(_('(11) Comprar recursos')) print(_('(12) Activar modo vacaciones')) print(_('(13) Activar milagro')) print(_('(14) Entrenar tropas')) print(_('(15) Ver movimientos')) print(_('(16) Actualizar Ikabot')) entradas = len(menu_actions) eleccion = read(min=0, max=entradas) if eleccion != 0: try: menu_actions[eleccion - 1](s) except KeyboardInterrupt: pass menu(s) else: clear()
def chooseResource(session, city): """ Parameters ---------- session : ikabot.web.session.Session city : dict """ print(_('Which resource do you want to buy?')) for index, material_name in enumerate(materials_names): print('({:d}) {}'.format(index + 1, material_name)) choise = read(min=1, max=5) resource = choise - 1 if resource == 0: resource = 'resource' data = { 'cityId': city['id'], 'position': city['pos'], 'view': 'branchOffice', 'activeTab': 'bargain', 'type': 444, 'searchResource': resource, 'range': city['rango'], 'backgroundView': 'city', 'currentCityId': city['id'], 'templateView': 'branchOffice', 'currentTab': 'bargain', 'actionRequest': actionRequest, 'ajax': 1 } # this will set the chosen resource in the store session.post(payloadPost=data) resource = choise - 1 # return the chosen resource return resource
def botValido(s): if telegramFileValido(): return True else: print( _('Debe proporcionar las credenciales válidas para comunicarse por telegram.' )) print(_('Se requiere del token del bot a utilizar y de su chat_id')) print( _('Para más informacion sobre como obtenerlos vea al readme de https://github.com/physics-sp/ikabot' )) rta = read(msg=_('¿Porporcionará las credenciales ahora? [y/N]'), values=['y', 'Y', 'n', 'N', '']) if rta.lower() != 'y': return False else: botToken = read(msg=_('Token del bot:')) chat_id = read(msg=_('Chat_id:')) with open(config.telegramFile, 'w', os.O_NONBLOCK) as filehandler: filehandler.write(botToken + '\n' + chat_id) filehandler.flush() rand = random.randint(1000, 9999) msg = _('El token a ingresar es:{:d}').format(rand) sendToBot(msg, Token=True) rta = read( msg=_('Se envio un mensaje por telegram, ¿lo recibió? [Y/n]'), values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': with open(config.telegramFile, 'w', os.O_NONBLOCK) as file: pass print(_('Revíse las credenciales y vuelva a proveerlas.')) enter() return False else: recibido = read( msg=_('Ingrese el token recibido mediante telegram:'), digit=True) if rand != recibido: with open(config.telegramFile, 'w', os.O_NONBLOCK) as file: pass print(_('El token es incorrecto')) enter() return False else: print(_('El token es correcto.')) enter() return True
def proxyConf(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( _('Warning: The proxy does not apply to the requests sent to the lobby!\n' )) session_data = session.getSessionData() if 'proxy' not in session_data or session_data['proxy']['set'] is False: print(_('Right now, there is no proxy configured.')) proxy_dict = read_proxy() if proxy_dict is None: event.set() return session_data['proxy'] = {} session_data['proxy']['conf'] = proxy_dict session_data['proxy']['set'] = True else: curr_proxy = session_data['proxy']['conf']['https'] print(_('Current proxy: {}').format(curr_proxy)) print(_('What do you want to do?')) print(_('0) Exit')) print(_('1) Set a new proxy')) print(_('2) Remove the current proxy')) rta = read(min=0, max=2) if rta == 0: event.set() return if rta == 1: proxy_dict = read_proxy() if proxy_dict is None: event.set() return session_data['proxy']['conf'] = proxy_dict session_data['proxy']['set'] = True if rta == 2: session_data['proxy']['set'] = False print(_('The proxy has been removed.')) enter() session.setSessionData(session_data) event.set() except KeyboardInterrupt: event.set() return
def sellResources(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() commercial_cities = getCommercialCities(session) if len(commercial_cities) == 0: print(_('There is no store built')) enter() event.set() return if len(commercial_cities) == 1: city = commercial_cities[0] else: city = chooseCommercialCity(commercial_cities) banner() print(_('What resource do you want to sell?')) for index, material_name in enumerate(materials_names): print('({:d}) {}'.format(index + 1, material_name)) selected_material = read(min=1, max=len(materials_names)) resource = selected_material - 1 banner() print( _('Do you want to sell to existing offers (1) or do you want to make your own offer (2)?' )) selected = read(min=1, max=2) [sellToOffers, createOffer][selected - 1](session, city, resource, event) except KeyboardInterrupt: event.set() return
def modoVacaciones(s): banner() print(_('¿Activar modo vacaciones? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return activarModoVacaciones(s) print(_('Se activo el modo vacaciones.')) enter() clear() exit()
def read_proxy(): print( _('Enter the proxy (examples: socks5://127.0.0.1:9050, https://45.117.163.22:8080):' )) proxy_str = read(msg='proxy: ') proxy_dict = {'http': proxy_str, 'https': proxy_str} if test_proxy(proxy_dict) is False: print(_('The proxy does not work.')) enter() return None print(_('The proxy works and it will be used for all future requests.')) enter() return proxy_dict
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
def chooseCommertialCity(commercial_cities): """ Parameters ---------- commercial_cities : list[dict] Returns ------- commercial_city : dict """ print(_('From which city do you want to buy resources?\n')) for i, city in enumerate(commercial_cities): print('({:d}) {}'.format(i + 1, city['name'])) selected_city_index = read(min=1, max=len(commercial_cities)) return commercial_cities[selected_city_index - 1]
def chooseCommercialCity(commercial_cities): """ Parameters ---------- commercial_cities : list[dict] Returns ------- commercial_city : dict """ print(_('In which city do you want to sell resources?\n')) for i, city in enumerate(commercial_cities): print('({:d}) {}'.format(i + 1, city['name'])) ind = read(min=1, max=len(commercial_cities)) return commercial_cities[ind - 1]
def vacationMode(s, e, fd): sys.stdin = os.fdopen(fd) try: banner() print(_('Activate vacation mode? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': e.set() return activateVacationMode(s) print(_('Vacation mode has been activated.')) enter() e.set() clear() exit() except KeyboardInterrupt: e.set() return
def __proxy_error(self): sessionData = self.getSessionData() if 'proxy' not in sessionData or sessionData['proxy']['set'] is False: sys.exit('network error') elif self.padre is True: print(_('There seems to be a problem connecting to ikariam.')) print(_('Do you want to disable the proxy? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': sys.exit() else: sessionData['proxy']['set'] = False self.setSessionData(sessionData) print(_('Proxy disabled, try again.')) enter() sys.exit() else: msg = _('Network error. Consider disabling the proxy.') sendToBot(self, msg) sys.exit()
def importCookie(session): banner() print( '{}⚠️ INSERTING AN INVALID COOKIE WILL LOG YOU OUT OF YOUR OTHER SESSIONS ⚠️{}\n\n' .format(bcolors.WARNING, bcolors.ENDC)) print( 'Go ahead and export the cookie from another ikabot instance now and then' ) print('type your "ikariam" cookie below:') newcookie = read() newcookie = newcookie.strip() newcookie = newcookie.replace('ikariam=', '') cookies = session.getSessionData()['cookies'] cookies['ikariam'] = newcookie if session.host in session.s.cookies._cookies: session.s.cookies.set('ikariam', newcookie, domain=session.host, path='/') else: session.s.cookies.set('ikariam', newcookie, domain='', path='/') session.s.proxies = proxyDict html = session.s.get(session.urlBase).text session.s.proxies = {} if session.isExpired(html): print( '{}Failure!{} All your other sessions have just been invalidated!'. format(bcolors.RED, bcolors.ENDC)) enter() else: print( '{}Success!{} This ikabot session will now use the cookie you provided' .format(bcolors.GREEN, bcolors.ENDC)) sessionData = session.getSessionData() sessionData['cookies']['ikariam'] = newcookie session.setSessionData(sessionData) enter() session.get()
def comprarRecursos(s): banner() ciudades_comerciales = getCiudadesComerciales(s) if len(ciudades_comerciales) == 0: print(_('No hay una Tienda contruida')) enter() return ciudad = ciudades_comerciales[0] # por ahora solo uso la primera ciudad numRecurso, recurso = asignarRecursoBuscado(s, ciudad) banner() ofertas = obtenerOfertas(s, ciudad) if len(ofertas) == 0: print(_('No se encontraron ofertas.')) return precio_total = 0 cantidad_total = 0 for oferta in ofertas: cantidad = oferta['cantidadDisponible'] unidad = oferta['precio'] costo = cantidad * unidad print(_('cantidad :{}').format(addPuntos(cantidad))) print(_('precio :{:d}').format(unidad)) print(_('costo :{}').format(addPuntos(costo))) print('') precio_total += costo cantidad_total += cantidad ocupado = getRecursosDisponibles(ciudad['html'], num=True)[numRecurso - 1] capacidad = getCapacidadDeAlmacenamiento(ciudad['html'], num=True) disponible = capacidad - ocupado print( _('Total disponible para comprar: {}, por {}').format( addPuntos(cantidad_total), addPuntos(precio_total))) if disponible < cantidad_total: print( _('Solo se puede comprar {} por falta de almacenamiento.').format( addPuntos(disponible))) cantidad_total = disponible print('') cantidadAComprar = read(msg=_('¿Cuánta cantidad comprar? '), min=0, max=cantidad_total) if cantidadAComprar == 0: return oro = getOro(s, ciudad) costoTotal = calcularCosto(ofertas, cantidadAComprar) print( _('\nOro actual : {}.\nCosto total: {}.\nOro final : {}.').format( addPuntos(oro), addPuntos(costoTotal), addPuntos(oro - costoTotal))) print(_('¿Proceder? [Y/n]')) rta = read(values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': return print(_('Se comprará {}').format(addPuntos(cantidadAComprar))) enter() forkear(s) if s.padre is True: return info = _('\nCompro {} de {} para {}\n').format(addPuntos(cantidadAComprar), tipoDeBien[numRecurso - 1], ciudad['cityName']) setInfoSignal(s, info) try: do_it(s, ciudad, ofertas, cantidadAComprar) except: msg = _('Error en:\n{}\nCausa:\n{}').format(info, traceback.format_exc()) sendToBot(msg) finally: s.logout()
def __login(self, retries=0): self.__log('__login()') if not self.logged: banner() self.mail = read(msg=_('Mail:')) 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: exit('gameEnvironmentId not found') gameEnvironmentId = gameEnvironmentId.group(1) platformGameId = re.search(r'"platformGameId":"(.*?)"', js) if platformGameId is None: 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: 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() # 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) # 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": "es_AR", "gfLang": "ar", "platformGameId": platformGameId, "gameEnvironmentId": gameEnvironmentId, "autoGameAccountCreation": "false" } r = self.s.post('https://gameforge.com/api/v1/auth/thin/sessions', json=data) if r.status_code == 403: 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'] world = [ srv['name'] for srv in servers if srv['language'] == server and srv['number'] == mundo ][0] i += 1 pad = ' ' * (max_name - len(account['name'])) print('({:d}) {}{} [{} - {}]'.format( i, account['name'], pad, server, 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.servidor = self.account['server']['language'] self.mundo = str(self.account['server']['number']) self.word = [ srv['name'] for srv in servers if srv['language'] == self.servidor and srv['number'] == int(self.mundo) ][0] config.infoUser = _('Server:{}').format(self.servidor) config.infoUser += _(', World:{}').format(self.word) config.infoUser += _(', Player:{}').format(self.username) banner() self.host = f's{self.mundo}-{self.servidor}.ikariam.gameforge.com' self.urlBase = f'https://{self.host}/index.php?' 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' } self.cipher = AESCipher(self.mail, self.username, self.password) sessionData = self.getSessionData() used_old_cookies = False # if there are cookies stored, try to use them if 'num_sesiones' in sessionData and sessionData[ 'num_sesiones'] > 0 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) # make a request to check the connection old_s.proxies = proxyDict html = old_s.get(self.urlBase).text old_s.proxies = {} 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 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.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) exit() else: exit(msg) url = resp['url'] match = re.search( r'https://s\d+-\w{2}\.ikariam\.gameforge\.com/index\.php\?', url) if match is None: exit('Error') # set the headers self.s.headers.clear() self.s.headers.update(self.headers) # use the new cookies instead, invalidate the old ones self.s.proxies = proxyDict html = self.s.get(url).text self.s.proxies = {} 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 used_old_cookies: self.__updateCookieFile(nuevo=True) else: self.__updateCookieFile(primero=True) self.logged = True
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 chooseCommertialCity(commercial_cities): print(_('From which city do you want to buy resources?\n')) for i, ciudad in enumerate(commercial_cities): print('({:d}) {}'.format(i + 1, ciudad['name'])) ind = read(min=1, max=len(commercial_cities)) return commercial_cities[ind - 1]
def updateTelegramData(s, e=None, fd=None): """This function asks the user to input the Telegram bot's token and the user's own Telegram chat id. After the user has inputted the neccessary data, this function will generate a random 4 digit number, send it to the user as a Telegram message using the token the user provided. It will then ask the user to input that number as validation. Parameters ---------- s : Session Session object e : multiprocessing.Event an event which, when fired, give back control of the terminal to the main process fd : int the standard input file descriptor passed to the function as a means of gaining control of the terminal Returns ------- valid : bool a boolean indicating whether or not the Telegram data has been successfully updated """ if e is not None and fd is not None: sys.stdin = os.fdopen(fd) # give process access to terminal banner() botToken = read(msg=_('Bot\'s token:')) chat_id = read(msg=_('Chat_id:')) sessionData = s.getSessionData() sessionData['telegram'] = {} sessionData['telegram']['botToken'] = botToken.replace(' ', '').replace( '.', '') sessionData['telegram']['chatId'] = chat_id s.setSessionData(sessionData) rand = random.randint(1000, 9999) msg = _('El token a ingresar es:{:d}').format(rand) sendToBot(s, msg, Token=True) rta = read( msg=_('A message was sent by telegram, did you receive it? [Y/n]'), values=['y', 'Y', 'n', 'N', '']) if rta.lower() == 'n': valid = False else: recibido = read(msg=_('Enter the received token in telegram:'), digit=True) if rand != recibido: print(_('The token is incorrect')) valid = False else: print(_('The token is correct')) valid = True if valid is False: sessionData['telegram']['botToken'] = '' sessionData['telegram']['chatId'] = '' s.setSessionData(sessionData) print(_('Check the credentials and re-supply them.')) else: print(_('The data was saved.')) enter() if e is not None and fd is not None: e.set() #give main process control before exiting return valid
def menu(session, checkUpdate=True): """ Parameters ---------- session : ikabot.web.session.Session checkUpdate : bool """ if checkUpdate: checkForUpdate() banner() process_list = updateProcessList(session) if len(process_list) > 0: print(_('Running tasks:')) for process in process_list: if len(process['proxies']) == 0: proxy = '' else: proxy = _('proxy: ') + str(process['proxies']) print(_('- pid: {} task: {} {}').format(process['pid'], process['action'], proxy)) print('') menu_actions = [ constructionList, sendResources, distributeResources, getStatus, donate, searchForIslandSpaces, loginDaily, alertAttacks, donationBot, alertLowWine, buyResources, sellResources, vacationMode, activateMiracle, trainArmy, shipMovements, constructBuilding, update, importExportCookie, autoPirate, updateTelegramData ] print(_('(0) Exit')) print(_('(1) Construction list')) print(_('(2) Send resources')) print(_('(3) Distribute resources')) print(_('(4) Account status')) print(_('(5) Donate')) print(_('(6) Search for new spaces')) print(_('(7) Login daily')) print(_('(8) Alert attacks')) print(_('(9) Donate automatically')) print(_('(10) Alert wine running out')) print(_('(11) Buy resources')) print(_('(12) Sell resources')) print(_('(13) Activate vacation mode')) print(_('(14) Activate miracle')) print(_('(15) Train army')) print(_('(16) See movements')) print(_('(17) Construct building')) print(_('(18) Update Ikabot')) print(_('(19) Import / Export cookie')) print(_('(20) Auto-Pirate')) if telegramDataIsValid(session): print(_('(21) Change the Telegram data')) else: print(_('(21) Enter the Telegram data')) total_options = len(menu_actions) selected = read(min=0, max=total_options) if selected != 0: try: selected -= 1 event = multiprocessing.Event() #creates a new event process = multiprocessing.Process(target=menu_actions[selected], args=(session, event, sys.stdin.fileno()), name=menu_actions[selected].__name__) process.start() process_list.append({'pid': process.pid, 'proxies': session.s.proxies, 'action': menu_actions[selected].__name__ }) updateProcessList(session, programprocesslist=process_list) event.wait() #waits for the process to fire the event that's been given to it. When it does this process gets back control of the command line and asks user for more input except KeyboardInterrupt: pass menu(session, checkUpdate=False) else: if isWindows: # in unix, you can exit ikabot and close the terminal and the processes will continue to execute # in windows, you can exit ikabot but if you close the terminal, the processes will die print(_('Closing this console will kill the processes.')) enter() clear() os._exit(0) #kills the process which executes this statement, but it does not kill it's child processes
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()