import asyncio from datetime import datetime from lnbits.core.models import Payment from lnbits.core.services import websocket_updater from lnbits.tasks import register_invoice_listener from loguru import logger from .crud import get_myextension, update_myextension from .models import CreateMyExtensionData from .transaction_processor import poll_lamassu_transactions ####################################### ########## RUN YOUR TASKS HERE ######## ####################################### # The usual task is to listen to invoices related to this extension async def wait_for_paid_invoices(): invoice_queue = asyncio.Queue() register_invoice_listener(invoice_queue, "ext_myextension") while True: payment = await invoice_queue.get() await on_invoice_paid(payment) async def hourly_transaction_polling(): """Background task that polls Lamassu database every hour for new transactions""" logger.info("Starting hourly Lamassu transaction polling task") while True: try: logger.info(f"Running Lamassu transaction poll at {datetime.now()}") await poll_lamassu_transactions() logger.info("Completed Lamassu transaction poll, sleeping for 1 hour") # Sleep for 1 hour (3600 seconds) await asyncio.sleep(3600) except Exception as e: logger.error(f"Error in hourly polling task: {e}") # Sleep for 5 minutes before retrying on error await asyncio.sleep(300) # Do somethhing when an invoice related top this extension is paid async def on_invoice_paid(payment: Payment) -> None: if payment.extra.get("tag") != "MyExtension": return myextension_id = payment.extra.get("myextensionId") assert myextension_id, "myextensionId not set in invoice" myextension = await get_myextension(myextension_id) assert myextension, "MyExtension does not exist" # update something in the db if payment.extra.get("lnurlwithdraw"): total = myextension.total - payment.amount else: total = myextension.total + payment.amount myextension.total = total await update_myextension(CreateMyExtensionData(**myextension.dict())) # here we could send some data to a websocket on # wss:///api/v1/ws/ and then listen to it on some_payment_data = { "name": myextension.name, "amount": payment.amount, "fee": payment.fee, "checking_id": payment.checking_id, } await websocket_updater(myextension_id, str(some_payment_data))