Review Response Agent: Python Script for Google Reviews
Part of the guide: Local SEO & Google Business Profile
Minimum age of the verified profile
Google prerequisites page
Reviews per page, maximum
Reviews list reference, v4
Bytes in a reply, maximum
ReviewReply reference, v4
Queries per minute once approved
Google prerequisites page
See Sources at the end of the article. Cards marked Assumption are examples, not results.
Google only grants Business Profile API access to a verified profile that has been active for 60 or more days and lists a website
After that you submit an Application for Basic API Access. A quota of 0 queries per minute means you are not approved yet; 300 means you are.
Google Business Profile APIs, Prerequisites, checked 3 November 2026
DRY_RUN=1 (the default) and test on your own reviews before you let it post anything. Treat it as a starting point, not a finished product.What access does Google require first?
- A Google Cloud project.
- A verified Business Profile, yours or a client's, that has been active for 60 or more days, with a website listed on it.
- A submitted "Application for Basic API Access" through Google's contact form, with your project number, from an email address that owns or manages the profile.
- After approval, the Business Profile APIs enabled for the project.
mybusiness.googleapis.com. Google's REST reference for listing reviews and replying shows no deprecation notice for these methods at the time of writing, but the docs link to a general deprecation schedule, so check it before you build anything long-lived.How does the script work?
Refresh OAuth access token
|
GET reviews (50 per page, newest first)
|
Skip any review that already has a reviewReply
|
Stop words (refund, lawyer, injured ...) -> flag for the owner, no draft
|
Draft a reply with the LLM (model may answer HOLD -> flag for the owner)
|
1-3 stars, or DRY_RUN on -> print the draft, post nothing
|
4-5 stars and DRY_RUN off -> PUT the reply, log the review
- Dry run is the default. Nothing posts until you set
DRY_RUN=0. - Only 4 to 5 star reviews can ever be auto-posted. Everything lower is draft-only.
- The model can say HOLD. The prompt tells it to output HOLD for health, money, legal or safety content, and the script treats that as "owner decides".
- No generic fallback reply. If the model fails, the script skips the review rather than posting boilerplate.
- A log file prevents double replies.
How do you find your account and location IDs?
readMask. Replace ACCESS_TOKEN with a token from the OAuth flow (scope https://www.googleapis.com/auth/business.manage):# 1. List accounts (the "name" looks like accounts/123...)
curl -H "Authorization: Bearer ACCESS_TOKEN" \
"https://mybusinessaccountmanagement.googleapis.com/v1/accounts"
# 2. List that account's locations (the "name" looks like locations/456...)
curl -H "Authorization: Bearer ACCESS_TOKEN" \
"https://mybusinessbusinessinformation.googleapis.com/v1/accounts/ACCOUNT_ID/locations?readMask=name,title"
accounts/ACCOUNT_ID/locations/LOCATION_ID. That is the value for LOCATION_NAME below. The review resource's own name field comes back as that path followed by /reviews/REVIEW_ID, which is what the reply call needs.What does the Python script look like?
llama-3.3-70b-versatile is the example model; check Groq's models page for the current list. Any OpenAI-style chat provider works with small changes.#!/usr/bin/env python3
"""Draft (and optionally post) replies to Google reviews.
UNTESTED STARTING POINT. Run with DRY_RUN=1 first and read every draft."""
import json
import os
import re
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
GROQ_API_KEY = os.environ["GROQ_API_KEY"]
GROQ_MODEL = os.environ.get("GROQ_MODEL", "llama-3.3-70b-versatile")
CLIENT_ID = os.environ["GOOGLE_CLIENT_ID"]
CLIENT_SECRET = os.environ["GOOGLE_CLIENT_SECRET"]
REFRESH_TOKEN = os.environ["GOOGLE_REFRESH_TOKEN"]
LOCATION_NAME = os.environ["LOCATION_NAME"] # accounts/ACCOUNT_ID/locations/LOCATION_ID
BUSINESS_NAME = os.environ.get("BUSINESS_NAME", "our business")
OWNER_NAME = os.environ.get("OWNER_NAME", "The team")
DRY_RUN = os.environ.get("DRY_RUN", "1") != "0" # anything but "0" means dry run
LOG_FILE = Path("replied_reviews.json")
MAX_PAGES = 3 # 3 pages x 50 reviews; raise if you have a backlog
STARS = {"ONE": 1, "TWO": 2, "THREE": 3, "FOUR": 4, "FIVE": 5}
STOP_WORDS = re.compile(
r"refund|lawyer|attorney|sue|injur|sick|poison|police|discriminat|allerg",
re.IGNORECASE,
)
def call(url, method="GET", headers=None, body=None, timeout=20):
data = body if isinstance(body, bytes) else (json.dumps(body).encode() if body else None)
req = urllib.request.Request(url, data=data, method=method, headers=headers or {})
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
return json.loads(raw) if raw else {}
def get_access_token():
body = urllib.parse.urlencode({
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"refresh_token": REFRESH_TOKEN,
"grant_type": "refresh_token",
}).encode()
resp = call("https://oauth2.googleapis.com/token", "POST",
{"Content-Type": "application/x-www-form-urlencoded"}, body)
return resp["access_token"]
def fetch_unanswered(token):
reviews, page_token = [], None
for _ in range(MAX_PAGES):
params = {"pageSize": 50}
if page_token:
params["pageToken"] = page_token
url = f"https://mybusiness.googleapis.com/v4/{LOCATION_NAME}/reviews?" + urllib.parse.urlencode(params)
data = call(url, headers={"Authorization": f"Bearer {token}"})
reviews += data.get("reviews", [])
page_token = data.get("nextPageToken")
if not page_token:
break
return [r for r in reviews if "reviewReply" not in r]
def draft_reply(review):
reviewer = review.get("reviewer", {})
first_name = ""
if not reviewer.get("isAnonymous") and reviewer.get("displayName"):
first_name = reviewer["displayName"].split()[0]
stars = STARS.get(review.get("starRating"), 0)
prompt = (
f"You write Google review replies for {BUSINESS_NAME}. Tone: warm, brief, human.\n"
f"Rules: use the reviewer's first name if given, mention one specific detail from the review, "
f"under 90 words, no discounts, no admitting legal fault, no private details, "
f"sign off as {OWNER_NAME}. For 1-3 stars, thank them, apologise that the visit fell short "
f"and invite them to contact us directly. If the review mentions health, safety, money or "
f"legal action, output exactly HOLD. Output only the reply text.\n\n"
f"First name: {first_name or '(not given)'}\nStars: {stars}\n"
f"Review: {review.get('comment') or '(no text)'}"
)
payload = {
"model": GROQ_MODEL,
"messages": [{"role": "user", "content": prompt}],
"max_completion_tokens": 250,
"temperature": 0.6,
}
try:
resp = call("https://api.groq.com/openai/v1/chat/completions", "POST",
{"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
payload)
text = resp["choices"][0]["message"]["content"].strip()
except Exception as exc: # no generic fallback: skip instead
print(f" model call failed, skipping: {exc}")
return None
if text.upper().startswith("HOLD") or len(text.encode()) > 4096:
return None
return text
def post_reply(token, review_name, text):
url = f"https://mybusiness.googleapis.com/v4/{review_name}/reply"
call(url, "PUT", {"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
{"comment": text})
def main():
log = json.loads(LOG_FILE.read_text()) if LOG_FILE.exists() else {}
token = get_access_token()
reviews = fetch_unanswered(token)
print(f"{len(reviews)} unanswered review(s). DRY_RUN={DRY_RUN}")
for review in reviews:
name = review["name"]
if name in log:
continue
stars = STARS.get(review.get("starRating"), 0)
comment = review.get("comment", "")
print(f"\n{stars} stars: {comment[:120]!r}")
if STOP_WORDS.search(comment):
print(" FLAGGED: stop word found. Owner replies personally.")
continue
text = draft_reply(review)
if text is None:
print(" No draft (HOLD or error). Owner decides.")
continue
print(f" DRAFT: {text}")
if DRY_RUN or stars < 4:
print(" Draft only. Review and post manually.")
continue
try:
post_reply(token, name, text)
except Exception as exc:
print(f" post failed: {exc}")
continue
log[name] = {"at": datetime.now(timezone.utc).isoformat(), "stars": stars}
print(" posted")
LOG_FILE.write_text(json.dumps(log, indent=2))
if __name__ == "__main__":
main()
- Moderation. Google's reply help page says each reply is checked against content policies before it posts, usually in about 10 minutes but sometimes up to 30 days, and that a rejected reply must be edited. The review resource includes a
reviewReplyStatefield, and apolicyViolationfield that is filled only when a reply is rejected. - Error handling. It stops on the first Google error when fetching and does not retry. Add exponential backoff for 429 responses, as Google recommends.
- Scheduling. Run it once a day from cron or a scheduled GitHub Action, not in a tight loop.
- Stop words. The list above is a starting point. Add words that matter in your trade.
What do the drafted replies look like?
What does it cost in time? Worked example
| Quiet | Typical | Busy | |
|---|---|---|---|
| Reviews per month (assumption) | 30 | 60 | 120 |
| Minutes saved per reply: 4 by hand vs 1 to review a draft (assumption) | 3 | 3 | 3 |
| Hours saved per month | 1.5 | 3.0 | 6.0 |
| Value of your time at $30 per hour (assumption) | $45 | $90 | $180 |
| Upkeep: 1 hour per month (assumption) | $30 | $30 | $30 |
| Net monthly gain | $15 | $60 | $150 |
| One-off build and approval time: 6 hours (assumption) | $180 | $180 | $180 |
| Months to pay back | 12 | 3 | 1.2 |
Worked example from the table above. Every input is an assumption: 3 minutes saved per reply, $30 per hour, 1 hour upkeep a month, 6 hours to build.
What should you do today?
- Check whether your Business Profile is verified, has a website listed and is at least 60 days old.
- Create a Google Cloud project, submit the "Application for Basic API Access", and note the project number you used.
- Count your unanswered reviews from the last 90 days. That is your volume and your backlog.
- Write a voice guide: three replies you are proud of and three phrases you never use. Paste them into the prompt.
- When access arrives, run the script with
DRY_RUN=1for a week and compare each draft with what you would have written. Only then considerDRY_RUN=0, and keep 1 to 3 star reviews manual.
FAQ
Is it allowed to post AI-written replies to Google reviews?
How do I find my location ID?
accounts/ACCOUNT_ID/locations/LOCATION_ID.Can I use a different model provider?
draft_reply(). Keep the HOLD rule and the length check.Can I delay replies so I can handle some personally?
createTime in RFC 3339 format. Parse it, compare it with the current time, and skip reviews newer than your chosen delay.Should I also automate asking for reviews?
Sources
- Google Business Profile APIs: Prerequisites
- Google Business Profile APIs: Basic setup
- Google Business Profile APIs: Review data
- Google Business Profile APIs: Usage limits
- REST reference: reviews.list (v4)
- REST reference: reviews resource (v4)
- REST reference: reviews.updateReply (v4)
- REST reference: Business Information locations.list
- Google Identity: OAuth 2.0 for installed apps, refreshing tokens
- Google Business Profile Help: Reply to reviews
- Groq: API reference
- Groq: Models
Related guides
Free for local businesses
Want this applied to your business?
I'll review your Google presence, local SEO, and ad accounts — and send you a specific action plan within 48 hours. No pitch, no pressure.
Want hands-on help?
See how DataLatte handles AI Agents & Automation for local businesses.

Local marketing strategist with 10+ years at global agencies — OMD, Dentsu, GroupM, and BBDO. Now helping small businesses get the same data-driven edge. Based in Europe, working with clients in the US, UK, Australia, and beyond.
Related articles
Want this applied to your business?
Let's review your current marketing setup together — free, no obligations.
Get Your Free Marketing Audit