コード例 #1
0
def delete(update, context):
    """
    Delete the 'Confirmed' match from 'predictions' table.
    """

    chat_id = update.message.chat_id
    user = utl.get_nickname(update)

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

    pred_to_delete = utl.prediction_to_delete(nickname=user)
    if not pred_to_delete:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Nessun pronostico da eliminare')

    dbf.db_delete(table='predictions', where=f'id = {pred_to_delete}')

    dbf.db_delete(table='to_play', where=f'pred_id = {pred_to_delete}')

    utl.remove_bet_without_preds()

    context.bot.send_message(chat_id=chat_id, text='Pronostico eliminato')

    # Send summary in group chat
    summary_updated = utl.create_summary_pending_bet()
    return context.bot.send_message(
        parse_mode='HTML',
        chat_id=cfg.GROUP_ID,
        text=f'Pronostico eliminato.\n\n{summary_updated}')
コード例 #2
0
def confermo_eliminazione(bot, update):
    """
	Elimina definitivamente dal db l'autobid scelto.
	Utilizzata all'ainterno di elimino_autobid().

	:param bot:
	:param update:

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

    ab_to_delete = dbf.db_select(table='elimina',
                                 columns=['elimina_ab'],
                                 where=f'elimina_user = "******"')
    if not ab_to_delete:
        return bot.send_message(chat_id=chat_id,
                                text='Non hai autobid da eliminare.')

    dbf.db_delete(table='autobids', where=f'autobid_id = {ab_to_delete[0]}')

    dbf.db_delete(table='elimina', where=f'elimina_ab = {ab_to_delete[0]}')

    message = 'Autobid eliminato' + cfg.SEPAR + utl.crea_riepilogo_autobid(
        user)

    return bot.send_message(parse_mode='HTML', chat_id=chat_id, text=message)
コード例 #3
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()
コード例 #4
0
def cancel(update, context, text: str = ''):
    """
    Delete the 'Not Confirmed' match from 'predictions' table.
    """

    chat_id = update.message.chat_id
    user = utl.get_nickname(update)

    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.nothing_pending(nickname=user):
        return context.bot.send_message(chat_id=chat_id,
                                        text='Nessun pronostico da eliminare')

    dbf.db_delete(table='predictions',
                  where=f'user = "******" AND status = "Not Confirmed"')
    utl.remove_bet_without_preds()

    if not text:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Pronostico eliminato')
    else:
        return context.bot.send_message(chat_id=chat_id, text=text)
コード例 #5
0
ファイル: utils.py プロジェクト: alaporta85/FantAstaBot
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
コード例 #6
0
ファイル: utils.py プロジェクト: alaporta85/FantAstaBot
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
コード例 #7
0
def remove_expired_match_quotes() -> None:

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

    for match_id in match_ids:
        if match_already_started(table='matches', match_id=match_id):
            dbf.db_delete(table='matches', where=f'id = {match_id}')
            dbf.db_delete(table='quotes', where=f'match = {match_id}')
コード例 #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 remove_bet_without_preds() -> None:

    bet_id = get_pending_bet_id()
    if bet_id:
        preds = dbf.db_select(table='predictions',
                              columns=['id'],
                              where=f'bet_id = {bet_id}')
        if not preds:
            dbf.db_delete(table='bets', where=f'id = {bet_id}')
コード例 #10
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)
コード例 #11
0
def remove_existing_match_quotes(team_one: str, team_two: str) -> None:

    match_ids = dbf.db_select(
        table='matches',
        columns=['id'],
        where=f'team1 = "{team_one}" AND team2 = "{team_two}"')
    if match_ids:
        for m_id in match_ids:
            dbf.db_delete(table='matches', where=f'id = {m_id}')
            dbf.db_delete(table='quotes', where=f'match = {m_id}')
コード例 #12
0
def scrape_results() -> None:

	brow = sf.open_browser()
	brow.get(cfg.URL)

	close_all_headers(browser=brow)
	top_headers = active_top_headers(browser=brow)

	for top_header in top_headers:

		if league_is_correct(header=top_header):
			league = get_league(header=top_header)
			all_teams = dbf.db_select(table='simulations',
			                          columns=['team1', 'team2'],
			                          where=f'league = "{league}"')
			all_teams = [tm for match in all_teams for tm in match]
			all_teams = list(set(all_teams))
			click_expander(browser=brow, header=top_header)
			matches = get_matches(browser=brow)

			for match in matches:
				match_info = matches_info(match_elem=match)

				status, tm1, ggtm1, ggtm2, tm2, pt = match_info

				team1, team2 = get_teams(all_teams=all_teams,
				                         team1_name=tm1,
				                         team2_name=tm2)

				if not correct_match_is_found(tm1_name=team1, tm2_name=team2):
					# TODO do something
					continue

				if status != 'Finale':
					dbf.db_delete(table='simulations',
					              where=(f'team1 = "{team1}" AND '
					                     f'team2 = "{team2}"'))
					continue

				(ggtm1pt, ggtm2pt,
				 ggtm1st, ggtm2st) = goal_details(goals_tm1=ggtm1,
				                                  goals_tm2=ggtm2,
				                                  pt_info=pt)

				dbf.db_update(table='simulations',
				              columns=['goals_tm1_pt', 'goals_tm2_pt',
				                       'goals_tm1_st', 'goals_tm2_st'],
				              values=[ggtm1pt, ggtm2pt, ggtm1st, ggtm2st],
				              where=(f'team1 = "{team1}" AND '
				                     f'team2 = "{team2}" AND '
				                     'label is NULL'))

			click_expander(browser=brow, header=top_header)

	brow.close()
コード例 #13
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}')
コード例 #14
0
def remove_pending_same_match(nickname: str):

    team1, team2 = dbf.db_select(
        table='predictions',
        columns=['team1', 'team2'],
        where=f'user = "******" AND status = "Not Confirmed"')[0]

    cond1 = f'team1 = "{team1}" AND team2 = "{team2}"'
    cond2 = f'user != "{nickname}"'
    cond3 = 'status = "Not Confirmed"'
    dbf.db_delete(table='predictions',
                  where=f'{cond1} AND {cond2} AND {cond3}')
コード例 #15
0
def delete_not_conf_offers_by_user(user):

    try:
        old_id = dbf.db_select(table='offers',
                               columns_in=['offer_id'],
                               where='offer_user = "******" '.format(user) +
                               'AND offer_status IS NULL')[0]

        dbf.db_delete(table='offers', where='offer_id = {}'.format(old_id))

    except IndexError:
        pass
コード例 #16
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)
コード例 #17
0
def delete_not_conf_offers_by_others(player_id, user):

    try:
        old_ids = dbf.db_select(
            table='offers',
            columns_in=['offer_id'],
            where='offer_player_id = {} '.format(player_id) +
            'AND offer_status IS NULL AND ' +
            'offer_user != "{}"'.format(user))

        for old_id in old_ids:
            dbf.db_delete(table='offers', where='offer_id = {}'.format(old_id))

    except IndexError:
        pass
コード例 #18
0
def pago(bot, update, args):
    """
	Aggiorna la tabella "pays" del db con lo status di "Not Confirmed".

	: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 i pagamenti precedenti non confermati dall'utente
    dbf.db_delete(table='pays',
                  where=f'pay_user = "******" AND pay_status IS NULL')

    # Controllo che il formato sia corretto
    result = utl.check_pago_format(args)
    if type(result) == str:
        return bot.send_message(chat_id=chat_id, text=result)
    else:
        acquisto, pagamento = result

    # Creo il messaggio di conferma ed aggiorno il db con il pagamento
    # provvisorio
    result = utl.message_with_payment(user, acquisto, pagamento)
    if type(result) == str:
        return bot.send_message(chat_id=chat_id, text=result)
    else:
        money_db, message = result

    dbf.db_update(table='pays',
                  columns=['pay_money'],
                  values=[money_db],
                  where=f'pay_user = "******" AND pay_status IS NULL')

    return bot.send_message(parse_mode='HTML', chat_id=chat_id, text=message)
コード例 #19
0
def remove_not_confirmed_before_play() -> str:
    bet_id = get_pending_bet_id()
    if not bet_id:
        return ''

    where = f'bet_id = {bet_id} AND status = "Not Confirmed"'

    pending = dbf.db_select(table='predictions',
                            columns=['team1', 'team2'],
                            where=where)

    dbf.db_delete(table='predictions', where=where)

    pend_message = ''
    for team1, team2 in pending:
        pend_message += f'{team1}-{team2} eliminata perché non confermata.\n'

    return pend_message
コード例 #20
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])
コード例 #21
0
ファイル: fix_teams_names.py プロジェクト: alaporta85/bet_bot
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}"')
コード例 #22
0
def remove_too_late_before_play() -> str:

    preds = dbf.db_select(table='to_play', columns=['*'], where='')
    too_late_ids = []
    dt_now = datetime.datetime.now()
    for pred_id, _, dt, *_ in preds:
        if str_to_dt(dt) <= dt_now:
            too_late_ids.append(pred_id)

    too_late_message = ''
    for pred_id in too_late_ids:
        team1, team2 = dbf.db_select(table='predictions',
                                     columns=['team1', 'team2'],
                                     where=f'id = {pred_id}')[0]
        too_late_message += f'{team1}-{team2} già iniziata.\n'

        dbf.db_delete(table='to_play', where=f'pred_id = {pred_id}')
        dbf.db_delete(table='predictions', where=f'id = {pred_id}')
    remove_bet_without_preds()

    return too_late_message
