Lightweight Python SDK for tgram-analytics
Project description
tgram-analytics Python SDK
Lightweight Python SDK for tgram-analytics. Track events and pageviews from your Python backend.
Install
pip install tgram-analytics
Get a free proj_ API key from @MyTelegramAnalyticsBot on Telegram (1 project free), or self-host the server and create keys via your own bot.
Quick start (sync)
from tgram_analytics import TGA
with TGA("proj_xxx", "https://analytics.example.com") as tga:
tga.track("signup", session_id="user-session-123", properties={"plan": "pro"})
tga.pageview(session_id="user-session-123", url="/dashboard")
Quick start (async)
from tgram_analytics import AsyncTGA
async with AsyncTGA("proj_xxx", "https://analytics.example.com") as tga:
tga.track("signup", session_id="user-session-123")
await tga.flush()
Batching
Buffer events and send them in batches to reduce HTTP requests:
from tgram_analytics import TGA, BatchOptions
tga = TGA("proj_xxx", "https://analytics.example.com", batch=BatchOptions(max_size=20, max_wait=3.0))
# Events are buffered and auto-flushed when max_size is reached or max_wait seconds elapse
tga.track("click", "session-1")
tga.flush() # manual flush
tga.close() # flushes + closes HTTP client
Identifying users
Attach persistent properties to a session. All subsequent track() and pageview() calls for that session will include them:
tga.identify("session-123", {"plan": "pro", "locale": "en-US"})
tga.track("purchase", "session-123", {"amount": 49})
# sent properties: {"plan": "pro", "locale": "en-US", "amount": 49}
Per-event properties override identified properties when keys conflict.
Call tga.forget("session-123") to clear stored properties for a session.
Multi-value properties
Properties accept lists of scalars in addition to single scalars — useful for multi-select inputs, A/B variant memberships, or any set-style attribute that would otherwise be lossy to flatten:
tga.track(
"onboarding_completed",
session_id="user-session-123",
properties={
"role": "creator",
"interest_set": ["vertical_to_horizontal", "unsure"], # list of strings
},
)
Allowed value shapes:
| Shape | Allowed? | Example |
|---|---|---|
Scalar (str, int, float, bool, None) |
✅ | {"amount": 49} |
| List of scalars | ✅ | {"tags_set": ["a", "b"]} |
| Nested dict | ❌ — raises TypeError |
{"user": {"id": 1}} |
| Nested list | ❌ — raises TypeError |
{"matrix": [[1, 2]]} |
NaN / Infinity |
❌ — raises TypeError |
{"x": float("nan")} |
Keys ending in _set are sorted alphabetically/numerically by the server at write time, so GROUP BY properties->'interest_set' collapses ["a", "b"] and ["b", "a"] into one bucket. Other list properties keep insertion order.
Two canonical SQL queries for dashboards:
-- Per-element count (pie chart):
SELECT elem, count(*) AS n
FROM events, jsonb_array_elements_text(properties->'interest_set') AS elem
WHERE event_name = 'onboarding_completed'
GROUP BY elem
ORDER BY n DESC;
-- Most common combos:
SELECT properties->'interest_set' AS combo, count(*) AS n
FROM events
WHERE event_name = 'onboarding_completed'
GROUP BY combo
ORDER BY n DESC
LIMIT 20;
API reference
TGA(api_key, server_url, *, batch=False, timeout=10.0)
Sync client. api_key must start with "proj_".
batch—False(default),True(default thresholds), orBatchOptions(max_size=10, max_wait=5.0)timeout— HTTP request timeout in seconds
AsyncTGA(api_key, server_url, *, batch=False, timeout=10.0)
Async client with the same constructor signature.
.track(event_name, session_id, properties=None)
Track a custom event. Fire-and-forget — errors are logged, never raised.
.pageview(session_id, url, referrer=None, properties=None)
Track a pageview event.
.identify(session_id, properties)
Store properties that are merged into all subsequent events for this session.
.forget(session_id)
Remove stored identify() properties for a session.
.flush()
Send all buffered events immediately. No-op if batching is disabled.
.close() / await .close()
Flush pending events and close the HTTP client.
Both clients support context managers (with / async with) for automatic cleanup.
Error handling
Analytics should never break your application. All HTTP and network errors are caught and logged via Python's logging module under the tgram_analytics logger:
import logging
logging.getLogger("tgram_analytics").setLevel(logging.DEBUG)
Only the constructor raises exceptions (on invalid api_key or missing server_url).
License
MIT
Links
- Website: https://tgram-analytics.com
- Server (API): https://github.com/tgram-analytics/server
- JS SDK: https://github.com/tgram-analytics/tgram-analytics-js
- Python SDK: https://github.com/tgram-analytics/tgram-analytics-py
- Flutter SDK: https://github.com/tgram-analytics/tgram-analytics-flutter
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tgram_analytics-0.2.0.tar.gz.
File metadata
- Download URL: tgram_analytics-0.2.0.tar.gz
- Upload date:
- Size: 14.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
79dd61d5d76e50dc83bde3841008321a295b9c68dd0a24f1b1e79082d67d666b
|
|
| MD5 |
1b459dffeeefc1075f23b839248c2057
|
|
| BLAKE2b-256 |
541e288f52d18b86e0da91c31c3a9ffbe13a4f00ee776495d4089031dcf60817
|
Provenance
The following attestation bundles were made for tgram_analytics-0.2.0.tar.gz:
Publisher:
publish.yml on tgram-analytics/tgram-analytics-py
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
tgram_analytics-0.2.0.tar.gz -
Subject digest:
79dd61d5d76e50dc83bde3841008321a295b9c68dd0a24f1b1e79082d67d666b - Sigstore transparency entry: 1553651599
- Sigstore integration time:
-
Permalink:
tgram-analytics/tgram-analytics-py@a8cd89a927eb1e2d430f9950832ad49a6ac560cb -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/tgram-analytics
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@a8cd89a927eb1e2d430f9950832ad49a6ac560cb -
Trigger Event:
release
-
Statement type:
File details
Details for the file tgram_analytics-0.2.0-py3-none-any.whl.
File metadata
- Download URL: tgram_analytics-0.2.0-py3-none-any.whl
- Upload date:
- Size: 12.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
f484fc112d5f03713cf0595e249595f49422f7a99480205f4b5a83584946bde6
|
|
| MD5 |
62b85209505e87b045d474dfae5ed3c4
|
|
| BLAKE2b-256 |
8ddd9a825424561cbd3da2b7bd1674d790af4c9d7e3fff2f2a1b86ea1f7dd4ea
|
Provenance
The following attestation bundles were made for tgram_analytics-0.2.0-py3-none-any.whl:
Publisher:
publish.yml on tgram-analytics/tgram-analytics-py
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
tgram_analytics-0.2.0-py3-none-any.whl -
Subject digest:
f484fc112d5f03713cf0595e249595f49422f7a99480205f4b5a83584946bde6 - Sigstore transparency entry: 1553651634
- Sigstore integration time:
-
Permalink:
tgram-analytics/tgram-analytics-py@a8cd89a927eb1e2d430f9950832ad49a6ac560cb -
Branch / Tag:
refs/tags/v0.2.0 - Owner: https://github.com/tgram-analytics
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@a8cd89a927eb1e2d430f9950832ad49a6ac560cb -
Trigger Event:
release
-
Statement type: