What you are building
Your user writes to the bot, picks a service and a country, gets a number and then the SMS code in the same chat. The bot orders that number with its own API key and charges the user your price. The user never sees the key.
| Part | Holds | Talks to |
|---|---|---|
| Telegram | the chat with the user | your bot, through the Bot API |
| Your bot (a server process) | the API key, the price list, each user's balance and orders | Telegram and handler_api.php |
handler_api.php | your platform balance, the numbers, the codes | your bot only |
The bot below uses long polling (getUpdates), so it runs on any machine with outbound HTTPS: no domain, no TLS certificate, no open port. Telegram's docs note that getUpdates does not work while a webhook is set (Bot API, read 2026-11-24).
What the bot sells, and what it refuses
The bot resells access to the platform's numbers. It does not lend out SIM cards, and it is not a tool for creating accounts in bulk. Put these lines in the bot's terms and keep them in code:
- no bulk account creation;
- nothing for getting around bans, blocks or limits of a service;
- no orders for accounts that belong to someone else;
- no banks, payment apps or government services.
The code enforces what code can: it sells only the services listed in BOT_SERVICES (an allowlist, so a service added to the catalog tomorrow is not on sale by accident), and one user holds at most two open orders.
Prices: getPrices plus your markup
getPrices with service and country answers with the cost and the free stock for that pair:
// handler_api reference: https://otpwatch.com/telegram-number-bot
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
{ "16": { "tg": { "cost": 1.38, "count": 280 } } }cost is US dollars per one-off activation. The bot multiplies it by your markup and rounds up to a whole cent; that is the user's price. When it orders, it sends maxPrice equal to the cost it quoted. The platform will not place the order above that ceiling, so a price that moved between the quote and the tap cannot eat your margin: the order is refused with WRONG_MAX_PRICE:<lowest> instead, and the bot asks the user to look at the price again.
For scale: on , Telegram numbers started at $0.1875 (Indonesia) and the United Kingdom pair at $1.3798. On numbers that cheap, rounding to a cent changes your real markup a lot; the panel page has the table. Country ids and service codes list the values users type.
Every reply the bot handles
The user's money moves only on three of these lines. Everywhere else it stays on hold or goes straight back.
| Reply | From | The bot | User's money |
|---|---|---|---|
JSON with activationId | getNumberV2 | saves the order, then sends the number | on hold |
NO_NUMBERS, CHANNEL_LIMIT | getNumberV2 | "no number right now" | hold released |
WRONG_MAX_PRICE:<lowest> | getNumberV2 | asks the user to check the price again | hold released |
NO_BALANCE, BAD_KEY, ERROR_API | getNumberV2 | tells the user to retry, alerts you | hold released |
STATUS_WAIT_CODE | getStatus | polls again in 3 seconds; cancels after your timeout | on hold |
STATUS_OK:<code> | getStatus | sends the code, closes with setStatus 6 | charged |
STATUS_CANCEL, NO_ACTIVATION | getStatus | stops polling | refunded |
ACCESS_CANCEL | setStatus 8 | tells the user; the cost is back on your platform balance | refunded |
EARLY_CANCEL_DENIED | setStatus 8 | too early to cancel: tries again in 30 seconds | on hold |
BAD_STATUS | setStatus 8 | checks getStatus before refunding: the code may have arrived | decided by getStatus |
Two rules behind the table. The activation id is saved before the user sees the number, so a crash after the order cannot lose it. And no path charges a user for an order that ended without a code. The full list of refusals is on the error codes page; cancel and refund covers the platform side of status 8.
One worker, one request budget
Every user of the bot shares one key, and the API docs give that key 600 requests per minute, with status polling once every 2 to 5 seconds per activation. So the bot has one worker that polls all open orders, never a loop per chat.
The arithmetic behind the constants: at one poll every 3 seconds, an open activation costs 20 requests a minute. The code spaces its own calls to at most 540 a minute, and 20 open activations take 400 of those, which leaves 140 for orders, cancels and price checks. Hence MAX_OPEN = 20. If the key goes over its limit anyway, the API answers REQUEST_LIMIT: wait and repeat.
Setup
Create the bot with @BotFather: /newbot gives you its token. Your own Telegram user id goes into BOT_ADMIN_ID; that account can top up users and gets the alerts. Write to the bot once from it, or the alerts cannot reach you.
# handler_api reference: https://otpwatch.com/telegram-number-bot
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/key
SMS_API_KEY=
BOT_TOKEN=
BOT_ADMIN_ID=
# Your markup in whole percent, and the only services on sale
BOT_MARKUP_PCT=
BOT_SERVICES=tg,wa
# Seconds to wait for a code before the bot cancels
BOT_WAIT_SECONDS=600Both versions read the environment only. Load the file into the shell, then start one of them:
# handler_api reference: https://otpwatch.com/telegram-number-bot
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
set -a; . ./.env; set +a
python3 bot.py # Python 3.10+
node bot.mjs # Node.js 18+The code
One file each, the same behaviour: /price tg 16, /buy tg 16, /cancel <order>, /balance, and /topup <user id> <usd> for the admin. Python keeps money in Decimal; Node keeps cents as integers and the cost as the string getPrices returned. Both were run against a local mock of handler_api.php and the Bot API that replies as their docs describe: quote, order, a code with a leading zero, an early cancel, a price change, an unknown service.
# handler_api reference: https://otpwatch.com/telegram-number-bot
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
import json
import os
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from decimal import ROUND_UP, Decimal
SMS_URL = os.getenv("SMS_API_BASE_URL", "https://sim-aggregator.org/stubs/handler_api.php")
SMS_KEY = os.environ["SMS_API_KEY"]
TG_URL = os.getenv("TELEGRAM_API_URL", "https://api.telegram.org") + "/bot" + os.environ["BOT_TOKEN"]
ADMIN_ID = int(os.environ["BOT_ADMIN_ID"])
MARKUP_PCT = Decimal(os.environ["BOT_MARKUP_PCT"])
SERVICES = set(os.environ["BOT_SERVICES"].split(",")) # the only services this bot sells
WAIT_SECONDS = int(os.getenv("BOT_WAIT_SECONDS", "600")) # your timeout before a cancel
POLL_EVERY = 3 # seconds per activation; the API docs ask for 2 to 5
MAX_OPEN = 20 # 20 activations x 20 polls a minute = 400 of the key's 600 requests
MAX_OPEN_PER_USER = 2
CALL_GAP = 60 / 540 # at most 540 API calls a minute, under the 600 limit
OPEN = ("waiting", "cancelling", "checking")
lock = threading.Lock()
rate_lock = threading.Lock()
next_call = 0.0
balances: dict[int, Decimal] = {} # user id -> USD on the bot; keep it in a database in production
orders: dict[str, dict] = {} # activation id -> order
def sms(action: str, **params) -> str:
global next_call
with rate_lock:
time.sleep(max(0.0, next_call - time.monotonic()))
next_call = time.monotonic() + CALL_GAP
query = urllib.parse.urlencode({"action": action, "api_key": SMS_KEY, **params})
with urllib.request.urlopen(f"{SMS_URL}?{query}", timeout=30) as r:
return r.read().decode().strip()
def tg(method: str, **params):
req = urllib.request.Request(
f"{TG_URL}/{method}", data=json.dumps(params).encode(), headers={"Content-Type": "application/json"}
)
try:
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read())["result"]
except urllib.error.HTTPError as e:
raise RuntimeError(f"{method}: {e.read().decode()}") from e
def say(chat_id: int, text: str) -> None:
try:
tg("sendMessage", chat_id=chat_id, text=text)
except Exception as e: # a user who blocked the bot must not stop the worker
print("sendMessage:", e)
def quote(service: str, country: str):
reply = sms("getPrices", service=service, country=country)
if not reply.startswith("{"):
return None # BAD_COUNTRY, BAD_SERVICE ...
cell = json.loads(reply).get(country, {}).get(service)
if not cell or not cell.get("count"):
return None
cost = Decimal(str(cell["cost"]))
price = (cost * (100 + MARKUP_PCT) / 100).quantize(Decimal("0.01"), rounding=ROUND_UP)
return cost, price # cost goes into maxPrice, price is what the user pays
def buy(chat: int, user: int, service: str, country: str) -> None:
q = quote(service, country)
if not q:
return say(chat, "Not available right now.")
cost, price = q
with lock:
mine = sum(1 for o in orders.values() if o["user"] == user and o["state"] in OPEN)
total = sum(1 for o in orders.values() if o["state"] in OPEN)
refusal = None
if mine >= MAX_OPEN_PER_USER or total >= MAX_OPEN:
refusal = "Too many open orders, try again in a few minutes."
elif balances.get(user, Decimal(0)) < price:
refusal = f"The number costs ${price}. Top up first."
else:
balances[user] -= price # a hold: it comes back if no code arrives
if refusal:
return say(chat, refusal)
reply = sms("getNumberV2", service=service, country=country, maxPrice=str(cost))
if not reply.startswith("{"): # refusals are plain text
with lock:
balances[user] += price # no order, so no hold
if reply.startswith("WRONG_MAX_PRICE"):
return say(chat, "The price has just changed. Send /price again to see the new one.")
if reply in ("NO_BALANCE", "BAD_KEY", "ERROR_API"):
say(ADMIN_ID, f"getNumberV2 answered {reply}")
return say(chat, "No number right now, try again later.")
a = json.loads(reply)
act_id = str(a["activationId"])
with lock: # saved before the user sees the number
orders[act_id] = {"user": user, "chat": chat, "price": price, "state": "waiting", "started": time.time(), "polled": 0.0}
say(chat, f"Number: +{a['phoneNumber']}\nOrder {act_id}. The code will come here. /cancel {act_id} to cancel.")
def handle(msg: dict) -> None:
chat, user = msg["chat"]["id"], msg["from"]["id"]
words = msg.get("text", "").split()
if not words:
return
cmd, args = words[0].split("@")[0].lower(), words[1:]
if cmd == "/price" and len(args) == 2 and args[0] in SERVICES:
q = quote(args[0], args[1])
say(chat, f"{args[0]} in {args[1]}: ${q[1]}" if q else "Not available right now.")
elif cmd == "/buy" and len(args) == 2 and args[0] in SERVICES:
buy(chat, user, args[0], args[1])
elif cmd == "/cancel" and len(args) == 1:
with lock:
o = orders.get(args[0])
ok = bool(o and o["user"] == user and o["state"] == "waiting")
if ok:
o["state"] = "cancelling" # the worker sends setStatus 8
say(chat, "Cancelling. The hold comes back once the cancel goes through." if ok else "No such open order.")
elif cmd == "/balance":
with lock:
left = balances.get(user, Decimal(0))
say(chat, f"Balance: ${left}")
elif cmd == "/topup" and user == ADMIN_ID and len(args) == 2:
uid, amount = int(args[0]), Decimal(args[1])
with lock:
balances[uid] = balances.get(uid, Decimal(0)) + amount
say(chat, f"User {uid}: +${amount}")
else:
say(chat, "/price <service> <country>, /buy <service> <country>, /cancel <order>, /balance\n"
f"Services: {', '.join(sorted(SERVICES))}. Country is a numeric id, for example 16.")
def close(act_id: str, state: str, refund: bool) -> None:
with lock:
o = orders[act_id]
o["state"] = state
if refund:
balances[o["user"]] += o["price"]
def step(act_id: str, o: dict, now: float) -> None:
if o["state"] == "waiting" and now - o["started"] > WAIT_SECONDS:
o["state"] = "cancelling"
with lock:
orders[act_id]["state"] = "cancelling"
if o["state"] == "cancelling":
reply = sms("setStatus", id=act_id, status=8)
if reply == "ACCESS_CANCEL":
close(act_id, "refunded", refund=True)
say(o["chat"], f"Order {act_id} cancelled. ${o['price']} is back on your balance.")
elif reply == "BAD_STATUS": # already closed, or a code was delivered: look before refunding
with lock:
orders[act_id]["state"] = "checking"
else: # EARLY_CANCEL_DENIED: too early, repeat later
with lock:
orders[act_id]["polled"] = now + 27
return
status = sms("getStatus", id=act_id)
if status.startswith("STATUS_OK:"):
code = status.split(":", 1)[1] # keep it a string: leading zeros matter
close(act_id, "done", refund=False)
say(o["chat"], f"Code for order {act_id}: {code}")
sms("setStatus", id=act_id, status=6)
elif status in ("STATUS_CANCEL", "NO_ACTIVATION"):
close(act_id, "closed", refund=True) # closed without a code: the user pays nothing
say(o["chat"], f"Order {act_id} closed without a code. ${o['price']} is back on your balance.")
elif o["state"] == "checking":
close(act_id, "review", refund=False)
say(ADMIN_ID, f"Order {act_id} needs a manual check, getStatus: {status}")
def worker() -> None:
while True:
time.sleep(1)
now = time.time()
with lock:
due = [(i, dict(o)) for i, o in orders.items() if o["state"] in OPEN and now - o["polled"] >= POLL_EVERY]
for i, _ in due:
orders[i]["polled"] = now
for act_id, o in due:
try:
step(act_id, o, now)
except Exception as e:
print("worker:", act_id, e)
def main() -> None:
threading.Thread(target=worker, daemon=True).start()
offset = 0
while True:
try:
updates = tg("getUpdates", offset=offset, timeout=30, allowed_updates=["message"])
except Exception as e:
print("getUpdates:", e)
time.sleep(5)
continue
for u in updates:
offset = u["update_id"] + 1
if "from" in u.get("message", {}):
try:
handle(u["message"])
except Exception as e:
print("handle:", e)
if __name__ == "__main__":
main()// handler_api reference: https://otpwatch.com/telegram-number-bot
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/partner
const need = (name) => {
const v = process.env[name];
if (!v) throw new Error(`${name} is not set`);
return v;
};
const SMS_URL = process.env.SMS_API_BASE_URL ?? "https://sim-aggregator.org/stubs/handler_api.php";
const SMS_KEY = need("SMS_API_KEY");
const TG_URL = `${process.env.TELEGRAM_API_URL ?? "https://api.telegram.org"}/bot${need("BOT_TOKEN")}`;
const ADMIN_ID = Number(need("BOT_ADMIN_ID"));
const MARKUP_PCT = Number(need("BOT_MARKUP_PCT")); // whole percent, for example 20
const SERVICES = new Set(need("BOT_SERVICES").split(",")); // the only services this bot sells
const WAIT_MS = Number(process.env.BOT_WAIT_SECONDS ?? 600) * 1000; // your timeout before a cancel
const POLL_EVERY = 3000; // per activation; the API docs ask for 2 to 5 seconds
const MAX_OPEN = 20; // 20 activations x 20 polls a minute = 400 of the key's 600 requests
const MAX_OPEN_PER_USER = 2;
const CALL_GAP = 60000 / 540; // at most 540 API calls a minute, under the 600 limit
const OPEN = new Set(["waiting", "cancelling", "checking"]);
if (!Number.isInteger(MARKUP_PCT)) throw new Error("BOT_MARKUP_PCT must be a whole number");
const balances = new Map(); // user id -> cents on the bot; keep it in a database in production
const orders = new Map(); // activation id -> order
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const usd = (cents) => `$${(cents / 100).toFixed(2)}`;
let nextCall = 0;
async function sms(action, params = {}) {
const wait = nextCall - Date.now();
nextCall = Math.max(Date.now(), nextCall) + CALL_GAP;
if (wait > 0) await sleep(wait);
const res = await fetch(`${SMS_URL}?${new URLSearchParams({ action, api_key: SMS_KEY, ...params })}`);
return (await res.text()).trim();
}
async function tg(method, params) {
const res = await fetch(`${TG_URL}/${method}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(params),
});
const body = await res.json();
if (!body.ok) throw new Error(`${method}: ${body.description}`);
return body.result;
}
// A user who blocked the bot must not stop the worker.
const say = (chat_id, text) => tg("sendMessage", { chat_id, text }).catch((e) => console.error(e.message));
async function quote(service, country) {
const reply = await sms("getPrices", { service, country });
if (!reply.startsWith("{")) return null; // BAD_COUNTRY, BAD_SERVICE ...
const cell = JSON.parse(reply)[country]?.[service];
if (!cell || !cell.count) return null;
const cost = String(cell.cost); // goes into maxPrice as is
const units = Math.round(cell.cost * 10000); // 1/100 of a cent, exact for prices like 0.1875
const price = Math.ceil((units * (100 + MARKUP_PCT)) / 10000); // cents the user pays, rounded up
return { cost, price };
}
const openCount = (user) => [...orders.values()].filter((o) => OPEN.has(o.state) && (user == null || o.user === user)).length;
async function buy(chat, user, service, country) {
const q = await quote(service, country);
if (!q) return say(chat, "Not available right now.");
if (openCount(user) >= MAX_OPEN_PER_USER || openCount() >= MAX_OPEN) return say(chat, "Too many open orders, try again in a few minutes.");
if ((balances.get(user) ?? 0) < q.price) return say(chat, `The number costs ${usd(q.price)}. Top up first.`);
balances.set(user, balances.get(user) - q.price); // a hold: it comes back if no code arrives
const reply = await sms("getNumberV2", { service, country, maxPrice: q.cost });
if (!reply.startsWith("{")) { // refusals are plain text
balances.set(user, balances.get(user) + q.price); // no order, so no hold
if (reply.startsWith("WRONG_MAX_PRICE")) return say(chat, "The price has just changed. Send /price again to see the new one.");
if (["NO_BALANCE", "BAD_KEY", "ERROR_API"].includes(reply)) say(ADMIN_ID, `getNumberV2 answered ${reply}`);
return say(chat, "No number right now, try again later.");
}
const a = JSON.parse(reply);
const id = String(a.activationId);
orders.set(id, { user, chat, price: q.price, state: "waiting", started: Date.now(), polled: 0 }); // saved before the user sees it
return say(chat, `Number: +${a.phoneNumber}\nOrder ${id}. The code will come here. /cancel ${id} to cancel.`);
}
async function handle(msg) {
const chat = msg.chat.id, user = msg.from.id;
const words = (msg.text ?? "").split(/\s+/).filter(Boolean);
if (!words.length) return;
const cmd = words[0].split("@")[0].toLowerCase(), args = words.slice(1);
if (cmd === "/price" && args.length === 2 && SERVICES.has(args[0])) {
const q = await quote(args[0], args[1]);
return say(chat, q ? `${args[0]} in ${args[1]}: ${usd(q.price)}` : "Not available right now.");
}
if (cmd === "/buy" && args.length === 2 && SERVICES.has(args[0])) return buy(chat, user, args[0], args[1]);
if (cmd === "/cancel" && args.length === 1) {
const o = orders.get(args[0]);
const ok = o && o.user === user && o.state === "waiting";
if (ok) o.state = "cancelling"; // the worker sends setStatus 8
return say(chat, ok ? "Cancelling. The hold comes back once the cancel goes through." : "No such open order.");
}
if (cmd === "/balance") return say(chat, `Balance: ${usd(balances.get(user) ?? 0)}`);
if (cmd === "/topup" && user === ADMIN_ID && args.length === 2) {
const uid = Number(args[0]), cents = Math.round(Number(args[1]) * 100);
if (!Number.isInteger(uid) || !Number.isInteger(cents)) return say(chat, "/topup <user id> <usd>");
balances.set(uid, (balances.get(uid) ?? 0) + cents);
return say(chat, `User ${uid}: +${usd(cents)}`);
}
return say(chat, `/price <service> <country>, /buy <service> <country>, /cancel <order>, /balance\nServices: ${[...SERVICES].sort().join(", ")}. Country is a numeric id, for example 16.`);
}
function close(o, state, refund) {
o.state = state;
if (refund) balances.set(o.user, balances.get(o.user) + o.price);
}
async function step(id, o, now) {
if (o.state === "waiting" && now - o.started > WAIT_MS) o.state = "cancelling";
if (o.state === "cancelling") {
const reply = await sms("setStatus", { id, status: 8 });
if (reply === "ACCESS_CANCEL") {
close(o, "refunded", true);
say(o.chat, `Order ${id} cancelled. ${usd(o.price)} is back on your balance.`);
} else if (reply === "BAD_STATUS") o.state = "checking"; // already closed, or a code was delivered: look before refunding
else o.polled = now + 27000; // EARLY_CANCEL_DENIED: too early, repeat later
return;
}
const status = await sms("getStatus", { id });
if (status.startsWith("STATUS_OK:")) {
const code = status.slice("STATUS_OK:".length); // keep it a string: leading zeros matter
close(o, "done", false);
say(o.chat, `Code for order ${id}: ${code}`);
await sms("setStatus", { id, status: 6 });
} else if (status === "STATUS_CANCEL" || status === "NO_ACTIVATION") {
close(o, "closed", true); // closed without a code: the user pays nothing
say(o.chat, `Order ${id} closed without a code. ${usd(o.price)} is back on your balance.`);
} else if (o.state === "checking") {
close(o, "review", false);
say(ADMIN_ID, `Order ${id} needs a manual check, getStatus: ${status}`);
}
}
async function worker() {
for (;;) {
await sleep(1000);
const now = Date.now();
for (const [id, o] of orders) {
if (!OPEN.has(o.state) || now - o.polled < POLL_EVERY) continue;
o.polled = now;
await step(id, o, now).catch((e) => console.error("worker", id, e.message));
}
}
}
worker();
let offset = 0;
for (;;) {
let updates;
try {
updates = await tg("getUpdates", { offset, timeout: 30, allowed_updates: ["message"] });
} catch (e) {
console.error("getUpdates", e.message);
await sleep(5000);
continue;
}
for (const u of updates) {
offset = u.update_id + 1;
if (u.message?.from) await handle(u.message).catch((e) => console.error("handle", e.message));
}
}Before real users
- A database, not a dict. Write each order's state change and the balance change in one transaction. After a restart,
getCurrentActivationsListreturns the key's open orders (numberid,number,status0 waiting or 3 code received): reconcile them with your table before you take new orders. - Your payments.
/topupstands in for whatever way your users pay you. The platform balance is yours to keep funded: watchgetBalance(ACCESS_BALANCE:<amount>) and pause sales beforeNO_BALANCE. Funding with USDT TRC-20 walks through the top-up. - A second code. The bot closes an order with
setStatus6 as soon as the first code arrives. To offer another code on the same number, keep the order open and sendsetStatus3 (ACCESS_RETRY_GET);getStatusthen answersSTATUS_WAIT_RETRY:<previous code>until the nextSTATUS_OK. - The key stays on the server. It never goes into a message, a log line or a client. The handler_api reference has every call the bot makes, with all their replies.
Selling to other people: the software program
If the bot sells to people other than you, the platform has a program for exactly this kind of software. What its partner portal says, read on 2026-11-24:
- it is for software in which people buy activations: bots, panels, services;
- the software passes its own ID with each order, and the program pays a percentage of every completed activation its users make, with no cap, for as long as the software is active;
- the rate is set individually for each piece of software;
- connecting software takes an application and a review of one business day, and needs API access;
- withdrawal from $10 on request in the dashboard, processed within one business day, in USDT (TRC-20) or USDC (BEP-20, Polygon).
The application is on the partner portal. What changes in the bot's code is on For software owners.