telegram-gifts-fetcher 1.0.2
A Python library to fetch Telegram gifts data
Requires Python: >=3.8

# 🎁 Telegram Gifts Fetcher

A Python library to fetch Telegram gifts data using the Telegram API. This library provides an easy-to-use interface for retrieving and managing Telegram gifts information.

## ✨ Features

- 🔄 Asynchronous API for better performance
- 📦 Easy-to-use context manager support
- 🎯 Fetch individual gifts or all gifts with pagination
- 💾 Export gifts data to JSON format
- 📊 Built-in gifts summary and statistics
- 🔐 Secure credential management with environment variables
- 📝 Comprehensive logging with loguru

## 📋 Requirements

- Python 3.8+
- Telegram API credentials (API ID and API Hash)

## 🚀 Installation

```bash
pip install telegram-gifts-fetcher
```

## ⚙️ Configuration

1. Get your Telegram API credentials from [my.telegram.org/apps](https://my.telegram.org/apps)
2. Create a `.env` file in your project directory:

```env
API_ID=12345678
API_HASH=your_api_hash_here
SESSION_NAME=account
```

## 📖 Usage Examples

### Example 1: Fetch All Gifts and Save to JSON

```python
import asyncio
import json
from telegram_gifts_fetcher import TelegramGiftsClient

async def fetch_and_save_gifts():
    """Fetch all gifts and save them to a JSON file."""
    async with TelegramGiftsClient() as client:
        # Get all gifts using pagination
        all_gifts = await client.get_all_gifts()
        
        # Prepare data for JSON export
        gifts_data = {
            "username": "monk",
            "total_count": len(all_gifts),
            "gifts": [
                {
                    "name": gift.name,
                    "slug": gift.slug,
                    "type": gift.type,
                    "message": gift.message,
                    "received_date": gift.received_date,
                    "name_hidden": gift.name_hidden,
                    "can_upgrade": gift.can_upgrade,
                    "pinned_to_top": gift.pinned_to_top,
                    "transfer_stars": gift.transfer_stars,
                    "user_convert_stars": gift.user_convert_stars,
                    "received_datetime": gift.received_datetime.isoformat() if gift.received_datetime else None
                }
                for gift in all_gifts
            ]
        }
        
        # Save to JSON file
        with open("monk_gifts.json", "w", encoding="utf-8") as f:
            json.dump(gifts_data, f, indent=2, ensure_ascii=False)
        
        print(f"✅ Saved {len(all_gifts)} gifts to monk_gifts.json")

if __name__ == "__main__":
    asyncio.run(fetch_and_save_gifts())
```

### Example 2: Real-time Gifts Monitor

```python
import asyncio
from datetime import datetime
from telegram_gifts_fetcher import TelegramGiftsClient
from loguru import logger

async def monitor_gifts():
    """Monitor gifts in real-time and log new ones."""
    username = "monk"
    known_gifts = set()
    
    async with TelegramGiftsClient() as client:
        logger.info(f"🔍 Starting gifts monitor for user: {username}")
        
        while True:
            try:
                # Fetch current gifts
                current_gifts = await client.get_all_gifts()
                current_slugs = {gift.slug for gift in current_gifts}
                
                # Check for new gifts
                new_gifts = current_slugs - known_gifts
                if new_gifts:
                    for gift in current_gifts:
                        if gift.slug in new_gifts:
                            logger.success(f"🎁 New gift detected: {gift.name} ({gift.type})")
                            logger.info(f"📝 Message: {gift.message or 'No message'}")
                            logger.info(f"⭐ Stars: {gift.transfer_stars}")
                
                known_gifts = current_slugs
                
                # Wait before next check
                await asyncio.sleep(30)  # Check every 30 seconds
                
            except KeyboardInterrupt:
                logger.info("🛑 Monitor stopped by user")
                break
            except Exception as e:
                logger.error(f"❌ Error in monitor: {e}")
                await asyncio.sleep(60)  # Wait longer on error

if __name__ == "__main__":
    asyncio.run(monitor_gifts())
```

### Example 3: Gifts Analytics Dashboard

```python
import asyncio
from collections import defaultdict
from datetime import datetime, timedelta
from telegram_gifts_fetcher import TelegramGiftsClient
from loguru import logger

async def analyze_gifts():
    """Analyze gifts data and generate statistics."""
    username = "monk"
    
    async with TelegramGiftsClient() as client:
        logger.info(f"📊 Generating analytics for user: {username}")
        
        # Fetch all gifts
        all_gifts = await client.get_all_gifts()
        
        if not all_gifts:
            logger.warning("⚠️ No gifts found for analysis")
            return
        
        # Basic statistics
        total_gifts = len(all_gifts)
        total_stars = sum(gift.transfer_stars for gift in all_gifts)
        total_convertible = sum(gift.user_convert_stars for gift in all_gifts)
        
        logger.info(f"\n📈 GIFTS ANALYTICS FOR {username.upper()}")
        logger.info("=" * 50)
        logger.info(f"🎁 Total Gifts: {total_gifts}")
        logger.info(f"⭐ Total Stars Value: {total_stars:,}")
        logger.info(f"💰 Convertible Stars: {total_convertible:,}")
        
        # Gifts by type
        type_stats = defaultdict(int)
        type_stars = defaultdict(int)
        for gift in all_gifts:
            type_stats[gift.type] += 1
            type_stars[gift.type] += gift.transfer_stars
        
        logger.info(f"\n📊 GIFTS BY TYPE:")
        for gift_type, count in sorted(type_stats.items()):
            avg_stars = type_stars[gift_type] / count if count > 0 else 0
            logger.info(f"  {gift_type}: {count} gifts (avg {avg_stars:.1f} stars)")
        
        # Recent activity (last 30 days)
        now = datetime.now()
        recent_cutoff = now - timedelta(days=30)
        recent_gifts = [
            gift for gift in all_gifts 
            if gift.received_datetime and gift.received_datetime >= recent_cutoff
        ]
        
        logger.info(f"\n🕒 RECENT ACTIVITY (Last 30 days):")
        logger.info(f"  Recent Gifts: {len(recent_gifts)}")
        if recent_gifts:
            recent_stars = sum(gift.transfer_stars for gift in recent_gifts)
            logger.info(f"  Recent Stars: {recent_stars:,}")
            logger.info(f"  Daily Average: {len(recent_gifts) / 30:.1f} gifts/day")
        
        # Premium features analysis
        upgradeable = [gift for gift in all_gifts if gift.can_upgrade]
        pinned = [gift for gift in all_gifts if gift.pinned_to_top]
        hidden = [gift for gift in all_gifts if gift.name_hidden]
        
        logger.info(f"\n🔧 FEATURES ANALYSIS:")
        logger.info(f"  Upgradeable Gifts: {len(upgradeable)} ({len(upgradeable)/total_gifts*100:.1f}%)")
        logger.info(f"  Pinned Gifts: {len(pinned)} ({len(pinned)/total_gifts*100:.1f}%)")
        logger.info(f"  Hidden Name Gifts: {len(hidden)} ({len(hidden)/total_gifts*100:.1f}%)")
        
        # Top valuable gifts
        top_gifts = sorted(all_gifts, key=lambda x: x.transfer_stars, reverse=True)[:5]
        logger.info(f"\n🏆 TOP 5 MOST VALUABLE GIFTS:")
        for i, gift in enumerate(top_gifts, 1):
            date_str = gift.received_datetime.strftime('%Y-%m-%d') if gift.received_datetime else 'Unknown'
            logger.info(f"  {i}. {gift.name} - {gift.transfer_stars} stars ({date_str})")

if __name__ == "__main__":
    asyncio.run(analyze_gifts())
```

## 🔧 API Reference

### TelegramGiftsClient

Main client class for interacting with Telegram gifts.

#### Methods

- `__init__(api_id=None, api_hash=None, session_name=None)` - Initialize client
- `async connect()` - Connect to Telegram
- `async disconnect()` - Disconnect from Telegram
- `async fetch_gifts(offset="")` - Fetch gifts with pagination
- `async get_all_gifts()` - Fetch all gifts using pagination
- `print_gifts_summary(gifts)` - Print gifts statistics

### Gift Model

Data class representing a Telegram gift.

#### Properties

- `name: str` - Gift name
- `slug: str` - Gift unique identifier
- `type: str` - Gift type (e.g., "stars_gift", "premium_gift")
- `message: Optional[str]` - Gift message
- `received_date: Optional[int]` - Unix timestamp
- `received_datetime: Optional[datetime]` - Converted datetime object
- `name_hidden: bool` - Whether sender name is hidden
- `can_upgrade: bool` - Whether gift can be upgraded
- `pinned_to_top: bool` - Whether gift is pinned
- `transfer_stars: int` - Stars value for transfer
- `user_convert_stars: int` - Stars value for conversion

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## ⚠️ Disclaimer

This library is for educational and personal use only. Make sure to comply with Telegram's Terms of Service when using this library.

## 🔗 Links

- [PyPI Package](https://pypi.org/project/telegram-gifts-fetcher/)
- [GitHub Repository](https://github.com/Th3ryks/TelegramGiftsFetcher)
- [Telegram API Documentation](https://core.telegram.org/api)