Пример #1
0
def _download_external_data():
    nu = Nubank(os.environ.get('NUBANK_LOGIN'),
                os.environ.get('NUBANK_PASSWORD'))
    card_transactions = nu.get_card_statements()
    _transactions_to_csv(card_transactions, 'card_transactions')

    account_transactions = nu.get_account_statements()
    _transactions_to_csv(account_transactions, 'account_transactions')
Пример #2
0
def gen_token(password):
    log('Storing token')
    nu = Nubank()
    cpf = get_cpf()
    refresh_token = nu.authenticate_with_cert(cpf, password, tmp_path('cert.p12'))
    with open(tmp_path('token'), 'w') as token_file:
        token_file.write(refresh_token)
        log(f'{Fore.YELLOW}Token stored')
Пример #3
0
    def handle(self, *args, **options):

        nu = Nubank()
        uuid, qr_code = nu.get_qr_code()

        qr_code.print_ascii(invert=True)

        nu.authenticate_with_qr_code(NUBANK_CPF, NUBANK_PASSWORD, uuid)
        print(nu.get_account_balance())

        card_statements = nu.get_card_statements()
Пример #4
0
import json
import os
import re
import xml.etree.cElementTree as ET
from datetime import datetime, timedelta
from xml.dom import minidom

from pynubank import Nubank

nu = Nubank()
target = "/tmp/extrato_nuconta.ofx"
now = datetime.now().strftime('%Y%m%d')
d90 = datetime.now() - timedelta(days=90)
date_format = '%Y%m%d'
cpf = os.getenv('NU_CPF', '')
pwd = os.getenv('NU_PWD', '')
test_file = os.getenv('NU_TEST_FILE', '')
statements = []
balance = 0.00

PAYMENT_EVENT_TYPES = (
    'TransferOutEvent',
    'TransferInEvent',
    'TransferOutReversalEvent',
    'BarcodePaymentEvent',
    'DebitPurchaseEvent',
    'DebitPurchaseReversalEvent',
    'BillPaymentEvent',
)

# used to test from a json file with the statements
Пример #5
0
NUBANK_NUCONTA_ACCOUNT = os.getenv('NUBANK_NUCONTA_ACCOUNT')
STARTING_POINT = datetime.datetime.strptime(os.getenv('STARTING_POINT'),
                                            '%Y-%m-%d').date()

IN_EVENT = ['TransferInEvent', 'TransferOutReversalEvent']

