Пример #1
0
def get_rid_outdated_matches(bot):

    preds_to_remove = dbf.db_select(table='to_play',
                                    columns=['pred_id', 'date'],
                                    where='')

    preds_to_remove = [(pred_id, utl.str_to_dt(dt_as_string=pred_dt))
                       for pred_id, pred_dt in preds_to_remove]

    preds_to_remove = [
        pred_id for pred_id, pred_dt in preds_to_remove
        if pred_dt < datetime.datetime.now()
    ]

    for pred_id in preds_to_remove:
        dbf.db_delete(table='to_play', where=f'pred_id={pred_id}')

        bet_id = dbf.db_select(table='predictions',
                               columns=['bet_id'],
                               where=f'id = {pred_id}')[0]
        bet_status = dbf.db_select(table='bets',
                                   columns=['status'],
                                   where=f'id = {bet_id}')[0]

        if bet_status == 'Pending':
            dbf.db_delete(table='predictions', where=f'id={pred_id}')

    utl.remove_bet_without_preds()
Пример #2
0
def only_compatible_schemes(list_of_roles: list, players_needed: int,
                            scheme_to_exclude) -> list:

    all_schemes = dbf.db_select(table='schemes_details',
                                columns=['scheme'],
                                where=f'scheme != "{scheme_to_exclude}"')

    # First of all we need to remove all those schemes whose number of
    # defenders is not compatible with the roles in field
    all_schemes = [
        sch for sch in all_schemes
        if enough_defenders(players_needed=players_needed,
                            list_of_roles=list_of_roles,
                            scheme_used=sch)
    ]

    # Then we do the same considering the number of attackers
    res = []
    n_pc = count_roles(['Pc'], list_of_roles)
    for sch in all_schemes:
        rl_in_scheme = dbf.db_select(
            table='schemes_details',
            columns=['details'],
            where=f'scheme = "{sch}"')[0].split(', ')[1:]

        # To be a compatible scheme it must at least equal the number of
        # attackers playing
        if count_roles(['A/Pc'], rl_in_scheme) >= n_pc:
            res.append(sch)
    return res
Пример #3
0
def calculate_all_malus(player: str) -> float:
    """
	Calculate total malus for player.
	"""

    minus05 = dbf.db_select(table='votes',
                            columns=['amm'],
                            where=f'name = "{player}"')
    minus05 = sum(minus05) * .5

    minus1 = dbf.db_select(table='votes',
                           columns=['gs', 'esp'],
                           where=f'name = "{player}"')
    minus1 = sum([sum(i) for i in minus1])

    minus2 = dbf.db_select(table='votes',
                           columns=['au'],
                           where=f'name = "{player}"')
    minus2 = sum(minus2) * 2

    minus3 = dbf.db_select(table='votes',
                           columns=['rs'],
                           where=f'name = "{player}"')
    minus3 = sum(minus3) * 3

    return minus05 + minus1 + minus2 + minus3
Пример #4
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])
Пример #5
0
def quotes_rec() -> tuple:

    data = dbf.db_select(table='predictions',
                         columns=['user', 'quote'],
                         where='label = "WINNING"')
    data.sort(key=lambda x: x[1], reverse=True)
    quote = data[0][1]
    users = []
    for n, q in data:
        if q == quote:
            users.append(n)
        else:
            break

    win = (quote, '/'.join(users))

    data = dbf.db_select(table='predictions',
                         columns=['user', 'quote'],
                         where='label = "LOSING"')
    data.sort(key=lambda x: x[1])
    quote = data[0][1]
    users = []
    for n, q in data:
        if q == quote:
            users.append(n)
        else:
            break

    lose = (quote, '/'.join(users))

    return win, lose
Пример #6
0
    def __init__(self, fteams, a_round, n_days, all_players, captain, rfactor):
        """
		:param fteams: list, Ex [Ciolle United, FC STRESS, ...]
		:param a_round: list
		:param n_days: int
		:param all_players: dict, Ex: player_name: Player() instance
		:param captain: bool
		:param rfactor: bool

		"""
        self.fteams = {ft: Fantateam(ft) for ft in fteams}
        self.a_round = a_round
        self.n_days = n_days
        self.all_players = all_players
        self.captain = captain
        self.captain_details = dict(
            dbf.db_select(table='captain_details', columns=['*'], where=''))
        self.rfactor = rfactor
        self.rfactor_details = dict(
            dbf.db_select(table='rfactor_details', columns=['*'], where=''))
        self.schedule = ef.generate_schedule(a_round, self.n_days)
        self.matches = []

        self.play_league()
        self.ranking = None
