N comment a word, get a dm: the 267 line python script behind my reels - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/instagram-comment-to-dm-bot/
☷ comment a word, get a dm: the 267 line python script behind my reels - nicnonac guides _□×

← back to guides

comment a word, get a dm: the 267 line python script behind my reels

Builds · 9 min read · posted Nov 29, 2026, 8:33 am

You've seen the reels. Comment a word, get the link in your DMs. It looks like a big system. The feature itself is three API calls.

On my account one short Python script does it, on an old laptop with Linux on it. The laptop's screen doesn't even turn on anymore. It answers every keyword on my reels.

This is the setup from the reel: the script, how to get a token out of Meta, how to keep it running, and the things it can't do, so you can decide if it's enough for you.

what it does

  • Every 60 seconds it asks Instagram for your newest 100 posts and how many comments each one has.
  • If a post's count hasn't moved since the last check, it skips that post. If it has, it pulls the new comments.
  • It lowercases each comment and strips everything that isn't a letter or a digit, so CHAT!! 🙏 becomes chat. If what's left is one of your keywords, it's a match.
  • Matches go into a queue saved on disk and are sent oldest first, one a minute, under a daily cap. A reel that takes off just makes the queue longer, and nothing is lost if the machine restarts.
  • Each match gets the DM, and a short public reply under the comment if you want one ("Sent it over!").
  • One DM per person per keyword. Someone who comments the same word on three of your reels gets it once.
  • If Instagram starts refusing sends, it stops, keeps the queue and tries again six hours later.

It uses Meta's official Instagram API, not a browser bot, so your password isn't stored anywhere.

what it can't do

Read this part first.

  • No follow gate. It can't check that someone follows you before sending.
  • No buttons, flows or email capture. It sends one text message.
  • No follow-up later. Meta allows one private reply per comment. After that you can only message that person if they write back, and only within 24 hours of their message.
  • Not instant. It checks once a minute, so the DM lands a minute or two after the comment. On a busy day the daily cap makes people wait longer, sometimes until the next day.
  • 7 days. A private reply has to go out within 7 days of the comment. The script drops anything older.
  • Your own account only. Running it for other people's accounts means putting your app through Meta's App Review.

If you need any of those, this script isn't the tool for it. I only ever needed the one feature.

what you need

  • An Instagram professional account, creator or business. You don't need a Facebook Page linked to it.
  • A Meta developer account.
  • Anything that stays on and has Python 3: an old laptop, a Raspberry Pi, a small VPS. Nothing has to be reachable from the internet, because the script only makes outgoing calls. That's why a laptop on home wifi works.
  • No Python packages. It's the standard library only.

step 1: make the meta app and get a token

This is the slow part, about 20 minutes. Meta's dashboard changes often, so follow their own page for the exact clicks. The short version:

  1. At developers.facebook.com, create an app. Pick the Other use case, then Business.
  2. Add the Instagram product. You want API setup with Instagram login, not the Facebook login one.
  3. In that section, add your Instagram account and generate an access token for it. Approve the permissions for your profile, comments and messages: instagram_business_basic, instagram_business_manage_comments, instagram_business_manage_messages.
  4. Copy the token. Treat it like a password. Anyone who has it can read your comments and send DMs as you.

Two things cost me hours here:

  • Switch the app to Live mode. In Development mode the API gave me the right comment counts and zero comments, with no error. Live mode fixed it. I didn't need App Review, because the only account it touches is mine.
  • Live mode wants a privacy policy URL. A page on your own site that says what the app does with data is enough to fill the field.

The token lasts 60 days. The script refreshes it once a week by itself, so you only do this step once.

step 2: put the script on the machine

Three files in one folder:

ig-dm-bot/
  bot.py          the script
  keywords.json   your keywords and what each one sends
  token           the access token on one line, nothing else
mkdir ~/ig-dm-bot && cd ~/ig-dm-bot
curl -O https://nicnonac.com/assets/guides/ig-dm-bot/bot.py
nano keywords.json     # paste the example below, then edit it
nano token             # paste your token, save
chmod 600 token        # only you can read it

You can read the whole script before you run it: bot.py. It was 267 lines in the reel and is 314 now, after I added the daily cap, the one DM per person rule and the pause. It only talks to graph.instagram.com.

keywords.json looks like this:

{
 "CHAT": {
  "posts": [
   "https://www.instagram.com/reel/YOUR_REEL_CODE/"
  ],
  "dm": "hey, saw you commented \"CHAT\" on my reel. here ya go 👇\nhttps://example.com/your-link",
  "replies": [
   "Sent it over!",
   "Sent now, check DMs...",
   "Cheers, sent!"
  ]
 }
}
  • The key is the keyword. Capitals and punctuation don't matter.
  • posts is the list of reels the keyword works on. Leave posts out and it works on all of your newest 100 posts. An empty list, [], means the keyword is loaded but switched off, which is how I stage one before the reel is up.
  • dm is the message. \n is a new line.
  • replies are the public replies. One is picked at random each time, so they aren't all identical. Leave it out for no public reply.

