예제 #1
0
def scrape_classifica(brow: webdriver) -> None:
    """
	Scrape real data from website in order to check later how the algorithm is
	working.
	"""

    brow.get(f'{cfg.BASE_URL}classifica')
    time.sleep(3)

    dbf.empty_table(table='classifica')

    positions = brow.find_elements_by_xpath(
        './/table/tbody/tr[contains(@data-logo, ".png")]')

    columns = ['team', 'G', 'V', 'N', 'P', 'Gf', 'Gs', 'Dr', 'Pt', 'Tot']
    for pos in positions:
        team_data = []
        scroll_to_element(brow, pos)
        fields = pos.find_elements_by_xpath('.//td')[2:-2]

        for field in fields:
            team_data.append(field.text)

        dbf.db_insert(table='classifica', columns=columns, values=team_data)

    brow.close()
예제 #2
0
def insert_new_bet_entry() -> int:

    dbf.db_insert(table='bets',
                  columns=['status', 'result'],
                  values=['Pending', 'Unknown'])

    return get_pending_bet_id()
예제 #3
0
def add_expired_quotes() -> None:

	matches = dbf.db_select(table='matches', columns=['id', 'date'], where='')

	now_dt = datetime.datetime.now()
	past_matches = [str(i) for i, dt in matches if str_to_dt(dt) < now_dt]

	all_options = dbf.db_select(table='quotes',
	                            columns=['match', 'bet', 'quote'],
	                            where=f'match in ({",".join(past_matches)})')
	all_options = [i for i in all_options if 'HAND' not in i[1]]
	all_options = [i for i in all_options if i[1] != 'GOAL/NO GOAL_GOAL']
	all_options = [i for i in all_options if i[1] != 'GOAL/NO GOAL_NOGOAL']

	for i, data in enumerate(all_options, 1):

		print(f'\r{i}/{len(all_options)}', end='')

		match_id, bet, quote = data

		bet_alias = dbf.db_select(table='fields',
		                          columns=['alias'],
		                          where=f'name = "{bet}"')[0]

		_, lg, tm1, tm2, date, _ = dbf.db_select(table='matches',
		                                         columns=['*'],
		                                         where=f'id = {match_id}')[0]

		dbf.db_insert(table='simulations',
					  columns=['date', 'team1', 'team2',
							   'league', 'bet_alias', 'quote'],
					  values=[date, tm1, tm2, lg, bet_alias, quote])
예제 #4
0
def prezzo_base_automatico(user, ab_id, player_name, autobid_value, active):
    """
	Presenta un'offerta a prezzo base o comunica la mancanza di un'asta attiva.
	Utilizzata all'interno di confermo_autobid(). L'oggetto del return può
	essere un tuple o una str in modo da distinguere il messaggio da inviare
	in chat privata e quello da inviare nel gruppo ufficiale.
	Utilizzata all'interno di confermo_autobid().

	:param user: str, fantasquadra
	:param ab_id: int, id dell'autobid
	:param player_name: str, nome del calciatore
	:param autobid_value: int, valore autobid
	:param active: bool

	:return: tuple o str a seconda dei casi

	"""

    if active:

        pl_id, pr_base = dbf.db_select(
            table='players',
            columns=['player_id', 'player_price'],
            where=f'player_name = "{player_name}"')[0]

        if autobid_value < pr_base:
            dbf.db_delete(table='autobids', where=f'autobid_id = {ab_id}')

            return ('Valore autobid troppo basso. ' +
                    f'Prezzo base: {pr_base}'), None

        dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        dbf.db_insert(
            table='offers',
            columns=[
                'offer_user', 'offer_player', 'offer_player_id', 'offer_price',
                'offer_dt', 'offer_status'
            ],
            values=[user, player_name, pl_id, pr_base, dt, 'Winning'])

        dbf.db_update(table='autobids',
                      columns=['autobid_status'],
                      values=['Confirmed'],
                      where=f'autobid_id = {ab_id}')

        private = ('Autobid impostato ed offerta a prezzo base ' +
                   'ufficializzata.' + cfg.SEPAR +
                   crea_riepilogo_autobid(user))

        group = (f'<i>{user}</i> offre per <b>{player_name}</b>' + cfg.SEPAR +
                 crea_riepilogo(dt))

        return private, group

    else:
        dbf.db_delete(table='autobids', where=f'autobid_id = {ab_id}')

        return 'Nessuna asta trovata per il calciatore scelto.', None
예제 #5
0
def offro(bot, update, args):
    """
	Inserisce nella tabella "offers" del db la nuova offerta presentata.
	Nel caso in cui l'offerta sia presentata in modo sbagliato invia in chat un
	messaggio di avviso.
	Lo status dell'offerta del db sarà NULL, in attesa di conferma.

	:param bot:
	:param update:
	:param args: list, input dell'user

	:return: messaggio in chat

	"""

    chat_id = update.message.chat_id
    if chat_id == cfg.FANTA_ID:
        return bot.send_message(chat_id=chat_id,
                                text='Utilizza la chat privata')

    user = select_user(update)
    dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    utl.aggiorna_offerte_chiuse(datetime.strptime(dt, '%Y-%m-%d %H:%M:%S'))

    # Elimino dal db tutte le offerte precedenti non confermate dall'utente
    dbf.db_delete(table='offers',
                  where=f'offer_user = "******" AND offer_status IS NULL')

    # Controllo che il formato sia giusto
    result = utl.check_offer_format(args)
    if type(result) == str:
        return bot.send_message(chat_id=chat_id, text=result)
    else:
        offer, pl = result

    # Aggiorno il db con i parametri che mancano
    pl_id = dbf.db_select(table='players',
                          columns=['player_id'],
                          where=f'player_name = "{pl}"')[0]

    team, roles, price = dbf.db_select(
        table='players',
        columns=['player_team', 'player_roles', 'player_price'],
        where=f'player_name = "{pl}"')[0]

    dbf.db_insert(table='offers',
                  columns=[
                      'offer_user', 'offer_player', 'offer_player_id',
                      'offer_price'
                  ],
                  values=[user, pl, pl_id, offer])

    return bot.send_message(parse_mode='HTML',
                            chat_id=chat_id,
                            text=f'Offri <b>{offer}</b> per:\n\n\t\t' +
                            f'<b>{pl}   ({team})   {roles}</b>' +
                            '\n\n/confermo_offerta')