if __name__ == '__main__':
    with open('cert.p12', 'wb') as f:
        cert_content = base64.b64decode(NUBANK_CERT)
        f.write(cert_content)

    log_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                   'logging.json')
    setup_logging(log_config_file)
    ynab = YNAB(YNAB_EMAIL, YNAB_PASSWORD, YNAB_BUDGET)
    nu = Nubank()
    nu.authenticate_with_refresh_token(NUBANK_TOKEN, './cert.p12')

    transactions = filter_transactions(nu.get_card_statements(),
                                       STARTING_POINT)

    print(f'Found {len(transactions)} card transactions')
    for transaction in transactions:
        ynab.add_transaction(payee=transaction['description'],
                             date=parse_transaction_date(transaction),
                             value=-int(transaction['amount']) / 100,
                             id=transaction['id'],
                             subcategory=transaction['category'].capitalize(),
                             account=NUBANK_CARD_ACCOUNT)

    account_transactions = filter_transactions(nu.get_account_statements(),
Пример #6
0
 def __new__(self):
     credentials = json.load(open('credentials/nubank_credentials.json'))
     return Nubank(credentials['cpf'], credentials['password'])
Пример #7
0
# from pynubank import Nubank

# user = os.getenv('NU_USER')
# passwd = os.getenv('NU_PASSWD')

# nu = Nubank()
# nu.authenticate(user, passwd)

# bills = nu.get_bills()
# print(len(bills))
import os
from pynubank import Nubank

user = os.getenv('NU_USER')
passwd = os.getenv('NU_PASSWD')
nu = Nubank()
uuid, qr_code = nu.get_qr_code()
# Nesse momeento será printado o QRCode no console
# Você precisa escanear pelo o seu app do celular
# Esse menu fica em NU > Perfil > Acesso pelo site
qr_code.print_ascii(invert=True)
input('Após escanear o QRCode pressione enter para continuar')
# Somente após escanear o QRCode você pode chamar a linha abaixo
nu.authenticate_with_qr_code(user, passwd, uuid)
print(nu.get_bills())
Пример #8
0
 def __init__(self):
     self.nu = Nubank()
Пример #9
0
class NubankBot:
    nu = None
    logged = False
    n_card = None

    def __init__(self):
        self.nu = Nubank()

    def set_nubank_command(self, n: NubankCards):
        self.n_card = n

    def get_qr_code(self):

        uid, qr_code = self.nu.get_qr_code()
        img: PilImage = qr_code.make_image()

        NubankSession.objects.update_or_create(session_id=uid,
                                               defaults={"session_id": uid})

        name = f"./{uuid.uuid4().hex}.png"
        img.save(name)

        qr_code.print_ascii(invert=True)

        return name

    def _login(self, pwd: str):

        last_login_diff = timezone.now() - self.n_card.last_login
        total_hours = last_login_diff.total_seconds() / 3600
        if total_hours < 12:
            raise Exception("You can't login now")

        nu_session = NubankSession.objects.order_by("-created_at").first()

        self.nu.authenticate_with_qr_code(self.n_card.cpf, pwd,
                                          nu_session.session_id)
        self.logged = True
        self.n_card.last_login = timezone.now()
        self.n_card.save()

    def execute(self, pwd: str, card: NubankCards):

        if not self.logged:
            self._login(pwd)

        card_statements = self.nu.get_card_statements()

        for n in card_statements:

            amount_without_iof = 0
            if n.get("amount_without_iof"):
                amount_without_iof = Decimal(n["amount_without_iof"]) / 100

            defaults = {
                "amount": Decimal(n["amount"]) / 100,
                "amount_without_iof": amount_without_iof,
                "description": n.get("description"),
                "category": n.get("category"),
                "source": n.get("source"),
                "title": n.get("title"),
                "account": n.get("account"),
                "details": n.get("details"),
                "nubank_id": n["id"],
                "href": n.get("href"),
                "item_time": parse(n["time"]),
            }

            NubankStatement.objects.get_or_create(nubank_id=n["id"],
                                                  defaults=defaults)

        self._execute_bank_statements(card)

        return

    def _execute_bank_statements(self, card: NubankCards):
        account_statements = self.nu.get_account_statements()

        for a in account_statements:
            if a["__typename"] == "TransferOutReversalEvent":
                continue

            defaults = {
                "nubank_id": a["id"],
                "title": a["title"],
                "detail": a["detail"],
                "amount": Decimal(a["amount"]),
                "post_date": a["postDate"],
                "_type": a["__typename"],
                "cpf": card.cpf,
            }
            NubankBankStatement.objects.get_or_create(nubank_id=a["id"],
                                                      defaults=defaults)
Пример #10
0
class Bank:
    def __init__(self):
        self.__api = Nubank()
        self.__is_auth = False
        self.__credit_data_path = f"{os.getcwd()}/data/credit_history.csv"
        self.__account_data_path = f"{os.getcwd()}/data/account_history.csv"

    @property
    def is_auth(self):
        return self.__is_auth

    def auth(self, user_cpf: str, user_password: str, cert_path: str):
        """
        :param user_cpf: user's cpf
        :type str
        :param user_password: user's password
        :type str
        :param cert_path: certification's path
        :type str
        """
        try:
            self.__api.authenticate_with_cert(user_cpf, user_password,
                                              cert_path)
            self.__is_auth = True
        except Exception as e:
            print(e)

    def __limit_history(self, history, limit: int):
        return history.sample(limit) if limit else history

    @verify_auth
    def __get_api_data(self, fund):
        funds = {
            'credit': self.__api.get_card_statements,
            'account': self.__api.get_account_statements
        }
        method = funds[fund]
        return method()

    def credit_history(self, limit: int = None):
        """
        :param limit: credit card history statements rows limit
        :type int
        """
        fund = 'credit'
        if self.check_local_data(fund):
            df = pd.read_csv(self.__credit_data_path)
        else:
            df = pd.DataFrame(self.__get_api_data(fund))
            df.to_csv(self.__credit_data_path, index=False)
        return self.__limit_history(df, limit)

    def account_history(self, limit: int = None):
        """
        :param limit: account history statements rows limit
        :type int
        """
        fund = 'account'
        if self.check_local_data(fund):
            df = pd.read_csv(self.__account_data_path)
        else:
            df = pd.DataFrame(self.__get_api_data(fund))
            df.to_csv(self.__account_data_path, index=False)
        return self.__limit_history(df, limit)

    def check_local_data(self, fund):
        funds = {
            "credit": self.__credit_data_path,
            "account": self.__account_data_path
        }
        return os.access(funds[fund], os.F_OK)
Пример #11
0
import json
from pprint import pprint
from pynubank import Nubank

credentials = json.load(open('nubank_credentials.json'))

print(credentials)

nu = Nubank(credentials['cpf'], credentials['password'])

transactions = nu.get_account_statements()

for entry in transactions:
    row = [
        entry['time'], entry['title'], entry['description'], entry['amount']
    ]
    if 'tags' in entry['details']:
        row.append(entry['details']['tags'])
    pprint(row)
Пример #12
0
from pynubank import Nubank
import os

from dotenv import load_dotenv
load_dotenv()

NUBANK_CERT = os.getenv('NUBANK_CERT')

WARN = "Atenção: Utilizar apenas para obter o refresh token. Não utilizar com frequência, pois o Nubank pode bloquear sua conta."

if __name__ == '__main__':
    print(WARN)
    username = input('[>] Type your CPF: ')
    password = input('[>] Type your password: ')

    nu = Nubank()
    refresh_token = nu.authenticate_with_cert(username, password, NUBANK_CERT)
    print(refresh_token)
Пример #13
0
    print(transaction)
    transaction["detail"] = transaction['detail'].split(' - ')[0]
    if "amount" in transaction:
        transaction["amount"] = '{:.2f}'.format(transaction['amount']).replace(
            '.', ',')
    return transaction.values()


if __name__ == '__main__':
    log_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                   'logging.json')
    setup_logging(log_config_file)

    logging.info('Initializen Nubank export')

    nu = Nubank()
    nu.authenticate_with_refresh_token(NUBANK_TOKEN, NUBANK_CERT)

    account_transactions = nu.get_account_feed()
    logging.info(f'Found {len(account_transactions)} account transactions')

    with open('export.csv', mode='w', encoding='utf-8') as tfile:
        fieldnames = [
            'id', '__typename', 'title', 'detail', 'postDate', 'amount',
            'originAccount', 'destinationAccount'
        ]
        writer = csv.DictWriter(tfile,
                                delimiter=';',
                                quotechar='"',
                                quoting=csv.QUOTE_MINIMAL,
                                fieldnames=fieldnames)
