示例#1
0
async def res_handler(message: types.Message):
    if message['from']['id'] not in _u.get_user_ids():
        return
    try:
        c, resourse = message['text'].split()
        _type = c[1:]
        settings[_type.lower() + '_limit'] = int(resourse)
        await bot.send_message(
            message['from']['id'],
            f'<b>Установлено оповещение при {_type.upper()} > {resourse}%</b>',
            parse_mode='html')
        loadInTxt().save('settings.txt', settings)

    except Exception as e:
        _log.exception(f"Error {message['text']}: ")
        await message.reply(f"Error {message['text']}: {e}")
示例#2
0
async def onoff_handler(message: types.Message):
    if message['from']['id'] not in _u.get_user_ids():
        return
    try:
        if len(message['text'].split()) != 2:
            c = message['text']
            for _type in ['nfts', 'tokens']:
                to = True if c == '/on' else False
                settings = loadInTxt(separator=':').get('settings.txt')
                if settings.get(_type + "_notifications"):
                    settings[_type + "_notifications"] = str(to).lower()
                    loadInTxt().save('settings.txt', settings)
                    await message.reply(
                        f'Успешно изменен тип оповещений {_type}_notifications на {str(to).lower()}.'
                    )
                else:
                    await message.reply(
                        'InvalidType: один из 2 возможных типов уведомлений nfts/tokens'
                    )

        else:
            c, _type = message['text'].split()
            to = True if c == '/on' else False
            settings = loadInTxt(separator=':').get('settings.txt')
            if settings.get(_type + "_notifications"):
                settings[_type + "_notifications"] = str(to).lower()
                loadInTxt().save('settings.txt', settings)
                await message.reply(
                    f'Успешно изменен тип оповещений {_type}_notifications на {str(to).lower()}.'
                )
            else:
                await message.reply(
                    'InvalidType: один из 2 возможных типов уведомлений nfts/tokens'
                )
    except Exception as e:
        _log.exception("Error /on | /off: ")
        await message.reply(f"Error /on | /off: {e}")
                |            by @abuz.trade             |
                |                                       |
                |      Creator: vk.com/abuz.trade       |
                |      Group: vk.com/lowbank.trade      |
                |                                       |
                 ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
 
 
 
