web3.py 做简易的余额警报系统



 

1,安装库web3

2,json文件配置样例:

{
“chainurl”:”https://bsc-dataseed.binance.org/”,
“abiFILE”:””,
“checkAddress”:”0x………………………………..”,
“coinAddress”:””,
“alertAmount”:0.005,
“symbol”:”BNB”,
“equal”:”<“,
“note”:”紧急!BNB不足需要补充”
}

3,核心示例代码:(请根据自己的逻辑业务需求修改)

def job():

global nowindex,alertList
if nowindex < len(configList)-1:
nowindex=nowindex+1
else:
nowindex=0
myitem=configList[nowindex]
# print()
web1 = Web3(Web3.HTTPProvider(myitem[“chainurl”], request_kwargs={‘timeout’: 20}))

checkAddress = web1.toChecksumAddress(myitem[“checkAddress”])

# print(decimal_coin)
if myitem[“coinAddress”]==””:
coin_balance =web1.eth.getBalance(checkAddress)/ 10**18
else:
coinABI = open(f'{myitem[“abiFILE”]}’, ‘r’).read().replace(‘\n’, ”)
coinAddress = web1.toChecksumAddress(myitem[“coinAddress”])
contract_coin = web1.eth.contract(address=coinAddress, abi=coinABI)
decimal_coin = 10 ** contract_coin.functions.decimals().call()
coin_balance = contract_coin.functions.balanceOf(checkAddress).call() / decimal_coin
coin_balance = Decimal(coin_balance).quantize(Decimal(“0.0000”))
mailFlag=False
if coin_balance >= myitem[“alertAmount”] and myitem[‘equal’]==”>”:
mailFlag = True
myPrint(time.strftime(‘%H:%M:%S ‘, time.localtime(time.time())) +f”库存{myitem[‘symbol’]}: {coin_balance}{myitem[‘equal’]}{myitem[‘alertAmount’]} ” + myitem[“note”], type=”warning”)
elif coin_balance <= myitem[“alertAmount”] and myitem[‘equal’]==”<“:
mailFlag = True
myPrint(time.strftime(‘%H:%M:%S ‘, time.localtime(time.time())) +f”库存{myitem[‘symbol’]}: {coin_balance}{myitem[‘equal’]}{myitem[‘alertAmount’]} ” + myitem[“note”],type=”warning”)
else:
myPrint(time.strftime(‘%H:%M:%S ‘, time.localtime(time.time())) + f”库存{myitem[‘symbol’]}: {coin_balance}{myitem[‘equal’]}{myitem[‘alertAmount’]}=False”, type=””)

today=time.strftime(‘%Y%m%d%H’, time.localtime(time.time()))
if today+myitem[“note”] not in alertList and mailFlag:
alertList.append(today+myitem[“note”])
myMail.sendSMTPMail(“BalanceAlertSystem”,”余额预警信息!”,f’时间:{time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime(time.time()))}\n库存:{myitem[“symbol”]} {coin_balance}{myitem[“equal”]}{myitem[“alertAmount”]}\n提示:{myitem[“note”]}’)
if len(alertList)>200:
alertList.remove(alertList[0])