import json import os from urllib.request import Request, build_opener, ProxyHandler, HTTPRedirectHandler class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): raise ValueError("Redirect refused") def balance(): req = Request("http://127.0.0.1:7070/api/v5/btc/wallet/balance", data=b'{"net":"test","type":"segwit"}', headers={"Content-Type":"application/json", "X-BTC-KEY":os.environ["BTC_KEY"]}, method="POST") with build_opener(ProxyHandler({}), NoRedirect()).open(req, timeout=15) as response: raw = response.read(1048577) if len(raw) > 1048576: raise ValueError("Response too large") obj = json.loads(raw) if obj.get("ok") is not True: raise ValueError("Engine rejected request") sats = obj["result"]["balance_sat"] if type(sats) is not int or sats < 0: raise ValueError("Invalid balance") return {"net":"test", "type":"segwit", "balance_sat":sats} def run(event): # Call only AFTER external authentication and rate limiting. if event != {"operation":"balance"}: raise ValueError("Unexpected webhook input") return balance() if __name__ == "__main__": print(json.dumps(run({'operation': 'balance'})))