The TonapiWebhookDispatcher manages handler registration, webhook lifecycle, and event routing. It is designed to receive incoming HTTP requests and route them to the correct handler.
Initialization:
dispatcher = TonapiWebhookDispatcher(
url="https://example.com",
client=client,
accounts=["EQ..."],
opcodes=["0x7362d09c"],
db=database # Example dependency
)
Registering Handlers:
Use decorators to register handlers. Decorators can accept *accounts for local filtering and a path for custom URL paths. Default paths are /account-tx, /mempool-msg, /opcode-msg, and /new-contracts.
@dispatcher.account_tx()@dispatcher.mempool_msg()@dispatcher.opcode_msg()@dispatcher.new_contracts()
Lifecycle:
await dispatcher.setup(): Opens a session, creates webhooks, and subscribes to events. Existing webhooks are reused via ensure().await dispatcher.teardown(cleanup=True): Closes the session. If cleanup=True, it unsubscribes from all events first.
Processing Events:
When your web server receives a request, pass the data to process():
await dispatcher.process(
path="/account-tx",
data=payload,
authorization=headers.get("Authorization"),
)
Dependencies:
Dependencies passed to the constructor via **kwargs are injected into handlers. Per-request dependencies passed to process() take priority.
from pytonapi.webhook import TonapiWebhookClient, TonapiWebhookDispatcher
from pytonapi.types import Network
client = TonapiWebhookClient("YOUR_API_KEY", Network.MAINNET)
dispatcher = TonapiWebhookDispatcher(
"https://example.com",
client=client,
accounts=["EQ..."],
opcodes=["0x7362d09c"],
)
@dispatcher.account_tx()
async def handler(event: AccountTxEvent, db: Database) -> None:
await db.save(event)
# Lifecycle management
await dispatcher.setup()
# ... receive requests ...
await dispatcher.teardown(cleanup=True)