Skip to main content

Python library to interface with the myTNB API (Tenaga Nasional Berhad)

Project description

PyPI version CI

python-mytnb

A Python library to interface with the myTNB (Tenaga Nasional Berhad) API for electricity account management and usage monitoring in Malaysia.

Installation

uv add python-mytnb

Or with pip:

pip install python-mytnb

Quick Start

import asyncio
from mytnb import MyTNBClient

async def main():
    client = await MyTNBClient.login("user@example.com", "your-password")

    async with client:
        # Auto-discover linked accounts
        accounts = await client.get_customer_accounts()
        for acc in accounts:
            print(f"{acc.account_number}{acc.owner_name} (SMR: {acc.is_smart_meter})")

        # Get smart meter usage & billing history
        usage = await client.get_account_usage_smart("220123456789")

        # Monthly billing breakdown
        for month in usage.by_month.months:
            print(f"{month.month} {month.year}: {month.usage_total} kWh — RM {month.amount_total}")

        # Bill history, payment history & due amount
        history = await client.get_bill_history("220123456789")
        payments = await client.get_payment_history("220123456789")
        due = await client.get_account_due_amount("220123456789")

        # Most account-scoped methods also accept a CustomerAccount directly
        # (is_owner and account_type are derived automatically)
        for acc in accounts:
            if acc.is_smart_meter:
                usage = await client.get_account_usage_smart(acc)

asyncio.run(main())

CLI

The mytnb command-line tool requires the optional cli extra (it pulls in click and rich, which the library itself does not need). If you installed without it, mytnb (or python -m mytnb) will fail to start:

pip install "python-mytnb[cli]"

Pass credentials directly:

mytnb --email user@example.com --password yourpass usage 220123456789

Or via environment variables:

export MYTNB_EMAIL=user@example.com
export MYTNB_PASSWORD=yourpass
mytnb usage 220123456789

All commands:

mytnb login                                  # Test login, show user info
mytnb accounts                               # List all linked accounts (auto-discovery)
mytnb accounts --json                        # Account list as JSON
mytnb usage <account>                        # Monthly usage & billing summary
mytnb usage --daily <account>                # Daily usage breakdown
mytnb usage --json <account>                 # Full usage data as JSON
mytnb current-usage <account>                # Simplified current usage summary
mytnb due-amount <account>                   # Outstanding balance
mytnb bill-history <account>                 # Bill history (bills issued)
mytnb payment-history <account>              # Bill & payment history

Global options: --debug for full tracebacks, --version.

Use a config file instead of flags (--config <path>, mytnb.json, or ~/.config/mytnb/config.json):

mytnb init-config   # Generate a starter config file

API Architecture

myTNB uses two API backends, both handled transparently by this library:

Backend Domain Auth Used for
REST api.mytnb.com.my JWT + API key Bill eligibility, eligibility icons
AWS Gateway api.mytnb.com.my/core/api Encrypted payloads (AES-256-CBC + RSA-OAEP) Account listing (auto-discovery)
Legacy ASMX mytnbapp.tnb.com.my Encrypted payloads (AES-256-CBC + RSA-OAEP) Usage data, billing, services

Request encryption for the ASMX API is automatic — just pass plaintext parameters.

Data Models

Model Description
CustomerAccount Linked account: number, owner, address, SMR status
AccountUsage Full usage response: metrics, monthly and daily data
UsageMetric Current/average usage (kWh)
CostMetric Current/projected cost (RM)
BillingMonth Monthly billing record with tariff blocks
DailyUsage Daily consumption and cost
TariffBlock Tariff pricing block details
BillHistoryEntry Single bill issued (date, amount, billing number)
PaymentHistoryEntry Bill or payment entry with type, method, reference
AccountDueAmount Outstanding balance and due date
SMRAccount Smart Meter Reading eligibility status
BREligibility Bill rendering opt-in status

Geographic Restrictions

The myTNB API only accepts connections from Malaysian IP addresses and blocks most VPN services. If you get a GeoBlockedError (HTTP 403), make sure you are connecting from a Malaysian network without a VPN.

Error Handling

from mytnb.exceptions import MyTNBError, APIError, AuthenticationError, GeoBlockedError

try:
    client = await MyTNBClient.login("user@example.com", "password")
    async with client:
        usage = await client.get_account_usage_smart("220123456789")
except GeoBlockedError:
    print("Blocked — connect from a Malaysian IP without VPN")
except AuthenticationError:
    print("Invalid email or password")
except APIError as e:
    print(f"API error {e.error_code}: {e.display_message}")
except MyTNBError as e:
    print(f"Error: {e}")

Development

uv sync --extra dev
uv run pytest
uv run pylint src/mytnb/

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_mytnb-0.5.4.tar.gz (74.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

python_mytnb-0.5.4-py3-none-any.whl (29.0 kB view details)

Uploaded Python 3

File details

Details for the file python_mytnb-0.5.4.tar.gz.

File metadata

  • Download URL: python_mytnb-0.5.4.tar.gz
  • Upload date:
  • Size: 74.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for python_mytnb-0.5.4.tar.gz
Algorithm Hash digest
SHA256 2a5e9db2a1bafe0dcbcf6f73bb380ec6f45a96280d024cff43c0887fbf64ece2
MD5 6372926d8f53b9fdc01df92102065aa9
BLAKE2b-256 8ef387b4f070fa879aa9c025dddd60e34be0eaac18f5b604740917f1417bdb7f

See more details on using hashes here.

Provenance

The following attestation bundles were made for python_mytnb-0.5.4.tar.gz:

Publisher: publish.yml on danieyal/python-mytnb

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file python_mytnb-0.5.4-py3-none-any.whl.

File metadata

  • Download URL: python_mytnb-0.5.4-py3-none-any.whl
  • Upload date:
  • Size: 29.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for python_mytnb-0.5.4-py3-none-any.whl
Algorithm Hash digest
SHA256 6d5b9a8c0f789bb607dd19d79317593e1d0f891584191d184bfb2af367f4531e
MD5 760705c53faded340266350314e00ce6
BLAKE2b-256 b15d9993179023da97aaacb46a5f3e83f3669c4972f8a838a652aa6ba2bf3d57

See more details on using hashes here.

Provenance

The following attestation bundles were made for python_mytnb-0.5.4-py3-none-any.whl:

Publisher: publish.yml on danieyal/python-mytnb

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page