DEV Community

Scaplejett
Scaplejett

Posted on

Building a Telegram Bot That Monitors Instagram Posts with Concurrent Python Requests

What if I could monitor multiple Instagram accounts without waiting for each request to finish one by one?

That was the problem I was trying to solve. I wanted a Telegram bot that checks selected Instagram accounts and sends me a notification whenever something new is posted.

The straightforward approach works, but when you're checking multiple accounts, making every request sequentially starts wasting time waiting for network responses. Since this is mostly an I/O-bound task, concurrency makes more sense.

Starting with a basic API request

I started with a simple request using Python's requests library:

import requests

headers = {"x-access-key": "YOUR_KEY"}

resp = requests.get(
"https://api.hikerapi.com/v2/hashtag/medias/top?name=travel",
headers=headers
)

print(resp.json())

This is fine for a single request. The problem is that if I repeat this for multiple accounts, each request waits for the previous one to finish.

Why concurrency helps

Network requests spend much of their time waiting for a response. Rather than waiting for each request sequentially, I can run multiple requests concurrently.

For this workflow, I used HikerAPI, a REST Instagram API. It offers pricing starting at $0.001/request and 100 free requests to get started.

The goal isn't to fire unlimited requests. It's to reduce unnecessary waiting while keeping requests controlled.

Using asyncio with aiohttp

For a larger monitoring list, async requests are a useful approach. aiohttp allows multiple HTTP requests to be in progress without blocking the entire program.

import asyncio
import aiohttp

API_URL = "https://api.hikerapi.com/v2/hashtag/medias/top"
HEADERS = {"x-access-key": "YOUR_KEY"}

async def fetch(session, hashtag):
params = {"name": hashtag}

async with session.get(API_URL, params=params, headers=HEADERS) as response:
    response.raise_for_status()
    return await response.json()
Enter fullscreen mode Exit fullscreen mode

async def main():
hashtags = ["travel", "technology", "photography"]

async with aiohttp.ClientSession() as session:
    results = await asyncio.gather(
        *(fetch(session, tag) for tag in hashtags),
        return_exceptions=True
    )

for tag, result in zip(hashtags, results):
    if isinstance(result, Exception):
        print(f"{tag}: request failed - {result}")
    else:
        print(f"{tag}: fetched successfully")
Enter fullscreen mode Exit fullscreen mode

asyncio.run(main())

This demonstrates the concurrency pattern: multiple requests are started together, and the program collects their results as they finish.

For an account-monitoring bot, the same pattern can be applied to the relevant account-data endpoints instead of hashtag endpoints.

Keeping concurrency under control

Running concurrent requests doesn't mean running unlimited requests. I would use a semaphore to control the number of simultaneous connections:

semaphore = asyncio.Semaphore(5)

async def controlled_fetch(session, hashtag):
async with semaphore:
return await fetch(session, hashtag)

This gives the application a limit on simultaneous requests. It's useful for avoiding unnecessary bursts and making request behavior more predictable.

Handling rate limits and failures

A monitoring bot needs to handle API failures properly. A request shouldn't crash the entire monitoring cycle just because one endpoint temporarily fails.

Things I would account for:

429 Too Many Requests: Respect rate limits and any Retry-After header provided.

5xx errors: Retry temporary server failures with exponential backoff.

Timeouts: Set a reasonable request timeout rather than allowing requests to hang indefinitely.

Partial failures: Let other accounts finish checking if one request fails.

Duplicate notifications: Track the last processed post ID so the bot doesn't notify me about the same post repeatedly.

Retries should be limited. Repeatedly retrying a rate-limited request just creates more traffic and usually makes the problem worse.

Connecting it to Telegram

Once the API returns the data, the remaining part is relatively simple:

Compare the latest post against the last post stored for that account.

If it's new, save the updated post ID.

Send a Telegram message with the account and post information.

Continue the next monitoring cycle.

The important part is storing the last processed post somewhere persistent. Otherwise, restarting the bot could cause old posts to trigger notifications again.

Async or threads?

For this particular workflow, I'd generally start with asyncio because monitoring Instagram is primarily network-bound.

Threads using ThreadPoolExecutor are also perfectly reasonable if the existing code already uses requests and I don't want to rewrite everything around an async HTTP client.

The choice depends more on the existing application and how many requests need to be managed than on async being inherently better.

Conclusion

The useful part of concurrency here isn't making requests as fast as possible. It's being able to monitor multiple accounts without turning the entire process into a long sequence of network waits.

For a Telegram notification bot, controlled concurrency, persistent post tracking, and sensible rate-limit handling matter more than simply increasing the number of simultaneous requests.

I'd rather have a monitoring script that runs reliably over time than one that finishes a batch quickly and starts failing on the next cycle.

Top comments (0)