Пример #7
0
def aggiorna_offerte_chiuse(dt_now, return_offers=False):
    """
	Confronta i tempi trascorsi da ogni offerta e chiude quelle che hanno già
	raggiunto o superato le 24 ore necessarie.
	Utilizzata all'interno di confermo_autobid(), confermo_offerta(),
	crea_riepilogo(), offro() e pago().

	:param dt_now: datetime, data e ora attuale
	:param return_offers: bool

	:return offers_win: list, contiene le offerte ancora aperte
	:return offers_no: list, contiene le offerte chiuse e non ufficializzate

	"""

    offers_win = dbf.db_select(table='offers',
                               columns=[
                                   'offer_id', 'offer_user', 'offer_player',
                                   'offer_price', 'offer_dt'
                               ],
                               where='offer_status = "Winning"')

    offers_no = dbf.db_select(table='offers',
                              columns=[
                                  'offer_id', 'offer_user', 'offer_player',
                                  'offer_price', 'offer_dt'
                              ],
                              where='offer_status = "Not Official"')

    # Se tra le offerte aperte ce n'è qualcuna per la quale sono già scadute
    # le 24 ore allora il suo status viene modificato a 'Not Official' ed
    # elimina eventuali autobids attivi per quel calciatore
    for of_id, tm, pl, pr, dt in offers_win:
        dt2 = datetime.strptime(dt, '%Y-%m-%d %H:%M:%S')
        diff = dt_now - dt2
        if diff.total_seconds() > cfg.TIME_WINDOW1:
            offers_no.append((of_id, tm, pl, pr, dt))
            dbf.db_update(table='offers',
                          columns=['offer_status'],
                          values=['Not Official'],
                          where=f'offer_id = {of_id}')
            dbf.db_update(table='players',
                          columns=['player_status'],
                          values=[tm],
                          where=f'player_name = "{pl}"')
            dbf.db_delete(table='autobids', where=f'autobid_player = "{pl}"')

    if return_offers:

        # Ridefinisco le due liste trasformando le stringhe in oggetti datetime
        offers_win = [(el[0], el[1], el[2], el[3],
                       datetime.strptime(el[4], '%Y-%m-%d %H:%M:%S'))
                      for el in offers_win if el not in offers_no]

        offers_no = [(el[0], el[1], el[2], el[3],
                      datetime.strptime(el[4], '%Y-%m-%d %H:%M:%S'))
                     for el in offers_no]

        return offers_win, offers_no
Пример #8
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')
Пример #9
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)
Пример #10
0
def get_bet_quote(match_id: int, bet_name: str) -> float:

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

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

    return quote[0] if quote else 0.0
Пример #11
0
def remove_matches_without_quotes():
    """
    Sometimes it happens when matches are postponed, for example.
    """
    ids_in_quotes = set(
        dbf.db_select(table='quotes', columns=['match'], where=''))
    ids_in_matches = set(
        dbf.db_select(table='matches', columns=['id'], where=''))
    missing = ids_in_matches - ids_in_quotes
    for miss in missing:
        dbf.db_delete(table='matches', where=f'id = {miss}')
