Gmail OTP API for Bots: Telegram, Discord and Scripts
A bot that hands out verification codes looks simple: someone types a command, the bot replies with an email address, and a minute later it posts the code. Behind that sit a queue, a poller, rate limits and refunds. This guide is about that design. The Python example shows the single-script version; here the same API serves many chat users at once.
Short answer: four calls do the work. POST /v1/orders rents an inbox and returns its address. POST /v1/orders/status (or GET /v1/orders/{id}) reads the code. POST /v1/orders/{id}/cancel gives up early with a 100% refund. Webhooks, set with PUT /v1/webhook, can push the code instead of you polling for it. Keep the chat handler fast, put orders in a queue, and let one loop poll every open order.
Bot architecture: handler, queue, poller
Split the bot into three parts that do not block each other:
- Command handler. It parses
/code instagramor a slash command, checks the service code against a cached copy ofGET /v1/services(refresh it every few minutes), creates the order, and answers with the address. It never waits for the code. - Job store. One record per order:
orderId, the chat or user ID, the service,codeDeadlineAtand a status. Keep it in SQLite or Redis rather than memory, so a restart loses nothing. - Poller. One loop for the whole bot reads every open order in bulk, sends codes to the right chat and closes finished jobs.
A thread or task per order looks easier and breaks first: twenty users mean twenty loops hitting the same rate limit. One poller with a shared limiter scales much further.
Give each user their own order. Two people sharing one inbox would see each other's codes, and a refund could not be split between them.
The core loop in Python
import os, time, uuid, threading, requests
HOST = "otpgmail.net"
API = f"https://{HOST}/v1"
H = {"Authorization": f"Bearer {os.environ['OTPGMAIL_API_KEY']}", "X-Lang": "en"}
jobs, lock = {}, threading.Lock() # orderId -> chat id; use a real store in production
def rent_for(chat_id, service, domain="gmail.com"):
r = requests.post(f"{API}/orders", timeout=60,
headers={**H, "Idempotency-Key": str(uuid.uuid4())},
json={"service": service, "domain": domain, "warehouse": 99})
body = r.json()
if not body["success"]:
return None, body["error"]["code"]
order = body["data"][0]
with lock:
jobs[order["orderId"]] = chat_id
return order["email"], None
def poller(send):
while True:
with lock:
ids = list(jobs)[:100]
if ids:
r = requests.post(f"{API}/orders/status", json={"ids": ids}, headers=H, timeout=30)
for o in r.json().get("data", []):
if o["status"] == "completed":
send(jobs[o["orderId"]], f"Code: {o['otp'][-1]['code']}")
elif o["status"] == "cancelled":
send(jobs[o["orderId"]], "No code arrived in time, so the order was refunded.")
else:
continue
with lock:
jobs.pop(o["orderId"], None)
time.sleep(4)
send is your bot library's "send message" function. X-Lang: en makes error messages English. Use requests: the default user agent of the standard-library urllib is rejected by the CDN. Retry rules for a timed-out POST /v1/orders (resend with the same Idempotency-Key, never a new one) are covered in the retries and timeouts guide.
Concurrency and limits
- Rate limits apply per API key: by default 20 requests per second and 900 per minute, and your account may have its own values, shown on the API docs page. Every worker that uses the key shares them.
- Bulk status reads up to 100 orders in one request. Each call checks at most 20 open orders against the inbox (orders still waiting for a first code go first) and returns the rest from stored data, so a large queue simply takes a few rounds.
- Polling interval: every 3 to 5 seconds while orders wait for a code. Faster polling returns the same data and spends your limit.
- Quantity: one
POST /v1/orderscan rent up to 200 inboxes withquantity, and the response may hold fewer than asked; countdata[]before you assign addresses to users. - Waiting orders are capped per account. A burst of commands can hit
WAITING_LIMIT_REACHED; queue the extra requests in the bot instead of failing them.
Timeouts and cancellation, so no balance is wasted
Every order carries codeDeadlineAt, at most 25 minutes after renting. If no code arrives by then, it cancels itself and refunds 100%, and your poller sees cancelled. You are charged only when an inbox is issued.
Give users a Cancel button anyway. When someone gives up after a couple of minutes, POST /v1/orders/{id}/cancel returns the money at once instead of holding a waiting slot. Cancelling works only before the first code; once a code is delivered, the order cannot be cancelled or refunded.
Do not build a loop that rents, cancels after twenty seconds and rents again. Some warehouses pause renting for an account that cancels many orders without a code, which shows up as RATE_LIMITED. A patient wait per order costs less.
After the first code, more codes can arrive on the same inbox when the service sends them, at no extra charge within the order period. If your users need a second code, such as a login after sign-up, keep the job open and call POST /v1/orders/{id}/next-code.
Returning the code to the user in chat
- Telegram: send the code as monospace (
<code>123456</code>with HTML formatting). In Telegram apps a monospace block copies with one tap. Edit the bot's earlier "waiting for the code" message rather than posting several new ones. - Discord: answer the slash command with a deferred, ephemeral reply, so only the requester sees the address and the code. Discord expects a first response within 3 seconds and an interaction token lasts 15 minutes, while a code can take longer than that. Defer right away, and if the token has expired when the code arrives, send it by direct message.
- Scripts and CLIs: print the code and exit with a clear status, so a calling program can tell "code received" from "refunded".
Show the address with the service name and the deadline, for example: "Use this address on GitHub. Waiting for the code until 14:32." Take that time from codeDeadlineAt instead of hard-coding a number of minutes.
Handling failures
| What happens | What the bot should do |
|---|---|
NO_MAILS_AVAILABLE, OUT_OF_STOCK, ALL_WAREHOUSES_EXHAUSTED |
Nothing was charged. Wait error.retryAfterSec, try the other domain, or tell the user to try later |
DOMAIN_UNAVAILABLE |
Rent again with gmail.com |
RATE_LIMITED |
Sleep for the Retry-After seconds, then retry |
INSUFFICIENT_BALANCE |
Stop renting and alert the bot owner; it is not the user's fault |
| No code before the deadline | The order is refunded; offer a new attempt |
Every error has error.retryable and error.retryAfterSec, so the bot can decide without a table of its own: true means wait and repeat, false means fix the cause first.
Security: key storage and logs
- Keep the API key in an environment variable or a secret store, never in the code or the repository.
- Never log the full key. Log the last four characters at most.
- If a key leaks, press Generate new key on the docs page; the old key stops working immediately.
- Limit who can use the bot. An open bot spends your balance for anyone who finds it.
- Codes are short-lived, but keep them out of shared logs and public channels.
- With webhooks, verify the
X-OTPGmail-Signatureheader against your secret on every delivery, and keep a slow poll as a fallback, since delivery is best effort.
Follow the terms of every platform your users sign up on, and OTPGmail's acceptable use policy for automation.
Frequently asked questions
What are the API rate limits for a bot?
By default 20 requests per second and 900 per minute per API key, shared by every process using that key. Your account may have different values; the docs page shows the ones that apply. Going over returns HTTP 429 with a Retry-After header.
Does the API support webhooks?
Yes. Register one URL with PUT /v1/webhook and you receive a signed POST for order.code and order.cancelled events. Delivery is best effort, so keep a slow fallback poll with POST /v1/orders/status.
Can a bot buy Gmail accounts in bulk through the API?
Yes. Besides renting inboxes, the API can buy short-lived Gmail accounts through the /v1/mail-shop endpoints, with the same API key. The buy Gmail accounts overview explains what each account includes, and the docs page has the calls.
Should every user get their own inbox?
Yes. One order per request keeps codes private and makes refunds clean: if nobody receives a code, only that order is refunded.
Which language can I write the bot in?
Any language that can send HTTPS requests with a header. The Gmail OTP API overview lists the endpoints, and the docs page links ready-made clients.
