Skip to main content

aiothreema

Async Python client for the Threema Gateway HTTP API — send simple or end-to-end encrypted text messages from asyncio code.

This library implements the Gateway's HTTP wire protocol and NaCl-based end-to-end encryption directly (the official threema.gateway SDK is unmaintained), built on aiohttp and PyNaCl.

Install

pip install aiothreema

Usage

import asyncio

from aiothreema import ThreemaGatewayClient


async def main() -> None:
    async with ThreemaGatewayClient("*GATEWAY", "api-secret") as client:
        await client.validate_credentials()
        message_id = await client.send_text_message("ABCD1234", "Hello!")
        print(message_id)


asyncio.run(main())

End-to-end encryption

Pass a private key to send E2E-encrypted messages. The recipient's public key is looked up automatically via the Gateway's /pubkeys/{id} endpoint.

async with ThreemaGatewayClient(
    "*GATEWAY", "api-secret", private_key="<64-char hex>"
) as client:
    await client.send_text_message("ABCD1234", "Hello, encrypted!")

Generating a key pair

from aiothreema import generate_key_pair, derive_public_key

private_key, public_key = generate_key_pair()
# Register public_key with your Gateway account at gateway.threema.ch,
# then store private_key securely — it cannot be recovered.

assert derive_public_key(private_key) == public_key

Gateway QR code

Recipients can verify the Gateway's public key by scanning its Threema ID QR code (3mid:<id>,<public key>) in the Threema app:

from aiothreema import generate_qr_code

svg = generate_qr_code(client.gateway_id, client.public_key)
png = generate_qr_code(client.gateway_id, client.public_key, kind="png", scale=8)

client.public_key is derived from the private key, and is None for simple (non-E2E) mode. Rendering is CPU-bound, so run it in an executor when calling it from an event loop. qr_code_payload() returns just the encoded text.

Checking remaining credits

remaining = await client.get_credits()  # int

Using an existing aiohttp.ClientSession

When embedding this client in a larger application (e.g. a long-lived service that already manages its own session pool), pass a session explicitly instead of using the context-manager form — the client will not close a session it doesn't own:

client = ThreemaGatewayClient("*GATEWAY", "api-secret", session=my_session)
await client.send_text_message("ABCD1234", "Hello!")

Rate limiting and retries

Each client throttles its own requests and retries transient failures:

client = ThreemaGatewayClient(
    "*GATEWAY",
    "api-secret",
    rate_limit=10,  # max requests per second, None to disable (default: 10)
    max_retries=3,  # retries per request, 0 to disable (default: 3)
)
  • Retries use exponential backoff with jitter (about 1s, 2s, 4s, … capped at 30s).
  • On HTTP 429 the Gateway's Retry-After header is honored, and all other requests of the client are held back for that long. If the requested wait exceeds 30s, or the retries are used up, ThreemaRateLimitError is raised with the wait in retry_after.
  • Lookups (credits, public keys) are also retried on HTTP 5xx, connection errors and timeouts.
  • Sending a message is only retried when the Gateway definitely did not accept it (HTTP 429, or the connection could not be established). After a timeout or HTTP 5xx the message may already be on its way, so the error is raised instead of risking a duplicate.

Note that an end-to-end encrypted send counts as two requests (public key lookup and send).

Errors

All errors inherit from ThreemaGatewayError:

  • ThreemaAuthError — the Gateway ID or API secret was rejected.
  • ThreemaConnectionError — a network/transport failure talking to the Gateway.
  • ThreemaSendError — sending a message, or resolving a recipient's public key, failed.
  • ThreemaNoCreditsError — the account is out of credits (HTTP 402 on send). Subclasses ThreemaSendError.
  • ThreemaRateLimitError — the Gateway kept answering HTTP 429. Subclasses both ThreemaSendError and ThreemaConnectionError, so existing handlers keep catching it.

Development

pip install -e ".[test]"
pytest --cov=aiothreema

License

MIT

Metadata

Release files for aiothreema 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiothreema 0.3.0
File Size Uploaded Provenance Actions
aiothreema-0.3.0.tar.gz 14.7 kB With provenance Details for aiothreema-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiothreema 0.3.0
File Interpreter ABI Platform Actions
aiothreema-0.3.0-py3-none-any.whl Python 3 none any Details for aiothreema-0.3.0-py3-none-any.whl

Total release size: 25.9 kB

Release files / aiothreema-0.3.0.tar.gz

Download URL aiothreema-0.3.0.tar.gz
Size 14.7 kB
Tags Source
SHA-256 checksum
How to use checksums
82f51c75cc982560284ea0eae158904bfe2be41ebc0c504ebb50767387c40a14
BLAKE2b-256 checksum
How to use checksums
d4830bf9a3478adc220452649905646932d624b7ecf24ea386cf0712895aced2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Release files / aiothreema-0.3.0-py3-none-any.whl

Download URL aiothreema-0.3.0-py3-none-any.whl
Size 11.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
732e399b2f3bd0a66eecef23f47ff6468da587313048c700c1e79d30c43db44d
BLAKE2b-256 checksum
How to use checksums
c1ab008b7e51ec9adfae4f55c91207ae5bf02b883ae0fbdba8d653407775dbc1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

Security for aiothreema 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for aiothreema-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 23, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page