"""
)

def get_text(p: str):
    return eval(f'{p}_{l}')

settings = loadInTxt(create=True).get("settings.txt", create_data="chrome_path: \nlanguage: RU\noptions: ")

if settings.get('language') is None or \
   settings.get('chrome_path') is None or \
   settings.get('options') is None:
       
    print('settings.txt filled incorrectly. Refill it')
    with open('settings.txt', 'w') as f: f.write(def_settings)
    input(get_text('wait'))
    
elif settings.get('language').upper() not in ['RU', 'EN']:
    print('Language must be RU or EN...')
    print('Program will use English')
    settings['language'] = 'EN'
    
l = settings['language'].lower()
示例#4
0
def run():
    while True:
        accounts = loadInStrings(clear_empty=True,
                                 separate=False).get('accounts.txt')
        accounts_dumb = _u.get_accounts()

        for account in accounts:
            settings = loadInTxt().get('settings.txt')
            time.sleep(int(settings['timeout']))
            if account not in accounts_dumb.keys():
                accounts_dumb[account] = deepcopy(Payload.defoult_account_data)
                base.add(table='accounts',
                         name=account,
                         assets=[],
                         tokens=accounts_dumb[account]['tokens'])

            token, nft = _u.get_links(account)

            _isretry = False
            for _ in range(3):
                try:
                    tokens_response = scraper.get(token, timeout=10)
                    tokens_response = tokens_response.json()
                    if _isretry:
                        log("Подключение восстановлено!")
                    break
                except Exception as e:
                    log(f"[{_+1}]GetTokensError: {e}")
                    time.sleep(5)
                    _isretry = True
                    continue
            else:
                tokens_response = {
                    'tokens': [{
                        'symbol': x,
                        'amount': y
                    } for x, y in accounts_dumb[account]['tokens'].items()]
                }

            _isretry = False
            for _ in range(3):
                try:
                    nfts_response = scraper.get(nft, timeout=10)
                    nfts_response = nfts_response.json()
                    if _isretry:
                        log("Подключение восстановлено!")
                    break
                except Exception as e:
                    log(f"[{_+1}]GetNFTsError: {e}")
                    time.sleep(5)
                    _isretry = True
                    continue
            else:
                nfts_response = accounts_dumb[account]['assets']

            _p = Payload.wax_token_payload.copy()
            _p['account'] = account

            tokens = [{
                x['symbol']: x['amount']
                for x in tokens_response['tokens']
            }][0]

            resourses = _u.get_resourses(account)

            tokens['CPU_STAKED'] = resourses['cpu_staked']

            if type(nfts_response) is not list:
                assets = list(_u.get_assets(nfts_response).keys())
            else:
                assets = nfts_response

            # check tokens
            if tokens != accounts_dumb[account]['tokens']:
                # add new token or balance changed
                _a_ = False

                for k, v in tokens.items():
                    if k not in accounts_dumb[account]['tokens'].keys():
                        _type = "new token"
                        body = f"New token deposit to your wallet:\n"\
                               f"{k}: {v}"
                        accounts_dumb[account]['tokens'][k] = v
                        if settings['low_logging'] != 'true':
                            text = _u.get_notification_text(
                                account, _type, body)
                        else:
                            text = f'<b>Account: <code>{account}</code>\nNew token: {k}: {v}</b>'

                        if settings['tokens_notifications'] == 'true':
                            notification(text)
                        log(f'{account} new token deposit to your wallet: {k}: {v}'
                            )
                        base.edit_by('accounts', ['name', account],
                                     tokens=accounts_dumb[account]['tokens'])
                        _a_ = True

                else:
                    if _a_ == False:
                        for k1, v1 in tokens.items():
                            if v1 != accounts_dumb[account]['tokens'][k1]:
                                _type = "change balance"
                                if v1 > accounts_dumb[account]['tokens'][k1]:
                                    body = f"Add balance:\n"\
                                           f"{k1}: {v1} (+{round(v1 - accounts_dumb[account]['tokens'][k1], 5)} {k1})"
                                    log(f"{account} add balance: +{round(v1 - accounts_dumb[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]"
                                        )
                                    if settings['low_logging'] == 'true':
                                        _text = f"<b>Account: <code>{account}</code>\n+{round(v1 - accounts_dumb[account]['tokens'][k1], 5)} {k1} [{v1} {k1}]</b>"

                                    if round(
                                            v1 - accounts_dumb[account]
                                        ['tokens'][k1],
                                            6) <= 0.0001 and k1 == 'TLM':
                                        notification(
                                            f"<b>Account: {account}\n"\
                                            f"+{round(v1 - accounts_dumb[account]['tokens'][k1], 5)} TLM\n"\
                                            f"Seems like account was banned...</b>"
                                        )
                                    accounts_dumb[account]['tokens'][k1] = v1

                                else:
                                    body = f"Transfer balance:\n"\
                                           f"{k1}: {v1} (-{round(accounts_dumb[account]['tokens'][k1] - v1, 5)} {k1})"
                                    log(f"{account} transfer balance: -{round(accounts_dumb[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]"
                                        )
                                    if settings['low_logging'] == 'true':
                                        _text = f"<b>Account: <code>{account}</code>\n-{round(accounts_dumb[account]['tokens'][k1] - v1, 5)} {k1} [{v1} {k1}]</b>"

                                    accounts_dumb[account]['tokens'][k1] = v1

                                if settings['low_logging'] != 'true':
                                    text = _u.get_notification_text(
                                        account, _type, body)
                                else:
                                    text = _text

                                if settings['tokens_notifications'] == 'true':
                                    notification(text)

                                base.edit_by(
                                    'accounts', ['name', account],
                                    tokens=accounts_dumb[account]['tokens'])
                    _a_ = True

            # check assets
            if assets != accounts_dumb[account]['assets']:
                # add or delete assets
                _type = "change assets"
                new_assets = [
                    str(x) for x in assets
                    if str(x) not in accounts_dumb[account]['assets']
                ]
                del_assets = [
                    str(x) for x in accounts_dumb[account]['assets']
                    if str(x) not in assets
                ]

                if new_assets:
                    body = "Add NFTs:\n" + '\n'.join(new_assets)

                    body += "\n\n"

                    _text = f"<b>Account: <code>{account}</code></b>\n"
                    _price_sum = 0
                    for ass in new_assets:
                        parsed = _u.fetch_asset(ass)
                        if not parsed['success']:
                            continue
                        price = _u.get_price(parsed['template_id'])
                        body += f"<b>Asset: {ass}</b>\n"\
                                f"<b>Collection name: {parsed['collection_name']}</b>\n"\
                                f"<b>Name: {parsed['name']}</b>\n"\
                                f"<b>Rarity: {parsed['rarity']}</b>\n"\
                                f"<b>Price: {price} WAX</b>\n\n"
                        log(f"{account} new asset: {ass} {parsed['name']} ({price} WAX)"
                            )
                        _text += f"<b>[{ass}] {parsed['name']} - {price} WAX</b>\n"
                        _price_sum += price

                    if settings['low_logging'] != 'true':
                        text = _u.get_notification_text(account, _type, body)
                    else:
                        text = _text
                        text += f"\n<b>+{round(_price_sum, 2)} WAX</b>"

                    if settings['nfts_notifications'] == 'true':
                        notification(text)

                elif del_assets:
                    _text = f"<b>Account: <code>{account}</code></b>\n" + '\n'.join(
                        del_assets)
                    body = "Transfer/delete NFTs:\n" + '\n'.join(del_assets)
                    log(f"{account} transfer/delete NFTs: {' '.join(del_assets)}"
                        )
                    if settings['low_logging'] != 'true':
                        text = _u.get_notification_text(account, _type, body)
                    else:
                        text = _text
                    if settings['nfts_notifications'] == 'true':
                        notification(text)

                base.edit_by('accounts', ['name', account],
                             assets=list(assets))

            # check account resourses
            resourses = _u.get_resourses(account)
            for _res in resourses.keys():
                if 'stake' in _res:
                    continue
                if resourses[_res] > int(settings[_res + '_limit']):
                    if limits_notifications[_res].get(account):
                        if time.time(
                        ) - limits_notifications[_res][account] >= int(
                                settings['out_of_limit_timeout']):
                            # timeout done!
                            notification(
                                f"<b>Account {account} out of {_res.upper()} limit ({resourses[_res]}%).</b>"
                            )
                            log(f"Account {account} out of {_res.upper()} limit ({resourses[_res]}%)."
                                )
                            limits_notifications[_res][account] = int(
                                time.time())
                    else:
                        limits_notifications[_res][account] = int(time.time())
                        notification(
                            f"<b>Account {account} out of {_res.upper()} limit ({resourses[_res]}%).</b>"
                        )
                        log(f"Account {account} out of {_res.upper()} limit ({resourses[_res]}%)."
                            )
示例#5
0
from logger import log_handler, logger
from data import URL as _URL
from data import Payload as _Payload
from data import to_dict
from mw_sql import baseUniversal
from _utils import _utils

scraper = create_scraper()
_log = logger('WAXParser', 'WAXParser.log', 'INFO').get_logger()
log = log_handler(_log).log
base = baseUniversal('accounts.db')

URL = _URL()
Payload = _Payload()
limits_notifications = Payload.limits_notifications.copy()
settings = loadInTxt().get('settings.txt')

bot = Bot(token=settings['bot_token'])
dp = Dispatcher(bot)
zalupa = asyncio.new_event_loop()

_u = _utils(settings, base, _log, log, scraper, URL, Payload)


def notification(text):
    fut = asyncio.run_coroutine_threadsafe(send_welcome(text), zalupa)


async def send_welcome(text):
    uzs = _u.get_user_ids()
    for u in uzs: