The Dev Insights
The Dev Insights
My Little Bot That Grabs Telegram Gifts
Back to Blog
Web DevelopmentOctober 18, 202511 min read

My Little Bot That Grabs Telegram Gifts

Web DevelopmentOctober 18, 202511 min read

Sometimes, the most fun projects are the ones that automate a small, annoying task, and my Telegram gift-buyer bot was exactly that for me.

You know those little annoyances in life that just nag at you? The ones you think, 'there has to be a better way than staring at my screen'? For me, recently, it was missing out on those fleeting digital gifts that pop up in Telegram channels. You blink, and they're gone. It's not exactly life-changing stuff, but it's a bit of a bummer when you're just a second too slow.

I mean, we've all been there, right? Staring at a screen, waiting for something to happen, and then... poof, missed it. Whether it's a flash sale, a limited-time offer, or, in my case, a Telegram gift, the feeling is the same. After one particularly frustrating evening, I thought, 'Alex, you're a software engineer, you build production systems for a living. Surely, you can do better than this.' And that, my friends, is how gift-buyer, my little Telegram bot, came to be.

What Even is 'Gift Sniping' on Telegram?

Before we get too deep into the code, let's clear up what I mean by 'gift sniping'. Telegram, for those who don't know, sometimes allows users or channels to send 'gifts' – things like Premium subscriptions or other digital goodies – which can be claimed by the first person to tap a link. These links usually appear in a chat message, often with a countdown or a limited number of claims. They're often gone in seconds, literally. Manual claiming is a mug's game.

My goal was simple: build a bot that could automatically detect these gift messages, extract the claim link, and attempt to claim it faster than any human could. It sounds a bit cheeky, I know, but it was primarily a learning exercise, and honestly, a bit of fun. Plus, it saved my thumb from endless scrolling and tapping! It's a classic example of using code to solve a very specific, somewhat niche, personal problem.

The Anatomy of a Telegram Gift-Buyer Bot

Building this bot meant getting stuck into the Telegram API. There are a few ways to do this, but for something that needs to act like a user (i.e., read all messages in a channel and react), you generally look at user-bot libraries rather than the standard Bot API. I went with telethon for Python, as I've used it before for other automation tasks, and it's pretty robust. Pyrogram is another excellent choice, but I'm just more familiar with telethon's quirks.

Getting Started: Connecting to Telegram

The first hurdle is always authentication. You need an API ID and hash from Telegram, which you can get from my.telegram.org. Once you have those, connecting is relatively straightforward. This part's pretty standard, but it's where a lot of people trip up if they're not careful with their API keys. Never hardcode them, always use environment variables! I ran into this last month when I was spinning up a new dev environment and accidentally pushed a config file with a placeholder key – thankfully, it was just a placeholder, but it's an easy mistake to make when you're rushing.

python
import os
from telethon import TelegramClient, events

# Grab your API ID and hash from environment variables
api_id = int(os.environ.get('TG_API_ID'))
api_hash = os.environ.get('TG_API_HASH')
session_name = 'gift_buyer_session'

client = TelegramClient(session_name, api_id, api_hash)

async def main():
    print("Starting client...")
    await client.start()
    print("Client started.")
    await client.run_until_disconnected()

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())

This basic setup gets you connected. The session_name is important because telethon stores your session, so you don't have to log in every time. It's a nice quality of life feature that makes development quicker.

Listening for Messages: The Core Logic

The real magic happens when you start listening for new messages. You need to identify the channels you want to monitor and then set up an event handler. This is where the 'sniping' comes in. We're looking for specific patterns that indicate a gift link.

Gift links usually contain t.me/gift/ or similar. So, the bot needs to parse incoming messages, check for this pattern, and if found, quickly act.

python
# ... (previous imports and client setup)

TARGET_CHANNELS = [-100123456789, 'my_favourite_channel'] # Use channel IDs or usernames

@client.on(events.NewMessage(chats=TARGET_CHANNELS))
async def handle_new_message(event):
    message_text = event.message.message
    
    if message_text:
        print(f"New message in chat {event.chat_id}: {message_text[:100]}...")

        # Simple regex to find Telegram gift links
        import re
        gift_link_pattern = re.compile(r'https?://t\.me/gift/[a-zA-Z0-9]+')
        match = gift_link_pattern.search(message_text)

        if match:
            gift_link = match.group(0)
            print(f"Found potential gift link: {gift_link}")
            
            try:
                # This is the crucial part: trying to claim the gift
                # For this, you'd typically need to 'visit' the link or use a special API call.
                # Telethon's client.send_message or client.get_messages might not be enough
                # for a direct claim. Often, it involves opening the link in a browser context
                # or using a more specific Telegram Premium API if one exists for bots.
                # For simplicity here, let's just simulate 'acknowledging' it.
                print(f"Attempting to claim gift: {gift_link}")
                
                # In a real scenario, you might programmatically open this URL in a headless browser
                # or send a special request if Telegram exposes a direct claim endpoint.
                # For now, let's just log it and maybe send a notification.
                await client.send_message('me', f"🎁 Gift detected and theoretically claimed: {gift_link}")
                print(f"Notification sent for gift: {gift_link}")

            except Exception as e:
                print(f"Error claiming gift {gift_link}: {e}")
        else:
            print("No gift link found in this message.")
    else:
        print(f"Received an empty message in chat {event.chat_id}.")

# ... (async def main and if __name__ block)

The 'Claiming' Part: Where It Gets Tricky

