def attackBarbarians(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        banner()

        island = choose_island(session)
        if island is None:
            event.set()
            return

        babarians_info = get_barbarians_lv(session, island)

        banner()
        print(_('The barbarians have:'))
        for name, amount in babarians_info['troops']:
            print(_('{} units of {}').format(amount, name))
        print('')

        banner()
        print(_('From which city do you want to attack?'))
        city = chooseCity(session)

        plan = plan_attack(session, city, babarians_info)
        if plan is None:
            event.set()
            return

        banner()
        print(
            _('The barbarians in [{}:{}] will be attacked.').format(
                island['x'], island['y']))
        enter()

    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI attack the barbarians in [{}:{}]\n').format(
        island['x'], island['y'])
    setInfoSignal(session, info)
    try:
        do_it(session, island, city, babarians_info, plan)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
def searchForIslandSpaces(s, e, fd):
    sys.stdin = os.fdopen(fd)
    try:
        if checkTelegramData(s) is False:
            e.set()
            return
        banner()
        print(_('I will search for new spaces each hour.'))
        enter()
    except KeyboardInterrupt:
        e.set()
        return

    set_child_mode(s)
    e.set()

    info = _('\nI search for new spaces each hour\n')
    setInfoSignal(s, info)
    try:
        do_it(s)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()
Exemple #3
0
def loginDaily(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        banner()
        print(_('I will enter every day.'))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI enter every day\n')
    setInfoSignal(session, info)
    try:
        do_it(session)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #4
0
def alertLowWine(s, e, fd):
    sys.stdin = os.fdopen(fd)
    try:
        if checkTelegramData(s) is False:
            e.set()
            return
        banner()
        hours = read(msg=_(
            'How many hours should be left until the wine runs out in a city so that it\'s alerted?'
        ),
                     min=1)
        print(
            _('It will be alerted when the wine runs out in less than {:d} hours in any city'
              ).format(hours))
        enter()
    except KeyboardInterrupt:
        e.set()
        return

    set_child_mode(s)
    e.set()

    info = _('\nI alert if the wine runs out in less than {:d} hours\n'
             ).format(hours)
    setInfoSignal(s, info)
    try:
        do_it(s, hours)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()
Exemple #5
0
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()
Exemple #6
0
def alertAttacks(s,e,fd):
	sys.stdin = os.fdopen(fd)
	try:
		if checkTelegramData(s) is False:
			e.set()
			return

		banner()
		default = 20
		minutes = read(msg=_('How often should I search for attacks?(min:3, default: {:d}): ').format(default), min=3, empty=True)
		if minutes == '':
			minutes = default
		print(_('I will check for attacks every {:d} minutes').format(minutes))
		enter()
	except KeyboardInterrupt:
		e.set()
		return

	set_child_mode(s)
	e.set()

	info = _('\nI check for attacks every {:d} minutes\n').format(minutes)
	setInfoSignal(s, info)
	try:
		do_it(s, minutes)
	except:
		msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc())
		sendToBot(s, msg)
	finally:
		s.logout()
Exemple #7
0
def donationBot(s, e, fd):
    sys.stdin = os.fdopen(fd)
    try:
        banner()
        (cities_ids, cities) = getIdsOfCities(s)
        cities_dict = {}
        initials = [material_name[0] for material_name in materials_names]
        for cityId in cities_ids:
            tradegood = cities[cityId]['tradegood']
            initial = initials[int(tradegood)]
            print(
                _('In {} ({}), Do you wish to donate to the forest, to the trading good or neither? [f/t/n]'
                  ).format(cities[cityId]['name'], initial))
            f = _('f')
            t = _('t')
            n = _('n')

            rta = read(values=[f, f.upper(), t, t.upper(), n, n.upper()])
            if rta.lower() == f:
                donation_type = 'resource'
            elif rta.lower() == t:
                donation_type = 'tradegood'
            else:
                donation_type = None
                percentage = None

            if donation_type is not None:
                print(
                    _('What is the maximum percentage of your storage capacity that you whish to keep occupied? (the resources that exceed it, will be donated) (default: 80%)'
                      ))
                percentage = read(min=0, max=100, empty=True)
                if percentage == '':
                    percentage = 80
                elif percentage == 100:  # if the user is ok with the storage beeing totally full, don't donate at all
                    donation_type = None

            cities_dict[cityId] = {
                'donation_type': donation_type,
                'percentage': percentage
            }

        print(_('I will donate every day.'))
        enter()
    except KeyboardInterrupt:
        e.set()
        return

    set_child_mode(s)
    e.set()

    info = _('\nI donate every day\n')
    setInfoSignal(s, info)
    try:
        do_it(s, cities_ids, cities_dict)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()
Exemple #8
0
def botDonador(s):
	banner()
	(idsCiudades, ciudades) = getIdsDeCiudades(s)
	ciudades_dict = {}
	bienes = {'1': _('(V)'), '2': '(M)', '3': '(C)', '4': _('(A)')}
	for idCiudad in idsCiudades:
		tradegood = ciudades[idCiudad]['tradegood']
		bien = bienes[tradegood]
		print(_('En la ciudad {} {}, ¿Desea donar al aserradero, al bien de cambio o a ninguno? [a/b/n]').format(ciudades[idCiudad]['name'], bien))
		rta = read(values=[_('a'), _('A'), _('b'), _('B'), 'n', 'N'])
		if rta.lower() == _('a'):
			tipo = 'resource'
		if rta.lower() == _('b'):
			tipo = 'tradegood'
		else:
			tipo = None
		ciudades_dict[idCiudad] = {'tipo': tipo}

	print(_('Se donará todos los días.'))
	enter()

	forkear(s)
	if s.padre is True:
		return

	info = _('\nDono todos los días\n')
	setInfoSignal(s, info)
	try:
		do_it(s, idsCiudades, ciudades_dict)
	except:
		msg = _('Error en:\n{}\nCausa:\n{}').format(info, traceback.format_exc())
		sendToBot(msg)
	finally:
		s.logout()
