Skip to main content

Python SDK for the Trustat API — Telegram & MAX channel analytics, posts, and Telegram Ads.

Project description

Trustat Python SDK

PyPI Python CI License: MIT

The Python SDK for the Trustat API — analytics for Telegram & MAX channels: profiles, statistics, subscriber/views dynamics, mentions, forwards, posts and edit history, and the Telegram Ads database.

Typed (Pydantic v2), sync and async, with automatic pagination, retries, and a clean error hierarchy.

Install

pip install trustat

Requires Python 3.10+.

Quickstart

from trustat import Trustat

client = Trustat(api_key="tk_...")          # or set TRUSTAT_API_KEY

channel = client.channels.get("durov")       # id, username, @username, or +hash
print(channel.title, channel.participants)

stat = client.channels.stat("durov")
print(stat.er_day, stat.quality_score)

# auto-paginating: iterate the whole result set, pages fetched lazily
for post in client.posts.search(q="bitcoin", limit=50):
    print(post.message_id, post.views)

The client holds a pooled connection — reuse one instance, and close it when done (or use it as a context manager):

with Trustat(api_key="tk_...") as client:
    ...

Authentication

Pass api_key= or set the TRUSTAT_API_KEY environment variable. The key is sent as Authorization: Bearer <key> by default; pass auth_header="x-api-key" to use the X-API-Key header instead. Override the host with base_url= or TRUSTAT_BASE_URL.

Async

Every method has an async twin on AsyncTrustat — identical signatures, just await:

import asyncio
from trustat import AsyncTrustat

async def main():
    async with AsyncTrustat(api_key="tk_...") as client:
        channel = await client.channels.get("durov")

        # auto-paginate without awaiting first:
        async for ch in client.channels.search(q="news"):
            print(ch.title)

asyncio.run(main())

Pagination

List methods (search, catalog, channel posts/mentions/forwards/ads, ads.search, ads.by_advertiser) return a page you can iterate directly — it transparently fetches subsequent pages:

page = client.channels.search(q="news", limit=50)
print(page.total)            # approximate match count (informational)
print(page.next_cursor)      # the cursor for the next page
print(page.rate_limit.remaining, page.quota.requests_remaining)

for ch in page:              # iterates EVERY result across all pages, lazily
    ...

for one_page in page.iter_pages():   # or iterate page-by-page
    print(len(one_page))

Never use page.total to bound a loop — it is approximate. Iterating until exhaustion is correct. (Mentions and forwards are depth-capped server-side at ~10k results; iterate within a date window for deeper history.)

Errors

from trustat import NotFoundError, RateLimitError, QuotaReachedError, TrustatError

try:
    client.channels.get("does-not-exist")
except NotFoundError as e:
    print(e.code, e.request_id)        # "not_found", "req_..."
except RateLimitError as e:
    print("retry after", e.retry_after)
except QuotaReachedError as e:
    print("quota:", e.reason)          # "requests" | "channels" | "listing"
except TrustatError:
    ...                                 # base class — catches everything

The SDK automatically retries transient failures (429, 5xx, connection/timeout errors) with exponential backoff + jitter, honoring Retry-After / RateLimit-Reset. Configure with max_retries= and timeout=.

Resources

Namespace Highlights
client.channels get, stat, batch, subscribers, views, reach, mentions, forwards, posts, ads, catalog, search
client.posts search, get, history, stat
client.ads search, get, facets, timeline, by_advertiser
client.lookup resolve any id / link / @username → canonical ids (client.lookup("durov"))
client.dictionaries categories, countries, languages
client.usage info — your current quota consumption
client.system health, version

Configuration

Trustat(
    api_key=None,            # or TRUSTAT_API_KEY
    base_url=None,           # or TRUSTAT_BASE_URL
    auth_header="authorization",  # or "x-api-key"
    timeout=None,            # httpx.Timeout or seconds
    max_retries=2,
    default_headers=None,
    default_query=None,
    http_client=None,        # inject your own httpx.Client (proxies, transport, ...)
)

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

trustat-0.1.0.tar.gz (27.0 kB view details)

Uploaded Source

Built Distribution

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

trustat-0.1.0-py3-none-any.whl (35.4 kB view details)

Uploaded Python 3

File details

Details for the file trustat-0.1.0.tar.gz.

File metadata

  • Download URL: trustat-0.1.0.tar.gz
  • Upload date:
  • Size: 27.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for trustat-0.1.0.tar.gz
Algorithm Hash digest
SHA256 b418f36a63c3d5833cacc16fb8d03a693c456ce66fab49ffa5c818b34c983d11
MD5 303da6ceff495f65ba2cc3b86aeaf712
BLAKE2b-256 0100f38f18251d742b883e936ec0d1ac92171c2109355ae458db60c879dd9025

See more details on using hashes here.

Provenance

The following attestation bundles were made for trustat-0.1.0.tar.gz:

Publisher: release.yml on Trustat-Analytics/trustat-python

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

File details

Details for the file trustat-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: trustat-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 35.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for trustat-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0df319ea2094fe69ba1f7aa0a2f46a91ecbc317b2398709f3ec9fd3f3ab45341
MD5 a2ad86d84ad8b809abaad33bc4897fcf
BLAKE2b-256 2ad8e03a0c2067c6827f835d45a100710aeaff7912bcfcaebb11a20a050c35a9

See more details on using hashes here.

Provenance

The following attestation bundles were made for trustat-0.1.0-py3-none-any.whl:

Publisher: release.yml on Trustat-Analytics/trustat-python

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