Пример #12
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
Пример #13
0
def prezzo(bot, update, args):
    """
	Restituisce il prezzo di un calciatore.

	: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')

    args = ''.join(args).split(',')

    if len(args) != 2:
        return bot.send_message(chat_id=chat_id,
                                text=('Formato non corretto.\n' +
                                      'Ex: /prezzo higuain, milan'))

    pl, tm = args

    tm = ef.jaccard_result(
        tm, dbf.db_select(table='players', columns=['player_team']), 3)
    if not tm:
        return bot.send_message(chat_id=chat_id,
                                text='Squadra non riconosciuta, riprova.')

    pl = ef.jaccard_result(
        pl,
        dbf.db_select(table='players',
                      columns=['player_name'],
                      where=f'player_team = "{tm}"'), 3)
    if not pl:
        return bot.send_message(chat_id=chat_id,
                                text='Calciatore non riconosciuto, riprova.')

    rl, pr, st = dbf.db_select(
        table='players',
        columns=['player_roles', 'player_price', 'player_status'],
        where=f'player_name = "{pl}"')[0]

    if st == 'FREE':
        st = 'Svincolato'

    message = (f'\t\t\t\t<b>{pl}</b> <i>({tm})   {rl}</i>\n\n' +
               f'Squadra: <i>{st}</i>\nPrezzo: <b>{pr}</b>')

    return bot.send_message(parse_mode='HTML', chat_id=chat_id, text=message)
Пример #14
0
def start_asta():
    print('Type PLAYER_NAME, FANTATEAM, PRICE:')

    try:
        nm, tm, pr = input().split(',')
        pr = int(pr.strip())
    except ValueError:
        print('WRONG FORMAT')
        return start_asta()

    all_nm = dbf.db_select(table='players',
                           columns=['name'],
                           where='status = "FREE"',
                           database=cfa.DB_NAME)
    names = jaccard_result(name_to_fix=nm, all_options=all_nm, ngrams_lenght=3)

    all_tm = dbf.db_select(table='teams',
                           columns=['team_name'],
                           where='',
                           database=cfa.DB_NAME)
    tm = jaccard_result(name_to_fix=tm, all_options=all_tm, ngrams_lenght=3)[0]

    for opt in names:
        real_team, roles = dbf.db_select(table='players',
                                         columns=['team', 'roles'],
                                         where=f'name = "{opt}"',
                                         database=cfa.DB_NAME)[0]
        real_team = real_team[:3].upper()

        print(f'{opt} ({real_team}\t{roles})\t\t{tm}\t\t{pr}')
        print(('ENTER to confirm, SPACE to cancel, '
               'any letter if player is wrong.'))
        answer = input()
        if not answer:
            too_low, min_price = offer_is_too_low(player_name=opt,
                                                  offer_value=pr)
            if too_low:
                print(f'DENIED. Min price is {min_price}.')
            else:
                dbf.db_update(table='players',
                              columns=['status'],
                              values=[tm],
                              where=f'name = "{opt}"',
                              database=cfa.DB_NAME)
                update_excel(winner_team=tm, pl_name=opt, pl_team=real_team,
                             pl_roles=roles, pl_price=pr)
                with open('logs_asta.txt', 'a') as f:
                    f.write(f'{opt}, {real_team}, {roles}, {tm}, {pr}\n')
            return start_asta()
        elif answer == ' ':
            return start_asta()
        else:
            continue
Пример #15
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')
Пример #16
0
    def play_match(self):
        """
		Define lineups and call update_fantateams_data() to update all the
		attributes of each fantateam.
		To make it faster, lineups are defined in two ways depending on the
		case:

			1. First we look in the database in the 'mantra_lineups' table to
			   check if they have been already calculated.

			2. If not found we run the mantra algorithm to calculate them.

		:return: nothing

		"""

        # To save time, try to find mantra lineups already calculated
        try:
            lineup1 = dbf.db_select(
                table='mantra_lineups',
                columns=[f'day_{self.day}'],
                where=f'team_name="{self.team1.name}"')[0].split(', ')
            malus1 = int(lineup1[0])
            lineup1 = [tuple(el.split(':')) for el in lineup1[1:]]

            lineup2 = dbf.db_select(
                table='mantra_lineups',
                columns=[f'day_{self.day}'],
                where=f'team_name="{self.team2.name}"')[0].split(', ')
            malus2 = int(lineup2[0])
            lineup2 = [tuple(el.split(':')) for el in lineup2[1:]]

            # malus1 = sum([1 for nm, rl in lineup1 if '*' in rl])
            # malus2 = sum([1 for nm, rl in lineup2 if '*' in rl])

            lineup1 = [nm for nm, rl in lineup1]
            lineup2 = [nm for nm, rl in lineup2]

        # if not found, calculate them with mantra algorithm
        except IndexError:
            lineup1, _, malus1 = mf.mantra(day=self.day,
                                           fantateam=self.team1.name,
                                           starting_players=10)
            lineup2, _, malus2 = mf.mantra(day=self.day,
                                           fantateam=self.team2.name,
                                           starting_players=10)

        self.update_fantateams_data(lineup1, lineup2, malus1, malus2)
Пример #17
0
def all_bets_per_team(team_name: str) -> str:
    """
    Return a message with all the bets for the selected team.
    """

    match_id, _, team1, team2, *_ = get_match_details(team_name=team_name)[0]

    team1 = team1.replace('*', '')
    team2 = team2.replace('*', '')

    quotes = dbf.db_select(table='quotes',
                           columns=['bet', 'quote'],
                           where=f'match = {match_id}')
    standard = [(b, q) for b, q in quotes if '+' not in b]
    standard = bet_mapping(standard)
    combo = [(b, q) for b, q in quotes if '+' in b]
    combo = bet_mapping(combo)

    message_standard = f'{team1} - {team2}'
    for field in standard:
        message_standard += f'\n\n{field}\n\n'
        for b, q in standard[field]:
            message_standard += adjust_text_width(f'\t\t\t- {b}: {q}\n', 30)

    message_combo = ''
    for field in combo:
        message_combo += f'\n\n{field}\n\n'
        for b, q in combo[field]:
            message_combo += adjust_text_width(f'\t\t\t- {b}: {q}\n', 30)

    return message_standard, message_combo
Пример #18
0
def notify_inactive_fields() -> str:
    all_fields = dbf.db_select(table='fields', columns=['name'], where='')
    all_fields = [f.split('_')[0] for f in all_fields]

    fields_found = dbf.db_select(table='quotes', columns=['bet'], where='')
    fields_found = [f.split('_')[0] for f in fields_found]

    missing = set(all_fields) - set(fields_found)

    if missing:
        missing = sorted(list(missing))

        message = "\n\t\t\t- ".join(missing)
        return f'Scommesse mancanti:\n\n\t\t\t- {message}'
    else:
        return ''
Пример #19
0
def get_user_chat_id(update) -> int:

    name = update.message.from_user.first_name
    chat_id = dbf.db_select(table='people',
                            columns=['chat_id'],
                            where=f'name = "{name}"')[0]
    return chat_id
Пример #20
0
def get_placed_but_open_bet_ids() -> list:

    bet_ids = dbf.db_select(table='bets',
                            columns=['id'],
                            where='status = "Placed" AND result = "Unknown"')

    return bet_ids
Пример #21
0
def get_nickname(update) -> str:

    name = update.message.from_user.first_name
    nickname = dbf.db_select(table='people',
                             columns=['nick'],
                             where=f'name = "{name}"')[0]
    return nickname
Пример #22
0
def create_abs_points_dict(fteams, n_days):
    """
	Create a dict with each fantateam's abs_points day by day.

	:param fteams: list, Ex. ['Ciolle United', ' FC STRESS', ...]
	:param n_days: int

	:return: dict, Ex. {'Ciolle United': [67.5, 72, 68, ...],
						'FC STRESS': [72, 70.5, 64, ...], ...}

	"""

    abs_points = {tm: None for tm in fteams}

    for tm in abs_points:
        p = dbf.db_select(
            table='absolute_points',
            columns=[f'day_{day}' for day in range(1, n_days + 1)],
            where=f'team_name="{tm}"')[0]
        if type(p) == tuple:
            abs_points[tm] = p
        else:
            abs_points[tm] = [p]

    return abs_points
Пример #23
0
    def for_teams(label):

        teams = dbf.db_select(table='predictions',
                              columns=['team1', 'team2'],
                              where=f'label = "{label}"')

        return pd.Series(np.array(teams).flatten()).value_counts().to_dict()
Пример #24
0
    def for_bets(label):

        bets = dbf.db_select(table='predictions',
                             columns=['bet_alias'],
                             where=f'label = "{label}"')

        return pd.Series(np.array(bets).flatten()).value_counts().to_dict()
Пример #25
0
def crea_riepilogo_autobid(user):
    """
	Crea il messaggio di riepilogo degli autobid attivi dell'user.
	Utilizzata dentro riepilogo_autobid().

	:param user: str, fantasquadra

	:return: str, messaggio in chat

	"""

    autobids = dbf.db_select(
        table='autobids',
        columns=[
            'autobid_player', 'autobid_nonce', 'autobid_tag', 'autobid_value'
        ],
        where=f'autobid_user = "******" AND autobid_status = "Confirmed"')
    if not autobids:
        return 'Nessun autobid attivo.'

    message = 'I tuoi autobid attivi sono:\n\n'
    for pl, nonce, tag, encr_ab in autobids:
        decr_ab = int(dbf.decrypt_value(nonce, tag, encr_ab).decode())
        message += f'\t\t\t\t<b>{pl}</b>: {decr_ab}\n'

    return message
Пример #26
0
def get_league_url(league_name: str) -> str:

    league = fix_league_name(league_name)
    url = dbf.db_select(table='leagues',
                        columns=['url'],
                        where=f'name = "{league}"')[0]
    return url
Пример #27
0
def captain_points(captain_true_false, fantateam_name, lineup, day,
                   captain_details):
    """
	Return the bonus/malus points associated with the vote of the captain.

	:param captain_true_false: bool
	:param fantateam_name: str
	:param lineup: list
	:param day: int
	:param captain_details: dict

	:return: float

	"""

    if not captain_true_false:
        return 0

    text = dbf.db_select(table='captains',
                         columns=[f'day_{day}'],
                         where=f'team_name = "{fantateam_name}"')[0]
    captain, vice = text.split(', ')

    if captain in lineup:
        vote = players[captain].vote(day)
    elif vice in lineup:
        vote = players[vice].vote(day)
    else:
        vote = 'sv'

    return captain_details[vote]
Пример #28
0
def message_with_offers(list_of_offers, shift, dt_now, msg):
    """
	Crea il messaggio di riepilogo delle offerte.
	Utilizzata dentro crea_riepilogo().

	:param list_of_offers: list, ogni tuple è un'offerta
	:param shift: int, per calcolare lo shift in secondi e il tempo rimanente
	:param dt_now: datetime, data e ora attuali
	:param msg: str, messaggio da completare

	:return msg: str, messaggio finale

	"""

    for _, tm, pl, pr, dt in list_of_offers:
        team, roles = dbf.db_select(table='players',
                                    columns=['player_team', 'player_roles'],
                                    where=f'player_name = "{pl}"')[0]
        dt_plus = dt + timedelta(seconds=shift)
        diff = (dt_plus - dt_now).total_seconds()
        if diff < 0:
            diff = abs(diff)
            hh = -int(diff // 3600)
            mm = int((diff % 3600) // 60)
        else:
            hh = int(diff // 3600)
            mm = int((diff % 3600) // 60)

        msg += (f'\n\t\t- <b>{pl}</b> ({team}) {roles}:' +
                f' {pr}, <i>{tm}</i>   <b>{hh}h:{mm}m</b>')

    return msg
Пример #29
0
def correggi_file_asta():
    """
	Crea una copia del file originale contenente le rose definite il giorno
	dell'asta ma con i nomi dei calciatori corretti secondo il formato di
	Fantagazzetta.

	"""

    asta = pd.read_excel(os.getcwd() + '/Asta{}.xlsx'.format(anno),
                         header=0,
                         sheet_name="Foglio1")
    players = dbf.db_select(database=dbase,
                            table='players',
                            columns_in=['player_name', 'player_team'],
                            dataframe=True)

    for i in range(0, len(asta.columns), 3):
        temp_pl = asta[asta.columns[i:i + 3]].dropna()
        for j in range(len(temp_pl)):
            pl, tm = temp_pl.loc[j, temp_pl.columns[0:2]]
            flt_df = players[players['player_team'] == tm.upper()]
            names = flt_df['player_name'].values
            correct_pl = jaccard_result(pl, names, 3)
            asta.loc[
                j,
                [asta.columns[i], asta.columns[i +
                                               1]]] = correct_pl, tm.upper()

    writer = ExcelWriter('Asta{}_2.xlsx'.format(anno), engine='openpyxl')
    asta.to_excel(writer, sheet_name='Foglio1')
    writer.save()
    writer.close()
Пример #30
0
def autoplay() -> bool:

    bet_id = get_pending_bet_id()
    preds = dbf.db_select(table='predictions',
                          columns=['id'],
                          where=f'bet_id = {bet_id} AND status = "Confirmed"')
    return True if len(preds) == cfg.N_BETS else False