예제 #6
0
def elimino_autobid(bot, update, args):
    """
	Inserisce nella tabella "elimina" del db l'autobid da cancellare.
	Richiede conferma.

	:param bot:
	:param update:
	:param args: list, input dell'user

	:return: messaggio in chat

	"""

    chat_id = update.message.chat_id
    if update.message.chat_id == cfg.FANTA_ID:
        return bot.send_message(chat_id=chat_id,
                                text='Utilizza la chat privata')

    user = select_user(update)

    # Elimino tutte le proposte di cancellazione non confermate dall'user
    dbf.db_delete(table='elimina', where=f'elimina_user = "******"')

    # Seleziono tutti gli autobids dell'user
    autobids = dbf.db_select(table='autobids',
                             columns=['autobid_player'],
                             where=f'autobid_user = "******"')
    if not autobids:
        return bot.send_message(chat_id=chat_id,
                                text='Non hai autobid impostati.')

    # Controllo che il comando sia inviato correttamente
    pl = ''.join(args).split(',')
    if not pl[0] or len(pl) != 1:
        return bot.send_message(chat_id=chat_id,
                                text=('Formato errato. ' +
                                      'Es: /elimina_autobid petagna'))

    jpl = ef.jaccard_result(pl[0], autobids, 3)
    if not jpl:
        return bot.send_message(chat_id=chat_id,
                                text='Giocatore non riconosciuto.')

    ab = dbf.db_select(
        table='autobids',
        columns=['autobid_id'],
        where=f'autobid_user = "******" AND autobid_player = "{jpl}"')[0]

    dbf.db_insert(table='elimina',
                  columns=['elimina_ab', 'elimina_user'],
                  values=[ab, user])

    message = (f"Stai eliminando l'autobid per <b>{jpl}</b>:" +
               "\n\n\t\t\t\t/confermo_eliminazione")

    return bot.send_message(parse_mode='HTML', chat_id=chat_id, text=message)
예제 #7
0
def scrape_roles_and_players_serie_a(brow: webdriver) -> webdriver:
    """
	Scrape all players from each real team in Serie A and their roles.
	Players are used when 6 politico is needed.
	"""

    # Players which are already in the db with their roles
    already_in_db = dbf.db_select(table='roles', columns=['name'], where='')

    # Download excel file with the data
    # url = 'https://www.fantacalcio.it/quotazioni-fantacalcio/mantra'
    # brow.get(url)
    # close_popup(brow)
    # time.sleep(3)
    # button = './/button[@id="toexcel"]'
    # wait_visible(brow, WAIT, button)
    # brow.find_element_by_xpath(button).click()
    # time.sleep(2)

    players = open_excel_file(cfg.QUOTAZIONI_FILENAME)

    # Create dict where keys are the teams of Serie A and values are lists
    # containing their players
    shortlists = defaultdict(list)
    for row in range(len(players)):
        rl, nm, tm = players.loc[row, ['R', 'Nome', 'Squadra']].values
        nm = format_player_name(player_name=nm)
        shortlists[tm.upper()].append(nm)

        # Update roles in the db
        if nm not in already_in_db:
            dbf.db_insert(table='roles',
                          columns=['name', 'role'],
                          values=[nm, rl])

    # Update the db
    teams_in_db = dbf.db_select(table='all_players_serie_a',
                                columns=['team'],
                                where='')

    for team, shortlist in shortlists.items():
        shortlist = ', '.join(shortlist)
        if team not in teams_in_db:
            dbf.db_insert(table='all_players_serie_a',
                          columns=['team', 'day_1'],
                          values=[team.upper(), shortlist])
        else:
            dbf.db_update(table='all_players_serie_a',
                          columns=[f'day_{last_day_played()}'],
                          values=[shortlist],
                          where=f'team = "{team}"')

    return brow
예제 #8
0
def autobid(bot, update, args):
    """
	Imposta momentaneamente il valore dell'autobid per un calciatore.
	Richiede conferma.

	:param bot:
	:param update:
	:param args: list, input dell'user. Formato: giocatore, valore autobid

	:return: messaggio in chat

	"""

    chat_id = update.message.chat_id
    if chat_id == cfg.FANTA_ID:
        return bot.send_message(chat_id=chat_id,
                                text=('Grazie per avercelo fatto sapere ' +
                                      'ma devi mandarlo in chat privata.'))

    user = select_user(update)
    dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    utl.aggiorna_offerte_chiuse(datetime.strptime(dt, '%Y-%m-%d %H:%M:%S'))

    # Elimino dal db tutti gli autobid precedenti non confermati dall'utente
    dbf.db_delete(table='autobids',
                  where=f'autobid_user = "******" AND autobid_status IS NULL')

    result = utl.check_autobid_format(args)
    if type(result) == str:
        return bot.send_message(chat_id=chat_id, text=result)
    else:
        jpl, ab = result

    # Squadra e ruoli
    tm, rl = dbf.db_select(table='players',
                           columns=['player_team', 'player_roles'],
                           where=f'player_name = "{jpl}"')[0]

    # Creo gli oggetti necessari per criptare il valore dell'autobid e li
    # inserisco nel db
    nonce, tag, value = dbf.encrypt_value(ab)
    dbf.db_insert(table='autobids',
                  columns=[
                      'autobid_user', 'autobid_player', 'autobid_nonce',
                      'autobid_tag', 'autobid_value'
                  ],
                  values=[user, jpl, nonce, tag, value])

    message = (f'\t\t\t\t<b>{jpl}</b>  <i>{tm}  {rl}</i>' +
               f'\n\nAutobid: {ab}\n\n\t\t\t\t/confermo_autobid')

    return bot.send_message(parse_mode='HTML', chat_id=chat_id, text=message)