Пример #14
0
import configparser
import json
from datetime import datetime
from pynubank import Nubank
from NUBank.src.model.Compra import Despesa
from flask import Flask, render_template

app = Flask(__name__)
config = configparser.ConfigParser()
config.read_file(open('config.ini'))
nu = Nubank(config['DEFAULT']['usuario'],
            config['DEFAULT']['senha'])  # subistituir por usu e senha
dia_fechamento = int(config['DEFAULT']['dia_do_fechamento'])


def add_desp(n):
    return Despesa(
        descricao=n['description'],
        categoria=n['category'],
        valor=n['amount'],
        data=datetime.strptime(n['time'], "%Y-%m-%dT%H:%M:%SZ"),
        titulo=n['title'],
        detalhes=n['details'],  #json.dumps(n['details'])
        id=n['id'],
        _links=n['_links'],
        link=n['href'],
    )


def grava_saida(resultado, arquivosaida):
    arquivo = open(arquivosaida, "w")
Пример #15
0
 def __init__(self):
     self.__api = Nubank()
     self.__is_auth = False
     self.__credit_data_path = f"{os.getcwd()}/data/credit_history.csv"
     self.__account_data_path = f"{os.getcwd()}/data/account_history.csv"
Пример #16
0
            logging.config.dictConfig(config)
        return True
    except FileNotFoundError:
        print('Missing logging.json, logging not configured.')
        return False