step 3: check it before you trust it

python3 bot.py --check

This only reads. It sends nothing. You should see something like:

token ok: @yourname (id 17841400000000000)
keyword 'chat': only on YOUR_REEL_CODE
media visible: 100
newest: https://www.instagram.com/reel/YOUR_REEL_CODE/ (12 comments)
  @someone: 'CHAT' -> MATCH
  @someone_else: 'love this' -> no match

If the newest post says it has comments and none are listed under it, the app is still in Development mode.

step 4: keep it running

To try it, python3 bot.py in a terminal is enough. It runs until you close the window.

To keep it running on Linux, make it a service. Save this as /etc/systemd/system/ig-dm-bot.service, with your username in place of you:

[Unit]
Description=ig-dm-bot: Instagram comment keyword -> DM
After=network-online.target
Wants=network-online.target

[Service]
User=you
WorkingDirectory=/home/you/ig-dm-bot
ExecStart=/usr/bin/python3 /home/you/ig-dm-bot/bot.py
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target
sudo systemctl enable --now ig-dm-bot
sudo journalctl -u ig-dm-bot -f      # watch it work

The log is two kinds of line:

queued 18126939949931884 'chat' from @someone
sent DM for 18126939949931884 'chat'

It only answers comments made after the first time you start it. It won't message everyone who ever commented on an old post.

On a laptop, tell it not to sleep when the lid closes: set HandleLidSwitch=ignore in /etc/systemd/logind.conf, then reboot.

a new reel is one edit

Add a block to keywords.json for the new keyword. The script re-reads that file on every check, so there's nothing to restart.

I add the keyword with "posts": [] before I post, then paste the reel link in once it's up. Comments that came in between still get their DM on the next check, as long as they're inside the 7 days.

how it works

The four parts from the reel, with the lines that do them.

1. One request, every 60 seconds.

POLL_SECONDS = 60
MEDIA_WINDOW = 100         # newest N posts/reels watched, in one request. Trials count as posts.

One call returns the newest 100 posts with a comment count on each.

2. Skip what hasn't changed. The script remembers the count it saw last time for every post.

if seen and seen["count"] == count:
    watched[m["id"]] = seen
    continue

A quiet minute costs one API call instead of a hundred and one.

3. Match.

def normalize(text):
    """'DESIGN!! 🙏' -> 'design'. A comment matches only if the whole thing is the keyword."""
    return re.sub(r"[^a-z0-9]", "", text.lower())

The whole comment has to be the keyword. Chat!! matches. can i get the chat link doesn't. That's on purpose: fewer DMs sent to people who didn't ask.

4. Queue, then send.

call("POST", f"/{me['user_id']}/messages",
     body={"recipient": {"comment_id": cid}, "message": {"text": cfg["dm"]}})

That call is Meta's private reply: a DM addressed to a comment, not to a user. It's the only way to message someone who hasn't messaged you first. Meta's documented cap is 750 an hour per account for post and reel comments. Staying under that number is not enough on its own: Instagram can still restrict messaging on an account that suddenly sends a lot. So the script goes slower than it has to.

MAX_SENDS_PER_SWEEP = 1    # one DM a minute. Meta's documented limit is 750/hour, but see the daily cap
DAILY_CAP_START = 150      # DMs per rolling 24 hours after a first start or a block...
DAILY_CAP_STEP = 50        # ...raised by this much for every day without a block...
DAILY_CAP_MAX = 400        # ...up to this. A sudden jump in volume is what gets an account restricted.
BLOCK_STREAK = 5           # this many sends in a row refused on comments that still exist = a block
BLOCK_PAUSE = 6 * 3600     # then stop sending for this long, keep the queue, and try again

One DM per check, and a daily cap that starts at 150, goes up by 50 for every day without trouble and stops at 400. The rest wait in the queue. If five sends in a row are refused on comments that still exist, it stops sending for six hours and keeps everything queued. If Meta tells it to slow down, it stops and picks the queue up again on a later check. A send that fails for a temporary reason gets up to 5 attempts.

Those numbers are my guesses, not Meta's. Change them at the top of the script.

if something's off

  • Comment counts but no comments: the app is in Development mode. Switch it to Live.
  • --check fails on the token: it expired or was pasted with a space or a line break. Generate a new one in the dashboard and paste it into token again.
  • queued with no sent DM after it: it's waiting its turn (one a minute, under the cap), or Meta refused the send, and then the next line in the log says why.
  • daily cap reached in the log: normal on a busy day. The rest go out as the 24 hours roll over.
  • sends paused until in the log: five sends in a row were refused, which usually means Instagram has restricted messaging on the account. Check Account Status in the app. The queue is kept and the script tries again by itself.
  • A keyword does nothing: run --check and look at its line. If it says only on and your reel isn't in that list, the link in posts is wrong.

← all guides

Done nicnonac.com 56.6k