예제 #9
0
def insert_players_first_time():

    players = pd.read_excel(io=cfa.QUOTAZIONI,
                            sheet_name="Tutti",
                            usecols=[1, 2, 3, 4],
                            engine='openpyxl')

    for x in range(1, len(players)):
        roles, name, team, price = players.iloc[x].values
        dbf.db_insert(table='players',
                      columns=['name', 'team', 'roles', 'price', 'status'],
                      values=[name.strip().title(), team.strip(),
                              roles.strip(), int(price), 'FREE'],
                      database=cfa.DB_NAME)
예제 #10
0
def offro(bot, update, args):

    # if update.message.chat_id != -318148079:
    # 	return bot.send_message(chat_id=update.message.chat_id,
    # 	                        text='Utilizza il gruppo ufficiale')

    user = select_user(update)

    try:
        offer, pl, team = check_offer_format(args)
    except ValueError:
        message = check_offer_format(args)
        return bot.send_message(chat_id=update.message.chat_id, text=message)

    delete_not_conf_offers_by_user(user)

    all_teams = list(
        set(dbf.db_select(table='players', columns_in=['player_team'])))
    j_tm = ef.jaccard_team(team, all_teams)
    j_pl = dbf.db_select(table='players',
                         columns_in=['player_name'],
                         where='player_team = "{}"'.format(j_tm))
    if not len(j_pl):
        return bot.send_message(chat_id=update.message.chat_id,
                                text='Squadra inesistente')

    pl = ef.jaccard_player(pl, j_pl)
    pl_id = dbf.db_select(table='players',
                          columns_in=['player_id'],
                          where='player_name = "{}"'.format(pl))[0]

    team, roles, price = dbf.db_select(
        table='players',
        columns_in=['player_team', 'player_roles', 'player_price'],
        where='player_name = "{}"'.format(pl))[0]

    dbf.db_insert(table='offers',
                  columns=[
                      'offer_user', 'offer_player', 'offer_player_id',
                      'offer_price'
                  ],
                  values=[user, pl, pl_id, offer])

    return bot.send_message(
        parse_mode='HTML',
        chat_id=update.message.chat_id,
        text='<i>{}</i> offre <b>{}</b> per:\n\n\t\t'.format(user, offer) +
        '<b>{}   ({})   {}</b>'.format(pl, team, roles) +
        '\n\n/conferma_offerta')
예제 #11
0
def aggiorna_db_con_nuove_quotazioni():
    """
	Aggiorna tutte le quotazioni dei calciatori prima di ogni mercato.
	Gestisce anche i trasferimenti interni alla Serie A aggiornando la
	squadra di appartenenza e l'arrivo di nuovi calciatori.

	"""

    mercati = ['PrimoMercato', 'SecondoMercato', 'TerzoMercato']

    last = ''

    for i in mercati:
        name = os.getcwd() + '/Quotazioni_' + i + '.xlsx'
        if os.path.isfile(name):
            last = name

    players = pd.read_excel(last, sheet_name="Tutti", usecols=[1, 2, 3, 4])
    pls_in_db = dbf.db_select(database=dbase,
                              table='players',
                              columns_in=['player_name'])

    for x in range(len(players)):
        role, pl, team, price = players.iloc[x].values

        if pl in pls_in_db:
            dbf.db_update(database=dbase,
                          table='players',
                          columns=['player_team', 'player_price'],
                          values=[team[:3].upper(),
                                  int(price)],
                          where='player_name = "{}"'.format(pl))
        else:
            dbf.db_insert(
                database=dbase,
                table='players',
                columns=[
                    'player_name', 'player_team', 'player_roles',
                    'player_price', 'player_status'
                ],
                values=[pl, team[:3].upper(), role,
                        int(price), 'FREE'])

    del players
예제 #12
0
def update_stats() -> None:
    """
	Update database used for market with stats.
	"""

    names_in_stats = dbf.db_select(table='stats', columns=['name'], where='')

    players = open_excel_file(cfg.QUOTAZIONI_FILENAME)

    for row in range(players.shape[0]):
        roles, name, team, price = players.iloc[row][[
            'R', 'Nome', 'Squadra', 'Qt. A'
        ]]
        name = format_player_name(player_name=name)
        matches, mv = calculate_mv(name)
        bonus = calculate_all_bonus(name)
        malus = calculate_all_malus(name)
        mfv = round(mv + (bonus - malus) / matches, 2) if matches else 0
        regular, going_in, going_out = calculate_regular_in_out(name)

        if name in names_in_stats:
            dbf.db_update(table='stats',
                          columns=[
                              'name', 'team', 'roles', 'mv', 'mfv', 'regular',
                              'going_in', 'going_out', 'price'
                          ],
                          values=[
                              name, team, roles, mv, mfv, regular, going_in,
                              going_out, price
                          ],
                          where=f'name = "{name}"')
        else:
            # print('New name for stats: ', name)
            dbf.db_insert(table='stats',
                          columns=[
                              'name', 'team', 'roles', 'status', 'mv', 'mfv',
                              'regular', 'going_in', 'going_out', 'price'
                          ],
                          values=[
                              name, team, roles, 'FREE', mv, mfv, regular,
                              going_in, going_out, price
                          ])

    os.remove(cfg.QUOTAZIONI_FILENAME)
예제 #13
0
def add_6_politico_if_needed(day: int) -> None:
    """
	Assign 6 to each player of the matches which have not been played.
	"""

    teams_in_day = set(
        dbf.db_select(table='votes', columns=['team'], where=f'day = {day}'))
    if len(teams_in_day) == 20:
        return

    all_teams = set(dbf.db_select(table='votes', columns=['team'], where=''))
    missing = all_teams - teams_in_day

    votes_of_day = dbf.db_select(table='votes',
                                 columns=[
                                     'day', 'name', 'team', 'alvin', 'gf',
                                     'gs', 'rp', 'rs', 'rf', 'au', 'amm',
                                     'esp', 'ass', 'regular', 'going_in',
                                     'going_out'
                                 ],
                                 where=f'day = {day}')

    for team in missing:
        shortlist = dbf.db_select(table='all_players_serie_a',
                                  columns=[f'day_{day}'],
                                  where=f'team = "{team}"')[0]
        shortlist = shortlist.split(', ')

        for nm in shortlist:
            data = (day, nm, team, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
            votes_of_day.append(data)

    votes_of_day.sort(key=lambda x: x[2])
    dbf.db_delete(table='votes', where=f'day = {day}')

    for row in votes_of_day:
        dbf.db_insert(table='votes',
                      columns=[
                          'day', 'name', 'team', 'alvin', 'gf', 'gs', 'rp',
                          'rs', 'rf', 'au', 'amm', 'esp', 'ass', 'regular',
                          'going_in', 'going_out'
                      ],
                      values=[value for value in row])
예제 #14
0
def fill_teams_table():

    leagues = dbf.db_select(table='leagues', columns=['name'], where='')

    shorts = []
    for league in leagues:
        old_teams = dbf.db_select(table='teams',
                                  columns=['name'],
                                  where=f'league = "{league}"')
        old_teams = set(old_teams)

        new_teams = dbf.db_select(table='matches',
                                  columns=['team1', 'team2'],
                                  where=f'league = "{league}"')
        new_teams = [el for pair in new_teams for el in pair]
        new_teams = set(new_teams)

        if new_teams - old_teams:

            dbf.db_delete(table='teams', where=f'league = "{league}"')
            for team in new_teams:
                dbf.db_insert(table='teams',
                              columns=['league', 'name'],
                              values=[league, team])

                short = team.replace(' ', '')
                short = re.findall(r'[*A-Z]+', short)[0]
                short = short[:3] if league != 'CHAMPIONS LEAGUE' else short[:4]

                if short not in shorts:
                    dbf.db_update(table='teams',
                                  columns=['short'],
                                  values=[short],
                                  where=f'name = "{team}"')
                    shorts.append(short)

                else:
                    dbf.db_update(table='teams',
                                  columns=['short'],
                                  values=['-'],
                                  where=f'name = "{team}"')
예제 #15
0
def update_to_play_table(nickname: str, bet_id: int) -> None:

    pred_id, dt, team1, team2, league, bet_alias = dbf.db_select(
        table='predictions',
        columns=['id', 'date', 'team1', 'team2', 'league', 'bet_alias'],
        where=f'user = "******" AND bet_id = {bet_id}')[-1]

    field_bet = dbf.db_select(table='fields',
                              columns=['name'],
                              where=f'alias = "{bet_alias}"')[0]
    field, bet = field_bet.split('_')

    team1 = team1 if league != 'CHAMPIONS LEAGUE' else f'*{team1}'
    match_id, *_, url = get_match_details(team_name=team1)[0]

    panel = dbf.db_select(
        table='quotes',
        columns=['panel'],
        where=f'match = {match_id} AND bet = "{field_bet}"')[0]

    dbf.db_insert(table='to_play',
                  columns=['pred_id', 'url', 'date', 'panel', 'field', 'bet'],
                  values=[pred_id, url, dt, panel, field, bet])
예제 #16
0
def quotazioni_iniziali():
    """
	Dopo averla svuotata, riempie la tabella "players" del db con tutti i dati
	relativi a ciascun giocatore ad inizio campionato.

	"""

    dbf.empty_table('players')

    players = pd.read_excel(os.getcwd() + '/Quotazioni.xlsx',
                            sheet_name="Tutti",
                            usecols=[1, 2, 3, 4])

    for i in range(len(players)):
        role, name, team, price = players.iloc[i].values
        dbf.db_insert(table='players',
                      columns=[
                          'player_name', 'player_team', 'player_roles',
                          'player_price'
                      ],
                      values=[name, team[:3].upper(), role, price])

    del players
예제 #17
0
def update_market_db():
    """
	Update the db used for market.
	"""

    # Update table "classifica"
    cols = ['team', 'G', 'V', 'N', 'P', 'Gf', 'Gs', 'Dr', 'Pt', 'Tot']
    dbf.empty_table(table='classifica', database=cfg.dbase2)
    data = dbf.db_select(table='classifica', columns=cols, where='')
    for el in data:
        dbf.db_insert(table='classifica',
                      columns=cols,
                      values=el,
                      database=cfg.dbase2)

    # Update table "players"
    cols = ['name', 'team', 'roles', 'price', 'status']
    dbf.empty_table(table='players', database=cfg.dbase2)
    data = dbf.db_select(table='stats', columns=cols, where='')
    for el in data:
        dbf.db_insert(table='players',
                      columns=[f'player_{i}' for i in cols],
                      values=el,
                      database=cfg.dbase2)
예제 #18
0
def scrape_votes(brow: webdriver) -> webdriver:
    """
	Download the excel file with the votes day by day and update the db.
	"""

    for day in range(1, last_day_played() + 1):

        if wrong_day_for_votes(day):
            continue

        url = cfg.VOTES_URL + str(day)
        brow.get(url)

        # all_tables = brow.find_elements_by_xpath('.//table[@role="grid"]')
        all_tables = brow.find_elements_by_xpath(
            './/table[contains(@class , "table-ratings")]')
        for table in all_tables:
            team = table.find_element_by_xpath('.//th[@class="team-header"]')
            scroll_to_element(brow, team)
            team = team.get_attribute('innerText')

            players = table.find_elements_by_xpath('.//tbody/tr')[:-1]
            for player in players:
                regular, going_in, going_out = regular_or_from_bench(player)
                data = player.find_elements_by_xpath('.//td')
                del data[1]

                nm = data[0].find_element_by_xpath('.//a').get_attribute(
                    'innerText')
                nm = format_player_name(player_name=nm)
                alvin = data[2].find_element_by_xpath('.//span').get_attribute(
                    'innerText')
                color = data[2].find_element_by_xpath('.//span').get_attribute(
                    'class')
                if 'grey' in color:
                    alvin = 'sv'
                    going_in = 0
                else:
                    alvin = float(alvin.replace(',', '.'))
                try:
                    data[2].find_element_by_xpath(
                        './/span[contains(@class, "trn-r trn-ry absort")]')
                    amm = 1
                except NoSuchElementException:
                    amm = 0
                try:
                    data[2].find_element_by_xpath(
                        './/span[contains(@class, "trn-r trn-rr absort")]')
                    esp = 1
                except NoSuchElementException:
                    esp = 0

                try:
                    gf = data[6].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    gf = 0 if gf == '-' else gf
                except NoSuchElementException:
                    gf = 0
                try:
                    rf = data[7].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    rf = 0 if rf == '-' else rf
                except NoSuchElementException:
                    rf = 0
                try:
                    gs = data[8].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    gs = 0 if gs == '-' else gs
                except NoSuchElementException:
                    gs = 0
                try:
                    rp = data[9].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    rp = 0 if rp == '-' else rp
                except NoSuchElementException:
                    rp = 0
                try:
                    rs = data[10].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    rs = 0 if rs == '-' else rs
                except NoSuchElementException:
                    rs = 0
                try:
                    au = data[11].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    au = 0 if au == '-' else au
                except NoSuchElementException:
                    au = 0
                try:
                    ass = data[12].find_element_by_xpath(
                        './/span').get_attribute('innerText')
                    if ass == '-':
                        ass = 0
                    elif len(ass) == 1:
                        ass = int(ass)
                    else:
                        ass = int(ass[0])
                except NoSuchElementException:
                    ass = 0

                # Update db
                dbf.db_insert(table='votes',
                              columns=[
                                  'day', 'name', 'team', 'alvin', 'gf', 'gs',
                                  'rp', 'rs', 'rf', 'au', 'amm', 'esp', 'ass',
                                  'regular', 'going_in', 'going_out'
                              ],
                              values=[
                                  day, nm, team, alvin, gf, gs, rp, rs, rf, au,
                                  amm, esp, ass, regular, going_in, going_out
                              ])

        add_6_politico_if_needed(day)
    return brow
예제 #19
0
def message_with_payment(user, acquisto, pagamento):
    """
	Crea il messaggio di riepilogo del pagamento.
	Utilizzato all'interno della funzione pago().


	:param user: str, nome della fantasquadra
	:param acquisto: str, giocatore da pagare
	:param pagamento: list, metodo di pagamento

	:return money_db: list, user_input dopo la correzioni dei nomi
	:return message: str, messaggio di riepilogo

	"""

    jpl = ef.jaccard_result(
        acquisto,
        dbf.db_select(table='offers',
                      columns=['offer_player'],
                      where=(f'offer_user = "******" AND ' +
                             'offer_status = "Not Official"')), 3)
    if not jpl:
        return ("Pagamento non riuscito.\n" +
                "Controlla che l'asta sia conclusa e che tu l'abbia vinta.")

    rosa = dbf.db_select(table='players',
                         columns=['player_name'],
                         where=f'player_status = "{user}"')

    for i, pl in enumerate(pagamento):
        try:
            # noinspection PyTypeChecker
            pagamento[i] = int(pl)
            continue
        except ValueError:
            pl2 = ef.jaccard_result(pl, rosa, 3)
            if not pl2:
                return f'Calciatore non riconosciuto nella tua rosa: {pl}'

            tm, rls, pr = dbf.db_select(
                table='players',
                columns=['player_team', 'player_roles', 'player_price'],
                where=f'player_name = "{pl2}"')[0]

            # noinspection PyTypeChecker
            pagamento[i] = (pl2, tm, rls, pr)

    # Nel pagamento proposto dall'user cfg.SEPARo i calciatori dai soldi
    money = 0
    for i in pagamento:
        if type(i) == int:
            money += i

    # Gestisco prima tutta la parte relativa all'acquisto
    off_id, price = dbf.db_select(table='offers',
                                  columns=['offer_id', 'offer_price'],
                                  where=(f'offer_player = "{jpl}" AND ' +
                                         'offer_status = "Not Official"'))[0]

    dbf.db_insert(table='pays',
                  columns=['pay_user', 'pay_offer', 'pay_player', 'pay_price'],
                  values=[user, off_id, jpl, price])

    team, roles = dbf.db_select(table='players',
                                columns=['player_team', 'player_roles'],
                                where=f'player_name = "{jpl}"')[0]

    message = ('Stai ufficializzando:\n\n\t\t\t\t\t\t' +
               f'<b>{jpl}</b> <i>({team})   {roles}</i>\n\n' +
               f'Prezzo: <b>{price}</b>.\n\nPagamento:\n')

    # Formatto alcuni parametri per poi inviarli come messaggio in chat
    pagamento = [el for el in pagamento if type(el) != int]
    money_db = ', '.join([f'{el[0]} ({el[1]}: {el[3]})' for el in pagamento])
    if money and len(pagamento):
        money_db += f', {money}'
    elif money:
        money_db += f'{money}'

    for pl, tm, rl, pr in pagamento:
        message += f'\n\t\t- <b>{pl}</b> <i>({tm})   {rl}</i>   {pr}'
    if money:
        message += f'\n\t\t- <b>{money}</b>'

    return money_db, message + '\n\n/confermo_pagamento'
예제 #20
0
def check_autobid_value(user, player, new_id, new_ab):
    """
	Esamina tutti i possibili casi ed agisce di conseguenza.

	:param user: str, fantasquadra
	:param player: str, calciatore
	:param new_id: int, id dell'autobid nel db
	:param new_ab: int, valore dell'autobid

	:return: tuple, bool o str

	"""

    # Controllo se c'è già un'asta in corso per il calciatore
    try:
        last_id, last_user, last_offer = dbf.db_select(
            table='offers',
            columns=['offer_id', 'offer_user', 'offer_price'],
            where=(f'offer_player = "{player}" AND ' +
                   'offer_status = "Winning"'))[0]

    except IndexError:
        last_id = 0
        last_user = None
        last_offer = 0

    # Se non c'è, gestisco la situazione in modo da presentare automaticamente
    # un'offerta a prezzo base oppure segnalare all'utente l'assenza di un'asta
    # attiva
    if not last_offer:
        private, group = prezzo_base_automatico(user,
                                                new_id,
                                                player,
                                                new_ab,
                                                active=True)
        return private, group

    # Se invece c'è allora ne confronto il valore con l'autobid che si sta
    # provando ad impostare. Se l'autobid è inferiore o uguale, lo elimino dal
    # db e lo segnalo all'user
    if new_ab <= last_offer:
        dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')

        return ("Valore autobid troppo basso. Impostare un valore superiore" +
                " all'attuale offerta vincente."), None

    # Se è superiore allora devo controllare che l'user dell'ultima offerta non
    # abbia impostato anche lui un autobid
    else:
        old_ab = dbf.db_select(table='autobids',
                               columns=[
                                   'autobid_id', 'autobid_nonce',
                                   'autobid_tag', 'autobid_value'
                               ],
                               where=(f'autobid_player = "{player}" AND ' +
                                      'autobid_status = "Confirmed"'))

        # Caso 1: non c'è autobid ed il detentore dell'offerta è un avversario.
        # In questo caso l'avversario perde l'offerta a favore del nuovo user.
        # Il valore della nuova offerta sarà automaticamente uguale ad 1
        # fantamilione in più rispetto alla precedente
        if not old_ab and user != last_user:

            dbf.db_update(table='offers',
                          columns=['offer_status'],
                          values=['Lost'],
                          where=f'offer_id = {last_id}')

            dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            pl_id = dbf.db_select(table='players',
                                  columns=['player_id'],
                                  where=f'player_name = "{player}"')[0]

            dbf.db_insert(
                table='offers',
                columns=[
                    'offer_user', 'offer_player', 'offer_player_id',
                    'offer_price', 'offer_dt', 'offer_status'
                ],
                values=[user, player, pl_id, last_offer + 1, dt, 'Winning'])

            # Cancello l'autobid nel caso venga raggiunto il suo valore
            if new_ab == last_offer + 1:
                dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')

                private = ('Hai dovuto utilizzare tutto il tuo autobid. ' +
                           'Reimposta un valore più alto nel caso volessi ' +
                           'continuare ad usarlo.' + cfg.SEPAR +
                           crea_riepilogo_autobid(user))
            else:
                dbf.db_update(table='autobids',
                              columns=['autobid_status'],
                              values=['Confirmed'],
                              where=f'autobid_id = {new_id}')

                private = ('Offerta aggiornata ed autobid impostato ' +
                           'correttamente.' + cfg.SEPAR +
                           crea_riepilogo_autobid(user))

            group = (f'<i>{user}</i> rilancia per <b>{player}</b>.' +
                     cfg.SEPAR + crea_riepilogo(dt))

            return private, group

        # Caso 2: non c'è autobid ed il detentore dell'offerta è lo stesso user.
        # In questo caso viene semplicemente impostato l'autobid
        elif not old_ab and user == last_user:

            dbf.db_update(table='autobids',
                          columns=['autobid_status'],
                          values=['Confirmed'],
                          where=f'autobid_id = {new_id}')

            return ('Autobid impostato correttamente.' + cfg.SEPAR +
                    crea_riepilogo_autobid(user)), None

        # Se c'è già un autobid si aprono altri possibili casi
        else:
            old_id, last_nonce, last_tag, last_value = old_ab[0]
            old_ab = int(
                dbf.decrypt_value(last_nonce, last_tag, last_value).decode())

            # Caso 3: il nuovo autobid supera il vecchio ed il detentore
            # dell'offerta è un avversario. Simile al Caso 1.
            # Il valore della nuova offerta sarà automaticamente uguale ad 1
            # fantamilione in più rispetto al precedente autobid
            if new_ab > old_ab and user != last_user:

                dbf.db_update(table='offers',
                              columns=['offer_status'],
                              values=['Lost'],
                              where=f'offer_id = {last_id}')

                dbf.db_delete(table='autobids', where=f'autobid_id = {old_id}')

                dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                pl_id = dbf.db_select(table='players',
                                      columns=['player_id'],
                                      where=f'player_name = "{player}"')[0]

                dbf.db_insert(
                    table='offers',
                    columns=[
                        'offer_user', 'offer_player', 'offer_player_id',
                        'offer_price', 'offer_dt', 'offer_status'
                    ],
                    values=[user, player, pl_id, old_ab + 1, dt, 'Winning'])

                if new_ab == old_ab + 1:
                    dbf.db_delete(table='autobids',
                                  where=f'autobid_id = {new_id}')

                    private = ('Hai dovuto utilizzare tutto il tuo autobid. ' +
                               'Reimposta un valore più alto nel caso ' +
                               'volessi continuare ad usarlo.' + cfg.SEPAR +
                               crea_riepilogo_autobid(user))
                else:
                    dbf.db_update(table='autobids',
                                  columns=['autobid_status'],
                                  values=['Confirmed'],
                                  where=f'autobid_id = {new_id}')

                    private = ('Offerta aggiornata ed autobid impostato ' +
                               'correttamente.' + cfg.SEPAR +
                               crea_riepilogo_autobid(user))

                group = (f'<i>{user}</i> rilancia ' + f'per <b>{player}</b>.' +
                         cfg.SEPAR + crea_riepilogo(dt))

                return private, group

            # Caso 4: il nuovo autobid supera il vecchio ed il detentore
            # dell'offerta è lo stesso user. Viene aggiornato l'autobid
            # precedente al nuovo valore più alto
            elif new_ab > old_ab and user == last_user:

                nonce, tag, value = dbf.encrypt_value(str(new_ab))
                dbf.db_update(
                    table='autobids',
                    columns=['autobid_nonce', 'autobid_tag', 'autobid_value'],
                    values=[nonce, tag, value],
                    where=f'autobid_id = {old_id}')

                dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')

                return (f'Hai aumentato il tuo autobid per {player} ' +
                        f'da {old_ab} a {new_ab}.' + cfg.SEPAR +
                        crea_riepilogo_autobid(user)), None

            # Caso 5: il nuovo autobid non supera il vecchio ed il detentore
            # dell'offerta è un avversario. Il nuovo autobid non viene
            # confermato e l'offerta del detentore viene aggiornata ad un
            # valore pari all'autobid tentato dall'user più 1 fantamilione
            elif new_ab < old_ab and user != last_user:

                dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')

                dbf.db_update(table='offers',
                              columns=['offer_price', 'offer_dt'],
                              values=[new_ab + 1, dt],
                              where=f'offer_id = {last_id}')

                if old_ab == new_ab + 1:
                    dbf.db_delete(table='autobids',
                                  where=f'autobid_id = {old_id}')

                private = 'Autobid troppo basso.'
                group = (f'<i>{user}</i> ha tentato un rilancio' +
                         f' per <b>{player}</b>.' + cfg.SEPAR +
                         crea_riepilogo(dt))

                return private, group

            # Caso 6: il nuovo autobid non supera il vecchio ed il detentore
            # dell'offerta è lo stesso user. Viene aggiornato l'autobid
            # precedente al nuovo valore più basso
            elif new_ab < old_ab and user == last_user:

                nonce, tag, value = dbf.encrypt_value(str(new_ab))
                dbf.db_update(
                    table='autobids',
                    columns=['autobid_nonce', 'autobid_tag', 'autobid_value'],
                    values=[nonce, tag, value],
                    where=f'autobid_id = {old_id}')

                dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')

                return (f'Hai diminuito il tuo autobid per {player} ' +
                        f'da {old_ab} a {new_ab}.' + cfg.SEPAR +
                        crea_riepilogo_autobid(user)), None

            # Caso 7: il nuovo autobid è uguale al vecchio ed il detentore
            # dell'offerta è un avversario. Viene convalidato quello del
            # detentore per averlo impostato in anticipo
            elif new_ab == old_ab and user != last_user:

                dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

                sex = dbf.db_select(table='teams',
                                    columns=['team_sex'],
                                    where=f'team_name = "{last_user}"')[0]

                dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')

                dbf.db_delete(table='autobids', where=f'autobid_id = {old_id}')

                dbf.db_update(table='offers',
                              columns=['offer_price', 'offer_dt'],
                              values=[new_ab, dt],
                              where=f'offer_id = {last_id}')

                private = (f"Autobid uguale a quello di {last_user}." +
                           " Ha la precedenza " + sex + " perché l'ha " +
                           "impostato prima.")
                group = (f'<i>{user}</i> ha tentato un rilancio' +
                         f' per <b>{player}</b>.' + cfg.SEPAR +
                         crea_riepilogo(dt))

                return private, group

            # Caso 8: il nuovo autobid è uguale al vecchio ed il detentore
            # dell'offerta è lo stesso user.
            elif new_ab == old_ab and user == last_user:
                dbf.db_delete(table='autobids', where=f'autobid_id = {new_id}')
                return 'Hai già impostato questo valore di autobid.', None
예제 #21
0
def get(update, context):
    """
    /get team       -> Return all quotes of the match, if found
    /get team_bet   -> Return the requested quote, if found
    /get team_quote -> Return all the bets with the specified quote, if found
    """

    args = context.args
    chat_id = update.message.chat_id
    text = ' '.join(args).upper()

    if utl.wrong_chat(chat_id=chat_id):
        message_id = update.message.message_id
        context.bot.deleteMessage(chat_id=chat_id, message_id=message_id)
        return context.bot.send_message(
            chat_id=utl.get_user_chat_id(update),
            text='Usa questo gruppo per i comandi.')

    if utl.wrong_format(input_text=text):
        message = ('Formato non corretto. ' +
                   'Ex:\n\t- /get squadra_pronostico\n\t- /get squadra')
        return context.bot.send_message(chat_id=chat_id, text=message)

    team = utl.fix_team_name(text.split('_')[0])
    if not team:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Squadra non riconosciuta')

    match_details = utl.get_match_details(team_name=team)
    if not match_details:
        return context.bot.send_message(
            chat_id=chat_id, text=f'Nessun match trovato per {team}')

    # If only team is sent, send all quotes of that match
    if '_' not in text:
        standard, combo = utl.all_bets_per_team(team_name=team)

        if not combo:
            return context.bot.send_message(chat_id=chat_id, text=standard)

        context.bot.send_message(parse_mode='MarkdownV2',
                                 chat_id=chat_id,
                                 text=f'`{standard}`')
        return context.bot.send_message(parse_mode='MarkdownV2',
                                        chat_id=chat_id,
                                        text=f'`{combo}`')

    # Try to recognize the bet sent by user
    bet = text.split('_')[1]
    bet = utl.fix_bet_name(bet)
    if not bet:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Pronostico non riconosciuto')

    # Extract match details
    match_id, league, team1, team2, dt, _ = match_details[0]
    team1 = team1.replace('*', '')
    team2 = team2.replace('*', '')

    quote = utl.get_bet_quote(match_id=match_id, bet_name=bet)
    if not quote:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Pronostico non quotato')

    bet_id = utl.get_pending_bet_id()
    if not bet_id:
        bet_id = utl.insert_new_bet_entry()

    # Insert prediction as "Not Confirmed"
    user = utl.get_nickname(update)
    pred_id = dbf.db_insert(table='predictions',
                            columns=[
                                'bet_id', 'user', 'date', 'team1', 'team2',
                                'league', 'bet_alias', 'quote', 'status'
                            ],
                            values=[
                                bet_id, user, dt, team1, team2, league, bet,
                                quote, 'Not Confirmed'
                            ],
                            last_index=True)

    # Remove other pending predictions the user might have
    dbf.db_delete(table='predictions',
                  where=(f'id != {pred_id} AND user = "******" AND ' +
                         'status = "Not Confirmed"'))

    # Ask user for confirmation
    bet_details = '{} - {} {} @{}'.format(team1, team2, bet, quote)
    message = f'{bet_details}\n\n/confirm                /cancel'
    return context.bot.send_message(chat_id=chat_id, text=message)
예제 #22
0
def message_with_payment(user, user_input, offers_user):
    """
	Crea il messaggio di riepilogo del pagamento.
	Utilizzato all'interno della funzione pago().

	:param user: str, nome della fantasquadra
	:param user_input: list, [giocatore da pagare, metodo di pagamento]
	:param offers_user: list, tutte le offerte dell'user in stato Not Official

	:return money_db: list, user_input dopo la correzioni dei nomi
	:return message: str, messaggio di riepilogo

	"""

    rosa = dbf.db_select(table='players',
                         columns_in=['player_name'],
                         where='player_status = "{}"'.format(user))

    pls = []
    money = 0
    message = ''

    for i in user_input:
        try:
            money = int(i)
        except ValueError:
            pls.append(i)

    new_pls = []
    for i, pl in enumerate(pls):
        if not i:
            pl2 = ef.jaccard_player(pl, offers_user)

            off_id, price = dbf.db_select(
                table='offers',
                columns_in=['offer_id', 'offer_price'],
                where='offer_player = "{}"'.format(pl2))[-1]

            dbf.db_insert(
                table='pays',
                columns=['pay_user', 'pay_offer', 'pay_player', 'pay_price'],
                values=[user, off_id, pl2, price])

            team, roles = dbf.db_select(
                table='players',
                columns_in=['player_team', 'player_roles'],
                where='player_name = "{}"'.format(pl2))[0]

            message = (
                '<i>{}</i> ufficializza:\n\n\t\t\t\t\t\t'.format(user) +
                '<b>{}</b> <i>({})   {}</i>\n\n'.format(pl2, team, roles) +
                'Prezzo: <b>{}</b>.\n\nPagamento:\n'.format(price))

        else:
            pl2 = ef.jaccard_player(pl, rosa)
            tm, rls, pr = dbf.db_select(
                table='players',
                columns_in=['player_team', 'player_roles', 'player_price'],
                where='player_name = "{}"'.format(pl2))[0]

            new_pls.append((pl2, tm, rls, pr))

    money_db = ', '.join(
        ['{} ({}: {})'.format(el[0], el[1], el[3]) for el in new_pls])
    if money and len(new_pls):
        money_db += ', {}'.format(money)
    elif money:
        money_db += '{}'.format(money)

    for pl, tm, rl, pr in new_pls:
        message += '\n\t\t- <b>{}</b> <i>({})   {}</i>   {}'.format(
            pl, tm, rl, pr)
    if money:
        message += '\n\t\t- <b>{}</b>'.format(money)

    return money_db, message + '\n\n/conferma_pagamento'