Now, about that try block for claiming the gift. This is where the rubber meets the road, and honestly, it's the hardest bit. Simply finding the link isn't enough; you need to activate it. Telegram's gift links are often designed to be claimed by a human browser, with some behind-the-scenes checks. A telethon bot can visit URLs, but it doesn't always replicate a full browser environment, which might be necessary for the actual claim to register. This tripped me up at first, as I assumed a simple HTTP GET request would do the trick, but it's usually more complex.

Sometimes, you might need to use a headless browser like Playwright or Selenium to open the link and simulate a click. That adds a whole layer of complexity and dependencies, but for ultimate success, it's often the way. My current gift-buyer version primarily focuses on detecting and notifying me of these gifts, giving me a head start to manually claim if the automated claim fails. It's a compromise between complexity and reliability. You've got to know when to automate fully and when to build a really fast assistant.

Practicalities and Lessons Learned

Building gift-buyer taught me a few things about building real-time automation and dealing with external APIs:

1. Rate Limiting is Real

Telegram, like any good API provider, has rate limits. You can't just spam messages or requests. If you do, you'll get temporarily banned. My initial version was a bit too aggressive in its logging and notification sending. I quickly realised I needed to throttle my bot's outgoing messages, even to myself. It's a common pitfall, and I've seen it bite developers on bigger projects too. Always read the API documentation on rate limits, and build in delays or exponential backoffs.

2. Robust Parsing is Key

Message formats can change. What if Telegram changes the t.me/gift/ pattern? Or wraps it in some other text? Your regex needs to be flexible, or you need multiple patterns. This is where good old unit tests come in handy, even for a personal project. Test with various message structures to make sure your bot doesn't miss anything important, or worse, try to claim something that isn't a gift.

3. Asynchronous Programming is Your Friend

Python's asyncio is essential for bots like this. You're constantly waiting for network events (new messages), and you don't want your bot to block while processing one message and miss another. The telethon library is built on asyncio, so it fits naturally. If you're not comfortable with async/await yet, building a bot like this is a brilliant way to get some hands-on experience. It really helps you understand what's got my attention in web dev right now, especially with the move towards more real-time, event-driven architectures.

4. Hosting Matters

Where you run your bot is important. It needs to be always-on, reliable, and have a good internet connection. For a while, I ran it on a Raspberry Pi at home, but that's not ideal for stability or power outages. Eventually, I moved it to a small virtual private server (VPS). Speaking of hosting, we had quite the journey moving our apps from AWS to Hetzner recently, and while this bot is much smaller scale, the lessons on infrastructure, uptime, and cost-efficiency certainly apply.

Beyond Gift Sniping: The Broader Context of Automation

This gift-buyer bot, while a small, niche project, really highlights the power of automation and how much you can achieve with a bit of code. It's about empowering yourself to do things more efficiently.

It's a far cry from the grand visions of AI agents that everyone's talking about these days, but it touches on some similar foundational principles. You're building something that observes, decides, and acts. Speaking of agents, have you seen Andrej Karpathy's article making the rounds on HackerNews? He makes a brilliant point about how it's going to take a decade to really work through the issues with agents – and he's spot on. Our little gift-buyer is a far cry from a general-purpose AI, but it teaches you fundamental principles of automation and dealing with external APIs, which, frankly, are building blocks for any agent, big or small.

We're talking about simple pattern matching and reacting here, not deep learning or complex decision trees. But the journey from a simple script to something that can reliably interact with an external system, handle errors, and stay online is a significant one. It's the kind of practical, hands-on experience that you don't always get from just reading theory. It makes you think about robustness and error handling in a very concrete way.

Open Source and Developer Productivity

Projects like gift-buyer, even if initially personal, often benefit from an open-source approach. Sharing the code allows others to learn, contribute, and improve upon it. It ties into the wider developer productivity trend – how can we build tools that make our lives easier, whether it's for personal use or for a team?

I'm a big believer in building small, focused tools. They might not be the next big thing, but they solve real problems and teach you an incredible amount. The principles you learn here – interacting with APIs, handling real-time data, managing concurrency – are transferrable to much larger, more complex systems. For something ultra-high performance, you might even consider something like Rust for the core logic, if you're really optimising, which actually reminds me of what's got me thinking about Rust in the kernel recently.

Ethical Considerations (A Quick Aside)

It's worth a quick mention that when you build bots, especially ones that interact with services like Telegram in an automated way, you should always be mindful of their Terms of Service. While gift-buyer isn't doing anything malicious or spammy, constantly hitting an API or trying to exploit loopholes can lead to account bans. Always use these tools responsibly and respect the platforms you're automating against. My gift-buyer is very lightweight, sticking to reading public channel messages and only attempting a 'claim' when a very specific pattern is found, which keeps it well within reasonable usage.

What's Next for gift-buyer?

Honestly, for now, gift-buyer is doing exactly what I need it to do. My next step might be to refactor the claiming mechanism to use a headless browser for more reliable claims, but that's a project for another weekend. It's a fun little project that serves its purpose and keeps my coding muscles active.

So, if you've got a small, irritating task that you find yourself doing repeatedly, take a moment. Could a bot do it for you? You'd be surprised how much you can learn, and how much time you can save, by automating even the simplest things. It's a great way to put your web development skills to practical use, and it's always a good feeling to see your code make your life just a little bit easier. Happy coding!

TOPICS

Web Development

Share This Article

Related Articles

Archives

October 202546
T

The Dev Insights Team

Author