Exemple #9
0
def alertarPocoVino(s):
    if botValido(s) is False:
        return
    horas = read(msg=_(
        '¿Cuántas horas deben quedar hasta que se acabe el vino en una ciudad para que es dé aviso?: '
    ),
                 min=1)
    print(
        _('Se avisará cuando el vino se acabe en {:d} horas en alguna ciudad.'
          ).format(horas))
    enter()

    forkear(s)
    if s.padre is True:
        return

    info = _('\nAviso si el vino se acaba en {:d} horas\n').format(horas)
    setInfoSignal(s, info)
    try:
        do_it(s, horas)
    except:
        msg = _('Error en:\n{}\nCausa:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #10
0
def searchForIslandSpaces(session, event, stdin_fd):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	event : multiprocessing.Event
	stdin_fd: int
	"""
    sys.stdin = os.fdopen(stdin_fd)
    try:
        if checkTelegramData(session) is False:
            event.set()
            return
        banner()
        print(_('I will search for new spaces each hour.'))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI search for new spaces each hour\n')
    setInfoSignal(session, info)
    try:
        do_it(session)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #11
0
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()
Exemple #12
0
def entrarDiariamente(s):
    print(_('Se entrará todos los días automaticamente.'))
    enter()

    forkear(s)
    if s.padre is True:
        return

    info = _('\nEntro diariamente\n')
    setInfoSignal(s, info)
    try:
        do_it(s)
    except:
        msg = _('Error en:\n{}\nCausa:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #13
0
def buscarEspacios(s):
    if botValido(s) is False:
        return
    print('Se buscarán espacios nuevos cada hora.')
    enter()

    forkear(s)
    if s.padre is True:
        return

    info = '\nBusco espacios nuevos en las islas cada 1 hora\n'
    setInfoSignal(s, info)
    try:
        do_it(s)
    except:
        msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #14
0
def alertAttacks(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        if checkTelegramData(session) is False:
            event.set()
            return

        banner()
        default = 20
        minutes = read(msg=_(
            'How often should I search for attacks?(min:3, default: {:d}): ').
                       format(default),
                       min=3,
                       default=default)
        # min_units = read(msg=_('Attacks with less than how many units should be ignored? (default: 0): '), digit=True, default=0)
        print(_('I will check for attacks every {:d} minutes').format(minutes))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI check for attacks every {:d} minutes\n').format(minutes)
    setInfoSignal(session, info)
    try:
        do_it(session, minutes)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #15
0
def alertarAtaques(s):
	if botValido(s) is False:
		return
	print('Se buscarán ataques cada 20 minutos.')
	enter()

	forkear(s)
	if s.padre is True:
		return

	info = '\nEspero por ataques cada 20 minutos\n'
	setInfoSignal(s, info)
	try:
		do_it(s)
	except:
		msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc())
		sendToBot(msg)
	finally:
		s.logout()
Exemple #16
0
def alertLowWine(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        if checkTelegramData(session) is False:
            event.set()
            return
        banner()
        hours = read(msg=_(
            'How many hours should be left until the wine runs out in a city so that it\'s alerted?'
        ),
                     min=1)
        print(
            _('It will be alerted when the wine runs out in less than {:d} hours in any city'
              ).format(hours))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI alert if the wine runs out in less than {:d} hours\n'
             ).format(hours)
    setInfoSignal(session, info)
    try:
        do_it(session, hours)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #17
0
def alertAttacks(session, event, stdin_fd):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	event : multiprocessing.Event
	stdin_fd: int
	"""
    sys.stdin = os.fdopen(stdin_fd)
    try:
        if checkTelegramData(session) is False:
            event.set()
            return

        banner()
        default = 20
        minutes = read(msg=_(
            'How often should I search for attacks?(min:3, default: {:d}): ').
                       format(default),
                       min=3,
                       empty=True)
        if minutes == '':
            minutes = default
        print(_('I will check for attacks every {:d} minutes').format(minutes))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI check for attacks every {:d} minutes\n').format(minutes)
    setInfoSignal(session, info)
    try:
        do_it(session, minutes)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #18
0
def loginDaily(s, e, fd):
    sys.stdin = os.fdopen(fd)
    try:
        banner()
        print(_('I will enter every day.'))
        enter()
    except KeyboardInterrupt:
        e.set()
        return

    set_child_mode(s)
    e.set()

    info = _('\nI enter every day\n')
    setInfoSignal(s, info)
    try:
        do_it(s)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(s, msg)
    finally:
        s.logout()
Exemple #19
0
def botDonador(s):
    if botValido(s) is False:
        return

    banner()
    (idsCiudades, ciudades) = getIdsDeCiudades(s)
    ciudades_dict = {}
    bienes = {'1': '(V)', '2': '(M)', '3': '(C)', '4': '(A)'}
    for idCiudad in idsCiudades:
        html = s.get(urlCiudad + idCiudad)
        ciudad = getCiudad(html)
        tradegood = ciudades[idCiudad]['tradegood']
        bien = bienes[tradegood]
        print(
            'En la ciudad {} {}, ¿Desea donar al aserradero o al bien de cambio? [a/b]'
            .format(ciudad['cityName'], bien))
        rta = read(values=['a', 'A', 'b', 'B'])
        tipo = 'resource' if rta.lower() == 'a' else 'tradegood'
        ciudades_dict[idCiudad] = {'isla': ciudad['islandId'], 'tipo': tipo}

    print('Se donará todos los días.')
    enter()

    forkear(s)
    if s.padre is True:
        return

    info = '\nDono todos los días\n'
    setInfoSignal(s, info)
    try:
        do_it(s, idsCiudades, ciudades_dict)
    except:
        msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #20
0
def menuRutaComercial(s):
    rutas = []
    while True:

        banner()
        print('Ciudad de origen:')
        try:
            ciudadO = elegirCiudad(s)
        except KeyboardInterrupt:
            if rutas:
                print('¿Enviar viajes? [Y/n]')
                rta = read(values=['y', 'Y', 'n', 'N', ''])
                if rta.lower() != 'n':
                    break
            return
        html = ciudadO['html']
        max = getRecursosDisponibles(html)
        total = list(map(int, max))

        banner()
        print('Ciudad de destino')
        ciudadD = elegirCiudad(s, ajenas=True)
        idIsla = ciudadD['islandId']

        if ciudadO['id'] == ciudadD['id']:
            continue

        if ciudadD['propia']:
            html = ciudadD['html']
            mad, vin, mar, cri, azu = getRecursosDisponibles(html, num=True)
            capacidad = getCapacidadDeAlmacenamiento(html)
            capacidad = int(capacidad)
            mad = capacidad - mad
            vin = capacidad - vin
            mar = capacidad - mar
            cri = capacidad - cri
            azu = capacidad - azu

        resto = total
        for ruta in rutas:
            (origen, destino, _, md, vn, mr, cr, az) = ruta
            if origen['id'] == ciudadO['id']:
                resto = (resto[0] - md, resto[1] - vn, resto[2] - mr,
                         resto[3] - cr, resto[4] - az)
            if ciudadD['propia'] and destino['id'] == ciudadD['id']:
                mad = mad - md
                vin = vin - vn
                mar = mar - mr
                cri = cri - cr
                azu = azu - az

        banner()
        if ciudadD['propia']:
            msg = ''
            if resto[0] > mad:
                msg += '{} más de madera\n'.format(addPuntos(mad))
            if resto[1] > vin:
                msg += '{} más de vino\n'.format(addPuntos(vin))
            if resto[2] > mar:
                msg += '{} más de marmol\n'.format(addPuntos(mar))
            if resto[3] > cri:
                msg += '{} más de cristal\n'.format(addPuntos(cri))
            if resto[4] > azu:
                msg += '{} más de azufre\n'.format(addPuntos(azu))
            if msg:
                print('Solo puede almacenar:\n' + msg)
        print('Disponible:')
        print('Madera {} Vino {} Marmol {} Cristal {} Azufre {}'.format(
            addPuntos(resto[0]), addPuntos(resto[1]), addPuntos(resto[2]),
            addPuntos(resto[3]), addPuntos(resto[4])))
        print('Enviar:')
        try:
            md = pedirValor(' Madera:', resto[0])
            vn = pedirValor('   Vino:', resto[1])
            mr = pedirValor(' Marmol:', resto[2])
            cr = pedirValor('Cristal:', resto[3])
            az = pedirValor(' Azufre:', resto[4])
        except KeyboardInterrupt:
            continue
        if md + vn + mr + cr + az == 0:
            continue

        banner()
        print('Por enviar de {} a {}'.format(ciudadO['cityName'],
                                             ciudadD['cityName']))
        enviado = ''
        if md:
            enviado += 'Madera:{} '.format(addPuntos(md))
        if vn:
            enviado += 'Vino:{} '.format(addPuntos(vn))
        if mr:
            enviado += 'Marmol:{} '.format(addPuntos(mr))
        if cr:
            enviado += 'Cristal:{} '.format(addPuntos(cr))
        if az:
            enviado += 'Azufre:{}'.format(addPuntos(az))
        print(enviado)
        print('¿Proceder? [Y/n]')
        rta = read(values=['y', 'Y', 'n', 'N', ''])
        if rta.lower() != 'n':
            ruta = (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az)
            rutas.append(ruta)
            print('¿Realizar otro envio? [y/N]')
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() != 'y':
                break

    forkear(s)
    if s.padre is True:
        return

    info = '\nRuta comercial\n'
    for ruta in rutas:
        (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az) = ruta
        info = info + '{} -> {}\nMadera: {} Vino: {} Marmol: {} Cristal: {} Azufre: {}\n'.format(
            ciudadO['cityName'], ciudadD['cityName'], addPuntos(md),
            addPuntos(vn), addPuntos(mr), addPuntos(cr), addPuntos(az))

    setInfoSignal(s, info)
    try:
        msg = 'Comienzo a enviar recursos:\n'
        msg += info
        sendToBotDebug(msg, debugON_menuRutaComercial)

        planearViajes(s, rutas)

        msg = 'Termino de enviar recursos:\n'
        msg += info
        sendToBotDebug(msg, debugON_menuRutaComercial)
    except:
        msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #21
0
def constructionList(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        global expand
        global sendResources
        expand = True
        sendResources = True

        banner()
        wait_resources = False
        print(_('In which city do you want to expand a building?'))
        city = chooseCity(session)
        cityId = city['id']
        building = getBuildingToExpand(session, cityId)
        if building is None:
            event.set()
            return

        current_level = building['level']
        if building['isBusy']:
            current_level += 1
        final_level = building['upgradeTo']

        # calculate the resources that are needed
        resourcesNeeded = getResourcesNeeded(session, city, building,
                                             current_level, final_level)
        if -1 in resourcesNeeded:
            event.set()
            return

        print('\nMaterials needed:')
        for i, name in enumerate(materials_names):
            amount = resourcesNeeded[i]
            if amount == 0:
                continue
            print('- {}: {}'.format(name, addThousandSeparator(amount)))
        print('')

        # calculate the resources that are missing
        missing = [0] * len(materials_names)
        for i in range(len(materials_names)):
            if city['recursos'][i] < resourcesNeeded[i]:
                missing[i] = resourcesNeeded[i] - city['recursos'][i]

        # show missing resources to the user
        if sum(missing) > 0:
            print(_('\nMissing:'))
            for i in range(len(materials_names)):
                if missing[i] == 0:
                    continue
                name = materials_names[i].lower()
                print(
                    _('{} of {}').format(addThousandSeparator(missing[i]),
                                         name))
            print('')

            # if the user wants, send the resources from the selected cities
            print(_('Automatically transport resources? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                print(_('Proceed anyway? [Y/n]'))
                rta = read(values=['y', 'Y', 'n', 'N', ''])
                if rta.lower() == 'n':
                    event.set()
                    return
            else:
                wait_resources = True
                sendResourcesMenu(session, cityId, missing)
        else:
            print(_('\nYou have enough materials'))
            print(_('Proceed? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                event.set()
                return
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nUpgrade building\n')
    info = info + _('City: {}\nBuilding: {}. From {:d}, to {:d}').format(
        city['cityName'], building['name'], current_level, final_level)

    setInfoSignal(session, info)
    try:
        if expand:
            expandBuilding(session, cityId, building, wait_resources)
        elif thread:
            thread.join()
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #22
0
def subirEdificios(s):
    banner()
    ciudad = elegirCiudad(s)
    idCiudad = ciudad['id']
    edificios = getEdificios(s, idCiudad)
    if edificios == []:
        return
    posEdificio = edificios[0]
    niveles = len(edificios)
    html = s.get(urlCiudad + idCiudad)
    ciudad = getCiudad(html)
    edificio = ciudad['position'][posEdificio]
    desde = int(edificio['level'])
    if edificio['isBusy']:
        desde += 1
    hasta = desde + niveles
    try:
        (madera, vino, marmol, cristal,
         azufre) = recursosNecesarios(s, ciudad, edificio, desde, hasta)
        assert madera != 0
        html = s.get(urlCiudad + idCiudad)
        (maderaDisp, vinoDisp, marmolDisp, cristalDisp,
         azufreDisp) = getRecursosDisponibles(html, num=True)
        if maderaDisp < madera or vinoDisp < vino or marmolDisp < marmol or cristalDisp < cristal or azufreDisp < azufre:
            print('\nFalta:')
            if maderaDisp < madera:
                print('{} de madera'.format(addPuntos(madera - maderaDisp)))
            if vinoDisp < vino:
                print('{} de vino'.format(addPuntos(vino - vinoDisp)))
            if marmolDisp < marmol:
                print('{} de marmol'.format(addPuntos(marmol - marmolDisp)))
            if cristalDisp < cristal:
                print('{} de cristal'.format(addPuntos(cristal - cristalDisp)))
            if azufreDisp < azufre:
                print('{} de azufre'.format(addPuntos(azufre - azufreDisp)))
            print('¿Proceder de todos modos? [Y/n]')
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                return
        else:
            print('\nTiene materiales suficientes')
            print('¿Proceder? [Y/n]')
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                return
    except AssertionError:
        pass
    forkear(s)
    if s.padre is True:
        return

    info = '\nSubir edificio\n'
    info = info + 'Ciudad: {}\nEdificio: {}.Desde {:d}, hasta {:d}'.format(
        ciudad['cityName'], edificio['name'], desde, hasta)

    setInfoSignal(s, info)
    try:
        subirEdificio(s, idCiudad, posEdificio, niveles)
    except:
        msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #23
0
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()
Exemple #24
0
def trainArmy(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        banner()

        print(_('Do you want to train troops (1) or ships (2)?'))
        rta = read(min=1, max=2)
        trainTroops = rta == 1
        banner()

        if trainTroops:
            print(_('In what city do you want to train the troops?'))
        else:
            print(_('In what city do you want to train the fleet?'))
        city = chooseCity(session)
        banner()

        lookfor = 'barracks' if trainTroops else 'shipyard'
        for i in range(len(city['position'])):
            if city['position'][i]['building'] == lookfor:
                city['pos'] = str(i)
                break
        else:
            if trainTroops:
                print(_('Barracks not built.'))
            else:
                print(_('Shipyard not built.'))
            enter()
            event.set()
            return

        data = getBuildingInfo(session, city, trainTroops)

        units_info = data[2][1]
        units = generateArmyData(units_info)

        maxSize = max([len(unit['local_name']) for unit in units])

        tranings = []
        while True:
            units = generateArmyData(units_info)
            print(_('Train:'))
            for unit in units:
                pad = ' ' * (maxSize - len(unit['local_name']))
                amount = read(msg='{}{}:'.format(pad, unit['local_name']), min=0, empty=True)
                if amount == '':
                    amount = 0
                unit['cantidad'] = amount

            # calculate costs
            cost = [0] * (len(materials_names_english) + 3)
            for unit in units:
                for i in range(len(materials_names_english)):
                    material_name = materials_names_english[i].lower()
                    if material_name in unit['costs']:
                        cost[i] += unit['costs'][material_name] * unit['cantidad']

                if 'citizens' in unit['costs']:
                    cost[len(materials_names_english)+0] += unit['costs']['citizens'] * unit['cantidad']
                if 'upkeep' in unit['costs']:
                    cost[len(materials_names_english)+1] += unit['costs']['upkeep'] * unit['cantidad']
                if 'completiontime' in unit['costs']:
                    cost[len(materials_names_english)+2] += unit['costs']['completiontime'] * unit['cantidad']

            print(_('\nTotal cost:'))
            for i in range(len(materials_names_english)):
                if cost[i] > 0:
                    print('{}: {}'.format(materials_names_english[i], addThousandSeparator(cost[i])))
            if cost[len(materials_names_english)+0] > 0:
                print(_('Citizens: {}').format(addThousandSeparator(cost[len(materials_names_english)+0])))
            if cost[len(materials_names_english)+1] > 0:
                print(_('Maintenance: {}').format(addThousandSeparator(cost[len(materials_names_english)+1])))
            if cost[len(materials_names_english)+2] > 0:
                print(_('Duration: {}').format(daysHoursMinutes(int(cost[len(materials_names_english)+2]))))

            print(_('\nProceed? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                event.set()
                return

            tranings.append(units)

            if trainTroops:
                print(_('\nDo you want to train more troops when you finish? [y/N]'))
            else:
                print(_('\nDo you want to train more fleets when you finish? [y/N]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'y':
                banner()
                continue
            else:
                break

        # calculate if the city has enough resources
        resourcesAvailable = city['recursos'].copy()
        resourcesAvailable.append(city['ciudadanosDisp'])

        for training in tranings:
            for unit in training:

                for i in range(len(materials_names_english)):
                    material_name = materials_names_english[i].lower()
                    if material_name in unit['costs']:
                        resourcesAvailable[i] -= unit['costs'][material_name] * unit['cantidad']

                if 'citizens' in unit['costs']:
                    resourcesAvailable[len(materials_names_english)] -= unit['costs']['citizens'] * unit['cantidad']

        not_enough = [elem for elem in resourcesAvailable if elem < 0] != []

        if not_enough:
            print(_('\nThere are not enough resources:'))
            for i in range(len(materials_names_english)):
                if resourcesAvailable[i] < 0:
                    print('{}:{}'.format(materials_names[i], addThousandSeparator(resourcesAvailable[i]*-1)))

            if resourcesAvailable[len(materials_names_english)] < 0:
                print(_('Citizens:{}').format(addThousandSeparator(resourcesAvailable[len(materials_names_english)]*-1)))

            print(_('\nProceed anyway? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() == 'n':
                event.set()
                return

        if trainTroops:
            print(_('\nThe selected troops will be trained.'))
        else:
            print(_('\nThe selected fleet will be trained.'))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    if trainTroops:
        info = _('\nI train troops in {}\n').format(city['cityName'])
    else:
        info = _('\nI train fleets in {}\n').format(city['cityName'])
    setInfoSignal(session, info)
    try:
        planTrainings(session, city, tranings, trainTroops)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info, traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #25
0
def entrenarTropas(s):
    banner()
    print(_('¿En qué ciudad quiere entrenar las tropas?'))
    ciudad = elegirCiudad(s)
    banner()

    for i in range(len(ciudad['position'])):
        if ciudad['position'][i]['building'] == 'barracks':
            ciudad['pos'] = str(i)
            break

    data = getCuartelInfo(s, ciudad)
    unidades_info = data[2][1]
    unidades = generateTroops(unidades_info)

    maxSize = 0
    for unidad in unidades:
        if maxSize < len(unidad['local_name']):
            maxSize = len(unidad['local_name'])

    entrenamientos = []
    while True:
        unidades = generateTroops(unidades_info)
        print(_('Entrenar:'))
        for unidad in unidades:
            cantidad = read(msg='{}{}:'.format(
                ' ' * (maxSize - len(unidad['local_name'])),
                unidad['local_name']),
                            min=0,
                            empty=True)
            if cantidad == '':
                cantidad = 0
            unidad['cantidad'] = cantidad

        print(_('\nCosto total:'))
        costo = {
            'madera': 0,
            'vino': 0,
            'marmol': 0,
            'cristal': 0,
            'azufre': 0,
            'ciudadanos': 0,
            'manuntencion': 0,
            'tiempo': 0
        }
        for unidad in unidades:

            if 'wood' in unidad['costs']:
                costo['madera'] += unidad['costs']['wood'] * unidad['cantidad']
            if 'wine' in unidad['costs']:
                costo['vino'] += unidad['costs']['wine'] * unidad['cantidad']
            if 'marble' in unidad['costs']:
                costo[
                    'marmol'] += unidad['costs']['marble'] * unidad['cantidad']
            if 'cristal' in unidad['costs']:
                costo['cristal'] += unidad['costs']['cristal'] * unidad[
                    'cantidad']
            if 'sulfur' in unidad['costs']:
                costo[
                    'azufre'] += unidad['costs']['sulfur'] * unidad['cantidad']
            if 'citizens' in unidad['costs']:
                costo['ciudadanos'] += unidad['costs']['citizens'] * unidad[
                    'cantidad']
            if 'upkeep' in unidad['costs']:
                costo['manuntencion'] += unidad['costs']['upkeep'] * unidad[
                    'cantidad']
            if 'completiontime' in unidad['costs']:
                costo['tiempo'] += unidad['costs']['completiontime'] * unidad[
                    'cantidad']

        if costo['madera']:
            print(_('     Madera: {}').format(addPuntos(costo['madera'])))
        if costo['vino']:
            print(_('       Vino: {}').format(addPuntos(costo['vino'])))
        if costo['marmol']:
            print(_('     Marmol: {}').format(addPuntos(costo['marmol'])))
        if costo['cristal']:
            print(_('    Cristal: {}').format(addPuntos(costo['cristal'])))
        if costo['azufre']:
            print(_('     Azufre: {}').format(addPuntos(costo['azufre'])))
        if costo['ciudadanos']:
            print(_(' Ciudadanos: {}').format(addPuntos(costo['ciudadanos'])))
        if costo['manuntencion']:
            print(
                _('Manutención: {}').format(addPuntos(costo['manuntencion'])))
        if costo['tiempo']:
            print(
                _('   Duración: {}').format(
                    diasHorasMinutos(int(costo['tiempo']))))

        print(_('\nProceder? [Y/n]'))
        rta = read(values=['y', 'Y', 'n', 'N', ''])
        if rta.lower() == 'n':
            return

        entrenamientos.append(unidades)

        print(_('\n¿Quiere entrenar más tropas al terminar? [y/N]'))
        rta = read(values=['y', 'Y', 'n', 'N', ''])
        if rta.lower() == 'y':
            banner()
            continue
        else:
            break

    recursos = getRecursosDisponibles(ciudad['html'], num=True)
    ciudadanos = getCiudadanosDisponibles(ciudad['html'])
    sobrante = {}
    sobrante['madera'] = recursos[0]
    sobrante['vino'] = recursos[1]
    sobrante['marmol'] = recursos[2]
    sobrante['cristal'] = recursos[3]
    sobrante['azufre'] = recursos[4]
    sobrante['ciudadanos'] = ciudadanos

    for entrenamiento in entrenamientos:
        for unidad in entrenamiento:

            if 'wood' in unidad['costs']:
                sobrante[
                    'madera'] -= unidad['costs']['wood'] * unidad['cantidad']
            if 'wine' in unidad['costs']:
                sobrante[
                    'vino'] -= unidad['costs']['wine'] * unidad['cantidad']
            if 'marble' in unidad['costs']:
                sobrante[
                    'marmol'] -= unidad['costs']['marble'] * unidad['cantidad']
            if 'cristal' in unidad['costs']:
                sobrante['cristal'] -= unidad['costs']['cristal'] * unidad[
                    'cantidad']
            if 'sulfur' in unidad['costs']:
                sobrante[
                    'azufre'] -= unidad['costs']['sulfur'] * unidad['cantidad']
            if 'citizens' in unidad['costs']:
                sobrante['ciudadanos'] -= unidad['costs']['citizens'] * unidad[
                    'cantidad']

    falta = [elem for elem in sobrante if sobrante[elem] < 0] != []

    if falta:
        print(_('\nNo hay suficientes recursos:'))
        if sobrante['madera'] < 0:
            print(
                _('    Madera:{}').format(addPuntos(sobrante['madera'] * -1)))
        if sobrante['vino'] < 0:
            print(_('      Vino:{}').format(addPuntos(sobrante['vino'] * -1)))
        if sobrante['marmol'] < 0:
            print(
                _('    Marmol:{}').format(addPuntos(sobrante['marmol'] * -1)))
        if sobrante['cristal'] < 0:
            print(
                _('   Cristal:{}').format(addPuntos(sobrante['cristal'] * -1)))
        if sobrante['azufre'] < 0:
            print(
                _('    Azufre:{}').format(addPuntos(sobrante['azufre'] * -1)))
        if sobrante['ciudadanos'] < 0:
            print(
                _('Ciudadanos:{}').format(
                    addPuntos(sobrante['ciudadanos'] * -1)))

        print(_('\n¿Proceder de todos modos? [Y/n]'))
        rta = read(values=['y', 'Y', 'n', 'N', ''])
        if rta.lower() == 'n':
            return

    print(_('\nSe entrenarán las tropas seleccionadas.'))
    enter()

    forkear(s)
    if s.padre is True:
        return

    info = _('\nEntreno tropas en {}\n').format(ciudad['cityName'])
    setInfoSignal(s, info)
    try:
        planearEntrenamientos(s, ciudad, entrenamientos)
    except:
        msg = _('Error en:\n{}\nCausa:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #26
0
def activateMiracle(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        banner()

        islands = obtainMiraclesAvailable(session)
        if islands == []:
            print(_('There are no miracles available.'))
            enter()
            event.set()
            return

        island = chooseIsland(islands)
        if island is None:
            event.set()
            return

        if island['available']:
            print(
                _('\nThe miracle {} will be activated').format(
                    island['wonderName']))
            print(_('Proceed? [Y/n]'))
            activate_miracle_input = read(values=['y', 'Y', 'n', 'N', ''])
            if activate_miracle_input.lower() == 'n':
                event.set()
                return

            miracle_activation_result = activateMiracleHttpCall(
                session, island)

            if miracle_activation_result[1][1][0] == 'error':
                print(
                    _('The miracle {} could not be activated.').format(
                        island['wonderName']))
                enter()
                event.set()
                return

            data = miracle_activation_result[2][1]
            for elem in data:
                if 'countdown' in data[elem]:
                    enddate = data[elem]['countdown']['enddate']
                    currentdate = data[elem]['countdown']['currentdate']
                    break
            wait_time = enddate - currentdate

            print(
                _('The miracle {} was activated.').format(
                    island['wonderName']))
            enter()
            banner()

            while True:
                print(
                    _('Do you wish to activate it again when it is finished? [y/N]'
                      ))

                reactivate_again_input = read(values=['y', 'Y', 'n', 'N', ''])
                if reactivate_again_input.lower() != 'y':
                    event.set()
                    return

                iterations = read(msg=_('How many times?: '),
                                  digit=True,
                                  min=0)

                if iterations == 0:
                    event.set()
                    return

                duration = wait_time * iterations

                print(
                    _('It will finish in:{}').format(
                        daysHoursMinutes(duration)))

                print(_('Proceed? [Y/n]'))
                reactivate_again_input = read(values=['y', 'Y', 'n', 'N', ''])
                if reactivate_again_input.lower() == 'n':
                    banner()
                    continue
                break
        else:
            print(
                _('\nThe miracle {} will be activated in {}').format(
                    island['wonderName'],
                    daysHoursMinutes(island['available_in'])))
            print(_('Proceed? [Y/n]'))
            user_confirm = read(values=['y', 'Y', 'n', 'N', ''])
            if user_confirm.lower() == 'n':
                event.set()
                return
            wait_time = island['available_in']
            iterations = 1

            print(_('\nThe mirable will be activated.'))
            enter()
            banner()

            while True:
                print(
                    _('Do you wish to activate it again when it is finished? [y/N]'
                      ))

                reactivate_again_input = read(values=['y', 'Y', 'n', 'N', ''])
                again = reactivate_again_input.lower() == 'y'
                if again is True:
                    try:
                        iterations = read(msg=_('How many times?: '),
                                          digit=True,
                                          min=0)
                    except KeyboardInterrupt:
                        iterations = 1
                        break

                    if iterations == 0:
                        iterations = 1
                        break

                    iterations += 1
                    duration = wait_time * iterations
                    print(
                        _('It is not possible to calculate the time of finalization. (at least: {})'
                          ).format(daysHoursMinutes(duration)))
                    print(_('Proceed? [Y/n]'))

                    try:
                        activate_input = read(values=['y', 'Y', 'n', 'N', ''])
                    except KeyboardInterrupt:
                        iterations = 1
                        break

                    if activate_input.lower() == 'n':
                        iterations = 1
                        banner()
                        continue
                break
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI activate the miracle {} {:d} times\n').format(
        island['wonderName'], iterations)
    setInfoSignal(session, info)
    try:
        do_it(session, island, iterations)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #27
0
def sendResources(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        routes = []
        while True:

            banner()
            print(_('Origin city:'))
            try:
                cityO = chooseCity(session)
            except KeyboardInterrupt:
                if routes:
                    print(_('Send shipment? [Y/n]'))
                    rta = read(values=['y', 'Y', 'n', 'N', ''])
                    if rta.lower() != 'n':
                        break
                event.set()
                return

            banner()
            print(_('Destination city'))
            cityD = chooseCity(session, foreign=True)
            idIsland = cityD['islandId']

            if cityO['id'] == cityD['id']:
                continue

            resources_left = cityO['recursos']
            for route in routes:
                (origin_city, destination_city, __, *toSend) = route
                if origin_city['id'] == cityO['id']:
                    for i in range(len(materials_names)):
                        resources_left[i] -= toSend[i]

                # the destination city might be from another player
                if cityD['propia'] and destination_city['id'] == cityD['id']:
                    for i in range(len(materials_names)):
                        cityD['freeSpaceForResources'][i] -= toSend[i]

            banner()
            # the destination city might be from another player
            if cityD['propia']:
                msg = ''
                for i in range(len(materials_names)):
                    if resources_left[i] > cityD['freeSpaceForResources'][i]:
                        msg += '{} more {}\n'.format(
                            addThousandSeparator(
                                cityD['freeSpaceForResources'][i]),
                            materials_names[i].lower())

                if len(msg) > 0:
                    print(_('You can store just:\n{}').format(msg))

            print(_('Available:'))
            for i in range(len(materials_names)):
                print('{}:{} '.format(materials_names[i],
                                      addThousandSeparator(resources_left[i])),
                      end='')
            print('')

            print(_('Send:'))
            try:
                max_name = max([len(material) for material in materials_names])
                send = []
                for i in range(len(materials_names)):
                    material_name = materials_names[i]
                    pad = ' ' * (max_name - len(material_name))
                    val = askForValue(_('{}{}:'.format(pad, material_name)),
                                      resources_left[i])
                    send.append(val)
            except KeyboardInterrupt:
                continue
            if sum(send) == 0:
                continue

            banner()
            print(
                _('About to send from {} to {}').format(
                    cityO['cityName'], cityD['cityName']))
            for i in range(len(materials_names)):
                if send[i] > 0:
                    print('{}:{} '.format(materials_names[i],
                                          addThousandSeparator(send[i])),
                          end='')
            print('')

            print(_('Proceed? [Y/n]'))
            rta = read(values=['y', 'Y', 'n', 'N', ''])
            if rta.lower() != 'n':
                route = (cityO, cityD, idIsland, *send)
                routes.append(route)
                print(_('Create another shipment? [y/N]'))
                rta = read(values=['y', 'Y', 'n', 'N', ''])
                if rta.lower() != 'y':
                    break
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nSend resources\n')

    setInfoSignal(session, info)
    try:
        executeRoutes(session, routes)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #28
0
def enviarVino(s):
    banner()
    vinoTotal = 0
    dict_idVino_diponible = {}
    (idsCiudades, ciudades) = getIdsDeCiudades(s)
    ciudadesVino = {}
    for idCiudad in idsCiudades:
        esVino = ciudades[idCiudad]['tradegood'] == '1'
        if esVino:
            html = s.get(urlCiudad + idCiudad)
            ciudad = getCiudad(html)
            recursos = getRecursosDisponibles(html)
            disponible = int(recursos[1]) - 1000  # dejo 1000 por las dudas
            ciudad['disponible'] = disponible if disponible > 0 else 0
            vinoTotal += ciudad['disponible']
            ciudadesVino[idCiudad] = ciudad
    aEnviar = len(ciudades) - len(ciudadesVino)
    vinoXciudad = int(vinoTotal / aEnviar)
    maximo = addPuntos(vinoXciudad)

    if vinoXciudad > 100000:
        maximo = maximo[:-6] + '00.000'
    elif vinoXciudad > 10000:
        maximo = maximo[:-5] + '0.000'
    elif vinoXciudad > 1000:
        maximo = maximo[:-3] + '000'
    elif vinoXciudad > 100:
        maximo = maximo[:-2] + '00'
    elif vinoXciudad > 10:
        maximo = maximo[:-1] + '0'
    print('Se puede enviar como máximo {} a cada ciudad'.format(maximo))
    cantidad = read(msg='¿Cuanto vino enviar a cada ciudad?:',
                    min=0,
                    max=vinoXciudad)

    print('\nPor enviar {} de vino a cada ciudad'.format(addPuntos(cantidad)))
    print('¿Proceder? [Y/n]')
    rta = read(values=['y', 'Y', 'n', 'N', ''])
    if rta.lower() == 'n':
        return

    forkear(s)
    if s.padre is True:
        return

    rutas = []
    for idCiudadDestino in idsCiudades:
        if idCiudadDestino not in ciudadesVino:
            htmlD = s.get(urlCiudad + idCiudadDestino)
            ciudadD = getCiudad(htmlD)
            idIsla = ciudadD['islandId']
            faltante = cantidad
            for idCiudadOrigen in ciudadesVino:
                if faltante == 0:
                    break
                ciudadO = ciudadesVino[idCiudadOrigen]
                vinoDisponible = ciudadO['disponible']
                for ruta in rutas:
                    (origen, _, _, _, vn, _, _, _) = ruta
                    if origen['id'] == idCiudadOrigen:
                        vinoDisponible -= vn
                enviar = faltante if vinoDisponible > faltante else vinoDisponible
                faltante -= enviar
                ruta = (ciudadO, ciudadD, idIsla, 0, enviar, 0, 0, 0)
                rutas.append(ruta)

    info = '\nEnviar vino\n'
    for ruta in rutas:
        (ciudadO, ciudadD, idIsla, md, vn, mr, cr, az) = ruta
        info = info + '{} -> {}\nVino: {}\n'.format(
            ciudadO['cityName'], ciudadD['cityName'], addPuntos(vn))
    setInfoSignal(s, info)
    try:
        planearViajes(s, rutas)
    except:
        msg = 'Error en:\n{}\nCausa:\n{}'.format(info, traceback.format_exc())
        sendToBot(msg)
    finally:
        s.logout()
Exemple #29
0
def searchForIslandSpaces(session, event, stdin_fd):
    """
	Parameters
	----------
	session : ikabot.web.session.Session
	event : multiprocessing.Event
	stdin_fd: int
	"""
    sys.stdin = os.fdopen(stdin_fd)
    try:
        if checkTelegramData(session) is False:
            event.set()
            return
        banner()
        print(
            'Do you want to search for spaces on your islands or a specific set of islands?'
        )
        print('(0) Exit')
        print('(1) Search all islands I have colonised')
        print('(2) Search a specific set of islands')
        choice = read(min=0, max=2)
        islandList = []
        if choice == 0:
            event.set()
            return
        elif choice == 2:
            banner()
            print(
                'Insert the coordinates of each island you want searched like so: X1:Y1, X2:Y2, X3:Y3...'
            )
            coords_string = read()
            coords_string = coords_string.replace(' ', '')
            coords = coords_string.split(',')
            for coord in coords:
                coord = '&xcoord=' + coord
                coord = coord.replace(':', '&ycoord=')
                html = session.get('view=island' + coord)
                island = getIsland(html)
                islandList.append(island['id'])
        else:
            pass

        banner()
        print(
            'How frequently should the islands be searched in minutes (minimum is 3)?'
        )
        time = read(min=3, digit=True)

        banner()
        print(_('I will search for changes in the selected islands'))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI search for new spaces each hour\n')
    setInfoSignal(session, info)
    try:
        do_it(session, islandList, time)
    except:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()
Exemple #30
0
def donationBot(session, event, stdin_fd, predetermined_input):
    """
    Parameters
    ----------
    session : ikabot.web.session.Session
    event : multiprocessing.Event
    stdin_fd: int
    predetermined_input : multiprocessing.managers.SyncManager.list
    """
    sys.stdin = os.fdopen(stdin_fd)
    config.predetermined_input = predetermined_input
    try:
        banner()
        (cities_ids, cities) = getIdsOfCities(session)
        cities_dict = {}
        initials = [material_name[0] for material_name in materials_names]
        print(
            'Enter how often you want to donate in minutes. (min = 1, default = 1 day)'
        )
        waiting_time = read(min=1, digit=True, default=1 * 24 * 60)
        print(
            'Enter a maximum additional random waiting time between donations in minutes. (min = 0, default = 1 hour)'
        )
        max_random_waiting_time = read(min=0, digit=True, default=1 * 60)
        for cityId in cities_ids:
            tradegood = cities[cityId]['tradegood']
            initial = initials[int(tradegood)]
            print(
                _('In {} ({}), Do you wish to donate to the forest, to the trading good or neither? [f/t/n]'
                  ).format(cities[cityId]['name'], initial))
            f = _('f')
            t = _('t')
            n = _('n')

            rta = read(values=[f, f.upper(), t, t.upper(), n, n.upper()])
            if rta.lower() == f:
                donation_type = 'resource'
            elif rta.lower() == t:
                donation_type = 'tradegood'
            else:
                donation_type = None
                percentage = None

            if donation_type is not None:
                print(
                    _('What is the maximum percentage of your storage capacity that you whish to keep occupied? (the resources that exceed it, will be donated) (default: 80%)'
                      ))
                percentage = read(min=0, max=100, empty=True)
                if percentage == '':
                    percentage = 80
                elif percentage == 100:  # if the user is ok with the storage beeing totally full, don't donate at all
                    donation_type = None

            cities_dict[cityId] = {
                'donation_type': donation_type,
                'percentage': percentage
            }

        print(_('I will donate every {} minutes.'.format(waiting_time)))
        enter()
    except KeyboardInterrupt:
        event.set()
        return

    set_child_mode(session)
    event.set()

    info = _('\nI donate every {} minutes\n'.format(waiting_time))
    setInfoSignal(session, info)
    try:
        do_it(session, cities_ids, cities_dict, waiting_time,
              max_random_waiting_time)
    except Exception as e:
        msg = _('Error in:\n{}\nCause:\n{}').format(info,
                                                    traceback.format_exc())
        sendToBot(session, msg)
    finally:
        session.logout()