YNAB_EMAIL = os.getenv('YNAB_EMAIL')
YNAB_PASSWORD = os.getenv('YNAB_PASSWORD')
YNAB_BUDGET = os.getenv('YNAB_BUDGET')
NUBANK_LOGIN = os.getenv('NUBANK_LOGIN')
NUBANK_PASSWORD = os.getenv('NUBANK_PASSWORD')
STARTING_POINT = datetime.datetime.strptime(os.getenv('STARTING_POINT'), '%Y-%m-%d').date()

if __name__ == '__main__':
    log_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logging.json')
    setup_logging(log_config_file)
    ynab = YNAB(YNAB_EMAIL, YNAB_PASSWORD, YNAB_BUDGET)
    nu = Nubank(NUBANK_LOGIN, NUBANK_PASSWORD)
    transactions = filter_transactions(nu.get_card_statements(), STARTING_POINT)
    for transaction in transactions:
        ynab.add_transaction(
            payee=transaction['description'],
            date=parse_transaction_date(transaction),
            value=-int(transaction['amount']) / 100,
            id=transaction['id'],
            subcategory=transaction['category'].capitalize()
        )

    ynab.sync()
Пример #17
0
import json
import pygsheets
from cache_request import CacheRequest
from os import path
from dateutil import parser
from pprint import pprint
from pynubank import Nubank
from datetime import datetime

cache = CacheRequest('get_account_feed')

if cache.has_cache():
    feed = cache.read_cache()
else:
    credentials = json.load(open('nubank_credentials.json'))
    nu = Nubank(credentials['cpf'], credentials['password'])
    feed = nu.get_account_feed()
    cache.save_cache(feed)
# Find a workbook by name and open the first sheet
# Make sure you use the right name here.
#client = pygsheets.authorize(service_file='client_secret.json')
#nubank = client.open("Nubank")

#rows = []
#pprint(list(set(entry['category'] for entry in feed['events'])))

#bills = list(filter(lambda x: x['category'] in ('transactions') , feed['events']))

#sheets  = []
#rows = []
pprint(feed)
Пример #18
0
        return True
    except FileNotFoundError:
        print('Missing logging.json, logging not configured.')
        return False


YNAB_EMAIL = os.getenv('YNAB_EMAIL')
YNAB_PASSWORD = os.getenv('YNAB_PASSWORD')
YNAB_BUDGET = os.getenv('YNAB_BUDGET')
NUBANK_LOGIN = os.getenv('NUBANK_LOGIN')
NUBANK_PASSWORD = os.getenv('NUBANK_PASSWORD')
STARTING_POINT = datetime.datetime.strptime(os.getenv('STARTING_POINT'),
                                            '%Y-%m-%d').date()

if __name__ == '__main__':
    log_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                   'logging.json')
    setup_logging(log_config_file)
    ynab = YNAB(YNAB_EMAIL, YNAB_PASSWORD, YNAB_BUDGET)
    nu = Nubank(NUBANK_LOGIN, NUBANK_PASSWORD)
    transactions = filter_transactions(nu.get_account_statements(),
                                       STARTING_POINT)
    for transaction in transactions:
        ynab.add_transaction(payee=transaction['description'],
                             date=parse_transaction_date(transaction),
                             value=-int(transaction['amount']) / 100,
                             id=transaction['id'],
                             subcategory=transaction['category'].capitalize())

    ynab.sync()