コード例 #23
0
def confermo_offerta(bot, update):
    """
	Conferma l'offerta effettuata (se valida) ed aggiorna il db di conseguenza.
	Infine manda un messaggio in chat con tutte le offerte aperte e chiuse.

	:param bot:
	:param update:

	: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')
    if cfg.BLOCK:
        group_id = cfg.POLPS_ID
    else:
        group_id = cfg.FANTA_ID

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

    # Controllo che ci siano offerte da confermare
    try:
        of_id, pl = utl.select_offer_to_confirm(user)
    except TypeError:
        return bot.send_message(chat_id=chat_id,
                                text=f'Nulla da confermare per {user}')

    # Controllo che il calciatore sia svincolato
    if utl.non_svincolato(pl):
        dbf.db_delete(table='offers',
                      where=(f'offer_user = "******" AND ' +
                             'offer_status IS NULL'))
        return bot.send_message(
            chat_id=chat_id,
            text=f'Giocatore non svincolato ({utl.non_svincolato(pl)}).')

    # Controllo che non si tratti di autorilancio
    if utl.autorilancio(user, pl):
        dbf.db_delete(table='offers',
                      where=f'offer_user = "******" AND offer_status IS NULL')
        return bot.send_message(chat_id=chat_id,
                                text="L'ultima offerta è già tua.")

    # Controllo che l'offerta superi l'ultimo rilancio ed eventuali autobids
    result = utl.check_offer_value(user, of_id, pl, dt)

    if type(result) == str:
        return bot.send_message(chat_id=chat_id, text=result)
    else:
        # Elimino eventuali offerte non confermate da altri user per lo stesso
        # calciatore
        dbf.db_delete(
            table='offers',
            where=f'offer_player = "{pl}" AND offer_status IS NULL AND ' +
            f'offer_user != "{user}"')

        pvt, grp = result
        bot.send_message(chat_id=chat_id, text=pvt)
        return bot.send_message(parse_mode='HTML', chat_id=group_id, text=grp)
コード例 #24
0
def check_offer_value(offer_id, player, dt):
    """
	Controlla se l'offerta è valida. Nell'ordine controlla:

		- In caso di rilancio, se è troppo tardi per farlo
		- In caso di rilancio, se l'offerta supera quella già presente
		- In caso di prima offerta, se il valore offerto è sufficiente

	Utilizzata all'interno di conferma_offerta().

	:param offer_id: int, id dell'offerta
	:param player: str, nome del giocatore
	:param dt: str, data ed ora attuali

	:return last_id: int, l'id dell'offerta più recente per questo giocatore.
					 0 nel caso non si tratti di rilancio ma di prima offerta.

	"""

    offer = dbf.db_select(table='offers',
                          columns_in=['offer_price'],
                          where='offer_id = {}'.format(offer_id))[0]

    price = dbf.db_select(table='players',
                          columns_in=['player_price'],
                          where='player_name = "{}"'.format(player))[0]

    try:
        cond1 = 'offer_player = "{}" AND offer_status = "Winning"'.format(
            player)
        cond2 = 'offer_player = "{}" AND offer_status = "Not Official"'.format(
            player)

        last_id, last_user, last_offer, last_dt = dbf.db_select(
            table='offers',
            columns_in=[
                'offer_id', 'offer_user', 'offer_price', 'offer_datetime'
            ],
            where='{} OR {}'.format(cond1, cond2)
            # where='offer_player = "{}" AND '.format(player) +
            #       'offer_status = "Winning"'
        )[0]
    except IndexError:
        last_offer = 0
        last_user = ''
        last_id = 0
        last_dt = '2030-01-01 00:00:00'

    if too_late_to_offer(dt, last_dt):
        dbf.db_delete(table='offers', where='offer_id = {}'.format(offer_id))

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

        dbf.db_update(table='players',
                      columns=['player_status'],
                      values=[last_user],
                      where='player_name = "{}"'.format(player))

        return ('Troppo tardi, 24 ore scadute. ' +
                '{} acquistato da {}'.format(player, last_user))

    if offer <= last_offer:
        dbf.db_delete(table='offers', where='offer_id = {}'.format(offer_id))
        return ('Offerta troppo bassa. ' +
                'Ultimo rilancio: {}, {}'.format(last_offer, last_user))

    elif offer < price:
        dbf.db_delete(table='offers', where='offer_id = {}'.format(offer_id))
        return 'Offerta troppo bassa. Quotazione: {}'.format(price)

    else:
        return last_id
コード例 #25
0
def conferma_offerta(bot, update):
    """
	Conferma l'offerta effettuata (se valida) ed aggiorna il db di conseguenza.
	Infine manda un messaggio in chat con tutte le offerte aperte e chiuse.

	:param bot:
	:param update:

	:return: Nothing

	"""

    # 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)
    dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    try:
        of_id, pl = select_offer_to_confirm(user)
    except ValueError:
        return bot.send_message(chat_id=update.message.chat_id,
                                text=select_offer_to_confirm(user))

    # not_off = dbf.db_select(
    # 		table='offers',
    # 		columns_in=['offer_player'],
    # 		where='offer_status = "Not Official"')
    # if pl in not_off:
    # 	dbf.db_delete(
    # 			table='offers',
    # 			where='offer_user = "******" and offer_player = "{}"'.format(user,
    # 			                                                         pl))
    # 	return bot.send_message(chat_id=update.message.chat_id,
    # 	                        text='Asta già conclusa.')

    status = dbf.db_select(table='players',
                           columns_in=['player_status'],
                           where='player_name = "{}"'.format(pl))[0]
    if status != 'FREE':
        dbf.db_delete(table='offers', where='offer_id = {}'.format(of_id))
        return bot.send_message(
            chat_id=update.message.chat_id,
            text='Giocatore non svincolato ({}).'.format(status))

    last_valid_offer = check_offer_value(of_id, pl, dt)
    if type(last_valid_offer) == str:
        return bot.send_message(chat_id=update.message.chat_id,
                                text=last_valid_offer)

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

    delete_not_conf_offers_by_others(pl_id, user)

    dbf.db_update(table='offers',
                  columns=['offer_datetime', 'offer_status'],
                  values=[dt, 'Winning'],
                  where='offer_id = {}'.format(of_id))

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

    crea_riepilogo(bot, update, dt)
コード例 #26
0
def conferma_pagamento(bot, update):

    # 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:
        pay_id, pl, pr, mn = dbf.db_select(
            table='pays',
            columns_in=['pay_id', 'pay_player', 'pay_price', 'pay_money'],
            where='pay_user = "******" AND pay_status = "Not Confirmed"'.format(
                user))[-1]
        dbf.db_delete(table='pays',
                      where='pay_id != {} AND pay_player = "{}"'.format(
                          pay_id, pl))
    except IndexError:
        return bot.send_message(chat_id=update.message.chat_id,
                                text='Nulla da confermare per {}'.format(user))

    budget = dbf.db_select(table='budgets',
                           columns_in=['budget_value'],
                           where='budget_team = "{}"'.format(user))[0]

    # if len(mn) > 1:
    mn = mn.split(', ')

    for i in mn:
        try:
            int(i)
        except ValueError:
            budget += dbf.db_select(table='players',
                                    columns_in=['player_price'],
                                    where='player_name = "{}"'.format(
                                        i.split(' (')[0]))[0]

    if budget < pr:
        dbf.db_delete(table='pays',
                      where='pay_user = "******" AND pay_player = "{}"'.format(
                          user, pl))
        return bot.send_message(chat_id=update.message.chat_id,
                                text='Budget insufficiente'.format(user))
    else:
        dbf.db_update(table='budgets',
                      columns=['budget_value'],
                      values=[budget - pr],
                      where='budget_team = "{}"'.format(user))

        dbf.db_update(table='players',
                      columns=['player_status'],
                      values=[user],
                      where='player_name = "{}"'.format(pl))

        dbf.db_update(
            table='offers',
            columns=['offer_status'],
            values=['Official'],
            where='offer_player = "{}" AND offer_status = "Not Official"'.
            format(pl))

        dbf.db_update(table='pays',
                      columns=['pay_status'],
                      values=['Confirmed'],
                      where='pay_player = "{}"'.format(pl))

        for i in mn:
            try:
                int(i)
            except ValueError:
                dbf.db_update(table='players',
                              columns=['player_status'],
                              values=['FREE'],
                              where='player_name = "{}"'.format(
                                  i.split(' (')[0]))

    return bot.send_message(chat_id=update.message.chat_id,
                            text='Rosa {} aggiornata'.format(user))
コード例 #27
0
ファイル: utils.py プロジェクト: alaporta85/FantAstaBot
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
コード例 #28
0
ファイル: utils.py プロジェクト: alaporta85/FantAstaBot
def check_offer_value(user, offer_id, player, dt):
    """
	Controlla che il valore dell'offerta sia valido. Nell'ordine:

		- In caso di prima offerta, se il valore offerto è sufficiente
		- In caso di rilancio, se l'offerta supera quella già presente
		- Nel caso la superi, se l'offerta supera un possibile autobid

	Utilizzata all'interno di confermo_offerta().

	:param user: str, fantasquadra
	:param offer_id: int, id dell'offerta
	:param player: str, nome del giocatore
	:param dt: str, data ed ora attuali

	:return : str o tuple, messaggi in chat

	"""

    offer = dbf.db_select(table='offers',
                          columns=['offer_price'],
                          where=f'offer_id = {offer_id}')[0]

    # Prendo dal db i dettagli dell'ultima offerta valida per questo
    # calciatore, qualora ci sia
    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 si tratta di prima offerta, ne confronto il valore con il prezzo base
    # del calciatore ed aggiorno il db
    if not last_offer:
        price = dbf.db_select(table='players',
                              columns=['player_price'],
                              where=f'player_name = "{player}"')[0]
        if offer < price:
            dbf.db_delete(table='offers', where=f'offer_id = {offer_id}')

            return f'Offerta troppo bassa. Quotazione: {price}'
        else:

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

            private = 'Offerta aggiornata correttamente.'

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

            return private, group

    # Se si tratta di rilancio, controllo che l'offerta superi quella già
    # esistente
    else:
        if offer <= last_offer:
            dbf.db_delete(table='offers', where=f'offer_id = {offer_id}')

            return ('Offerta troppo bassa. ' +
                    f'Ultimo rilancio: {last_offer}, {last_user}')
        else:
            # Se la supera, resta da confrontarla con un eventuale autobid.
            # Quindi seleziono l'autobid già impostato dall'altro user oppure,
            # qualora non esista, assegno valore nullo ad alcune variabili in
            # modo da gestire il codice successivo
            try:
                iid, ab_user, nonce, tag, encr_value = dbf.db_select(
                    table='autobids',
                    columns=[
                        'autobid_id', 'autobid_user', 'autobid_nonce',
                        'autobid_tag', 'autobid_value'
                    ],
                    where=f'autobid_player = "{player}"')[0]
                last_ab = int(
                    dbf.decrypt_value(nonce, tag, encr_value).decode())
            except IndexError:
                iid = 0
                ab_user = None
                last_ab = 0

            # Se l'offerta è inferiore all'autobid di un altro user: cancello
            # l'offerta dal db, aggiorno il valore dell'offerta dell'altro
            # utente e, qualora questo nuovo valore raggiunga il suo limite
            # di autobid, elimino tale autobid dal db
            if offer < last_ab:
                dbf.db_delete(table='offers', where=f'offer_id = {offer_id}')
                dbf.db_update(table='offers',
                              columns=['offer_price', 'offer_dt'],
                              values=[offer + 1, dt],
                              where=f'offer_id = {last_id}')
                if offer + 1 == last_ab:
                    dbf.db_delete(table='autobids',
                                  where=f'autobid_id = {iid}')

                private = ("Offerta troppo bassa. Non hai superato" +
                           f" l'autobid di {ab_user}.")

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

                return private, group

            # Se invece l'offerta supera l'ultimo autobid allora cancello tale
            # autobid dal db ed aggiorno tutti gli altri parametri
            else:

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

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

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

                private = 'Offerta aggiornata correttamente.'

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

                return private, group
コード例 #29
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)
コード例 #30
0
def confermo_pagamento(bot, update):
    """
	Conferma il pagamento di un'offerta ufficiale ed aggiorna il db di
	conseguenza. Innanzitutto controlla se i milioni offerti sono sufficienti,
	dopodichè controlla se si ha effettivamente il budget per completare il
	pagamento. Se l'offerta risulta valida a tutti gli effetti, verrà
	aggiornato il budget della squadra in questione, lo status dei calciatori
	coinvolti, la tabella "offers" e la tabella "pays".

	:param bot:
	:param update:

	: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')
    if cfg.BLOCK:
        group_id = cfg.POLPS_ID
    else:
        group_id = cfg.FANTA_ID

    user = select_user(update)

    # Controllo ci sia il pagamento e, se sì, lo seleziono.
    try:
        pay_id, pl, pr, mn = dbf.db_select(
            table='pays',
            columns=['pay_id', 'pay_player', 'pay_price', 'pay_money'],
            where=f'pay_user = "******" AND pay_status IS NULL')[0]
    except IndexError:
        return bot.send_message(chat_id=chat_id,
                                text=f'Nulla da confermare per {user}')

    # Analizzo il metodo di pagamento proposto e controllo che sia sufficiente
    # a coprire la spesa
    mn = mn.split(', ')
    temp_bud = 0
    for i in mn:
        try:
            temp_bud += int(i)
        except ValueError:
            temp_bud += int(i.split(': ')[1][:-1])

    if temp_bud < pr:
        dbf.db_delete(table='pays',
                      where=f'pay_user = "******" AND pay_player = "{pl}"')
        return bot.send_message(chat_id=chat_id,
                                text=('Offerta insufficiente.\n' +
                                      f'Milioni mancanti: {pr - temp_bud}'))

    # Sommo al budget della fantasquadra il prezzo dei giocatori utilizzati
    # nel pagamento, se presenti, e che saranno quindi ceduti
    budget = dbf.db_select(table='budgets',
                           columns=['budget_value'],
                           where=f'budget_team = "{user}"')
    budget = budget[0] if budget else 0

    new_budget = budget
    for i in mn:
        try:
            int(i)
        except ValueError:
            player = i.split(' (')[0]
            new_budget += dbf.db_select(table='players',
                                        columns=['player_price'],
                                        where=f'player_name = "{player}"')[0]

    # Qualora l'offerta sia valida, aggiorno varie voci nel db sia del
    # calciatore acquistato che di quelli ceduti, se presenti
    if new_budget < pr:
        dbf.db_delete(table='pays',
                      where=f'pay_user = "******" AND pay_player = "{pl}"')
        return bot.send_message(chat_id=chat_id, text='Budget insufficiente')
    else:
        dbf.db_update(table='budgets',
                      columns=['budget_value'],
                      values=[new_budget - pr],
                      where=f'budget_team = "{user}"')

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

        # dbf.db_update(
        # 			table='stats',
        # 			columns=['status'],
        # 			values=[user],
        # 			where=f'name = "{pl}"')

        dbf.db_update(table='offers',
                      columns=['offer_status'],
                      values=['Official'],
                      where=(f'offer_player = "{pl}" AND ' +
                             'offer_status = "Not Official"'))

        dt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        dbf.db_update(table='pays',
                      columns=['pay_dt', 'pay_status'],
                      values=[dt, 'Confirmed'],
                      where=f'pay_player = "{pl}"')

        for i in mn:
            try:
                int(i)
            except ValueError:
                player = i.split(' (')[0]
                dbf.db_update(table='players',
                              columns=['player_status'],
                              values=['FREE'],
                              where=f'player_name = "{player}"')

                # dbf.db_update(
                # 			table='stats',
                # 			columns=['status'],
                # 			values=['FREE'],
                # 			where=f'name = "{player}"')

    message = (f'<i>{user}</i> ha ufficializzato ' +
               f'<b>{pl}</b> a {pr}.\nPagamento: {", ".join(mn)}\n')

    if budget == new_budget - pr:
        message += f'Il budget resta {budget}'
    else:
        message += f'Il budget passa da {budget} a {new_budget - pr}.'

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

    bot.send_message(chat_id=chat_id,
                     text='Pagamento effettuato correttamente.')

    bot.send_message(parse_mode='HTML',
                     chat_id=group_id,
                     text=(message + cfg.SEPAR + utl.crea_riepilogo(dt)))