A Python SDK for Dashgram
Project description
Dashgram SDK
A Python SDK for Dashgram - Analytics and tracking for Telegram bots with seamless integration for popular Python Telegram bot frameworks.
Features
- 🚀 Easy Integration - Works with aiogram, python-telegram-bot, and pyTelegramBotAPI
- 📊 Event Tracking - Track messages, callback queries, and all Telegram update types
- 🔄 Framework Agnostic - Automatically detects your bot framework
- ⚡ Async Support - Full async/await support with automatic sync wrapper
- 🛡️ Error Handling - Robust error handling with configurable exception suppression
- 🎯 Invitation Tracking - Track user invitations and referrals
Supported Frameworks
- aiogram (v3.x)
- python-telegram-bot (v21.x)
- pyTelegramBotAPI (v4.x)
Installation
pip install dashgram
Quick Start
Basic Usage
from dashgram import Dashgram, HandlerType
# Initialize the SDK with your project credentials
sdk = Dashgram(
project_id="your_project_id",
access_key="your_access_key"
)
# Track any Telegram update
sdk.track_event(update)
# Track a specific event type
sdk.track_event(event_data, HandlerType.MESSAGE)
# Mark user as invited by another user (for referral analytics)
sdk.invited_by(user_id, inviter_user_id)
The event_data parameter should contain the update data in raw Telegram API format, or the corresponding update/message object from your framework (aiogram, python-telegram-bot, or pyTelegramBotAPI).
Framework Integration
aiogram
Choose the integration method that best fits your needs:
import asyncio
from aiogram import Bot, Dispatcher
from aiogram.types import Message, Update
from dashgram import Dashgram, HandlerType
# Initialize SDK with your credentials
sdk = Dashgram(
project_id="your_project_id",
access_key="your_access_key"
)
dp = Dispatcher()
# Option 1: Automatic tracking (recommended for most use cases)
sdk.bind_aiogram(dp)
@dp.message()
async def handle_message(message: Message, event_update: Update):
# Option 2: Manual tracking with full update data
await sdk.track_event(event_update)
...
@dp.edited_message()
async def handle_edited_message(edited_message: Message):
# Option 3: Manual tracking with specific handler type
await sdk.track_event(edited_message, HandlerType.EDITED_MESSAGE)
...
python-telegram-bot (v21.x)
from telegram.ext import Application, MessageHandler, filters
from dashgram import Dashgram
# Initialize SDK with your credentials
sdk = Dashgram(
project_id="your_project_id",
access_key="your_access_key"
)
async def handle_message(update, context):
# Manual tracking for specific events
await sdk.track_event(update)
...
application = Application.builder().token("YOUR_BOT_TOKEN").build()
application.add_handler(MessageHandler(filters.TEXT, handle_message))
# Automatic tracking for all events
sdk.bind_telegram(application)
application.run_polling()
pyTelegramBotAPI
import telebot
from dashgram import Dashgram, HandlerType
# Initialize SDK with your credentials
sdk = Dashgram(
project_id="your_project_id",
access_key="your_access_key"
)
bot = telebot.TeleBot("YOUR_BOT_TOKEN", use_class_middlewares=True)
# Automatic tracking for all events
sdk.bind_telebot(bot)
@bot.message_handler(func=lambda message: True)
def handle_message(message):
# Manual tracking for specific events
sdk.track_event(message, HandlerType.MESSAGE)
...
bot.polling()
API Reference
Dashgram Class
Constructor
Dashgram(
project_id: Union[int, str],
access_key: str,
*,
api_url: Optional[str] = None,
origin: Optional[str] = None
)
Parameters:
project_id- Your Dashgram project ID (found in your project settings)access_key- Your Dashgram access key (found in your project settings)api_url- Custom API URL (defaults tohttps://api.dashgram.io/v1)origin- Custom origin string for SDK usage analytics (optional)
Methods
track_event()
async def track_event(
event,
handler_type: Optional[HandlerType] = None,
suppress_exceptions: bool = True
) -> bool
Track a Telegram event or update. This method automatically detects the framework and extracts relevant data.
Parameters:
event- Telegram event object or dictionary (from any supported framework)handler_type- Type of handler (optional if event is a framework object)suppress_exceptions- Whether to suppress exceptions (default: True)
Returns: bool - True if successful, False otherwise
invited_by()
async def invited_by(
user_id: int,
invited_by: int,
suppress_exceptions: bool = True
) -> bool
Track user invitation/referral for analytics purposes.
Parameters:
user_id- ID of the invited userinvited_by- ID of the user who sent the invitationsuppress_exceptions- Whether to suppress exceptions (default: True)
Returns: bool - True if successful, False otherwise
Framework Binding Methods
def bind_aiogram(dp) -> None
def bind_telegram(app, group: int = -1, block: bool = False) -> None
def bind_telebot(bot) -> None
Automatically track all events for the respective framework. These methods integrate middleware or handlers to capture all bot interactions.
Examples
Complete aiogram Example
import asyncio
import logging
from os import getenv
from aiogram import Bot, Dispatcher, html
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from dashgram import Dashgram, HandlerType
# Setup logging
logging.basicConfig(level=logging.INFO)
# Initialize SDK with environment variables
sdk = Dashgram(
project_id=getenv("PROJECT_ID"),
access_key=getenv("ACCESS_KEY")
)
dp = Dispatcher()
# Manual tracking example
@dp.message(CommandStart())
async def start_handler(message: Message):
await message.answer(f"Hello, {html.bold(message.from_user.full_name)}!")
# Automatic tracking for all events
sdk.bind_aiogram(dp)
async def main():
bot = Bot(token=getenv("BOT_TOKEN"))
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())
Complete python-telegram-bot Example
import logging
from os import getenv
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters
from dashgram import Dashgram
# Setup logging
logging.basicConfig(level=logging.INFO)
# Initialize SDK with environment variables
sdk = Dashgram(
project_id=getenv("PROJECT_ID"),
access_key=getenv("ACCESS_KEY")
)
async def start(update: Update, context):
await update.message.reply_text("Hello!")
async def echo(update: Update, context):
await update.message.reply_text(update.message.text)
def main():
application = Application.builder().token(getenv("BOT_TOKEN")).build()
# Add handlers
application.add_handler(CommandHandler("start", start))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
# Automatic tracking for all events
sdk.bind_telegram(application)
application.run_polling()
if __name__ == "__main__":
main()
Complete pyTelegramBotAPI Example
import logging
from os import getenv
import telebot
from dashgram import Dashgram
# Setup logging
logging.basicConfig(level=logging.INFO)
# Initialize SDK with environment variables
sdk = Dashgram(
project_id=getenv("PROJECT_ID"),
access_key=getenv("ACCESS_KEY")
)
bot = telebot.TeleBot(getenv("BOT_TOKEN"), use_class_middlewares=True)
# Automatic tracking for all events
sdk.bind_telebot(bot)
@bot.message_handler(commands=['start'])
def start(message):
bot.reply_to(message, "Hello!")
@bot.message_handler(func=lambda message: True)
def echo(message):
bot.reply_to(message, message.text)
if __name__ == "__main__":
bot.polling()
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- 📧 Email: team@dashgram.io
- 📖 Documentation: docs.dashgram.io
- 🐛 Issues: GitHub Issues
- 💬 Community: Telegram Channel
Changelog
See CHANGELOG.md for a list of changes and version history.
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 dashgram-0.1.3.tar.gz.
File metadata
- Download URL: dashgram-0.1.3.tar.gz
- Upload date:
- Size: 14.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
59de0462f04f348e42af1e5a55976b1702eec0bd1a8d585c092036419dbae6f3
|
|
| MD5 |
0df3f6f911eb8f128654ad95f911dc56
|
|
| BLAKE2b-256 |
91a3100da189b278f396e4aeb810d2b9dc407da457625ba4bab4210f5361096c
|
Provenance
The following attestation bundles were made for dashgram-0.1.3.tar.gz:
Publisher:
publish.yml on Dashgram/sdk-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
dashgram-0.1.3.tar.gz -
Subject digest:
59de0462f04f348e42af1e5a55976b1702eec0bd1a8d585c092036419dbae6f3 - Sigstore transparency entry: 867380215
- Sigstore integration time:
-
Permalink:
Dashgram/sdk-python@9ce5948436f7ae6408d8b16e24c754c6d33c4ddb -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/Dashgram
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@9ce5948436f7ae6408d8b16e24c754c6d33c4ddb -
Trigger Event:
push
-
Statement type:
File details
Details for the file dashgram-0.1.3-py3-none-any.whl.
File metadata
- Download URL: dashgram-0.1.3-py3-none-any.whl
- Upload date:
- Size: 16.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
50f3dd80f6711bb5fc7f173b84c98b1cdf7f49242be28c633cc3c251e4d96156
|
|
| MD5 |
5d155bd85bdcf76877bedf32913edda8
|
|
| BLAKE2b-256 |
4cc34df77a99a6b99d23392a06152c342fa5bd7c64b2cc535f2cf089b132354f
|
Provenance
The following attestation bundles were made for dashgram-0.1.3-py3-none-any.whl:
Publisher:
publish.yml on Dashgram/sdk-python
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
dashgram-0.1.3-py3-none-any.whl -
Subject digest:
50f3dd80f6711bb5fc7f173b84c98b1cdf7f49242be28c633cc3c251e4d96156 - Sigstore transparency entry: 867380216
- Sigstore integration time:
-
Permalink:
Dashgram/sdk-python@9ce5948436f7ae6408d8b16e24c754c6d33c4ddb -
Branch / Tag:
refs/tags/v0.1.3 - Owner: https://github.com/Dashgram
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@9ce5948436f7ae6408d8b16e24c754c6d33c4ddb -
Trigger Event:
push
-
Statement type: