Calls & messaging
Check emails and phone numbers with a Telegram bot
Build a private Telegram bot with /email and /phone commands on the Bot API: a webhook that checks the secret token header, then calls the API and replies.
Updated 2026-11-26
This recipe builds a private Telegram bot. You send it /email jane@example.com or /phone +14155550123 and it replies with the result: status and suggestion for an email, status, E.164 format and line type for a phone number. It uses the Telegram Bot API directly, with a webhook and no library, in a single Node.js file. There is no Qelka bot on Telegram: you create your own, so the key and the results stay with you.
What you need
- A Telegram account, to create the bot with BotFather.
- Node.js 20 or later on a host with a public HTTPS address. Telegram sends webhooks only over HTTPS, to ports 443, 80, 88 or 8443, so run the bot behind your platform's TLS or a reverse proxy.
- A Qelka API key. A
sk_test_key returns simulated results and never spends credits: see Test mode. Give the bot a key restricted toemailandphonein the dashboard: see Restricted keys.
Steps
1. Create the bot
In Telegram, open a chat with @BotFather, send /newbot and follow the prompts. BotFather gives you the bot's token. Treat it like a password: whoever has it controls the bot.
2. Store the secrets
Generate a webhook secret. Telegram accepts 1 to 256 characters made of letters, digits, _ and -, which a hex string satisfies:
openssl rand -hex 32
Set these environment variables on the host, never in the code:
TELEGRAM_BOT_TOKEN=123456789:your-bot-token
TELEGRAM_WEBHOOK_SECRET=the-hex-string-you-generated
TELEGRAM_ALLOWED_USERS=11111111,22222222
QELKA_API_KEY=sk_test_your_key
TELEGRAM_ALLOWED_USERS lists the numeric Telegram user ids allowed to use the bot. Leave it empty at first: the bot logs the id of everyone who writes to it, so you can read yours from the log and add it.
3. The bot
Save as bot.js and start it with node bot.js:
import { createServer } from 'node:http'
import { timingSafeEqual } from 'node:crypto'
const botToken = process.env.TELEGRAM_BOT_TOKEN
const secret = Buffer.from(process.env.TELEGRAM_WEBHOOK_SECRET ?? '')
const allowed = new Set((process.env.TELEGRAM_ALLOWED_USERS ?? '').split(',').map((id) => id.trim()).filter(Boolean))
const retryable = new Set([429, 500, 502, 503])
function secretMatches(header) {
const given = Buffer.from(typeof header === 'string' ? header : '')
return secret.length > 0 && given.length === secret.length && timingSafeEqual(given, secret)
}
async function telegram(method, payload) {
const response = await fetch(`https://api.telegram.org/bot${botToken}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10000),
})
const body = await response.json()
if (!body.ok) console.error(`telegram ${method} failed: ${body.description}`)
}
async function verify(kind, payload) {
for (let attempt = 1; attempt <= 3; attempt += 1) {
let response
try {
response = await fetch(`https://api.qelka.com/v1/${kind}`, {
method: 'POST',
headers: { Authorization: `Bearer ${process.env.QELKA_API_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: AbortSignal.timeout(15000),
})
} catch {
return { failure: 'unreachable' }
}
if (response.ok) return { result: await response.json() }
if (retryable.has(response.status) && attempt < 3) {
const retryAfter = Number(response.headers.get('Retry-After'))
await new Promise((resolve) => setTimeout(resolve, (retryAfter > 0 ? Math.min(retryAfter, 5) : attempt) * 1000))
continue
}
const failure = (await response.json().catch(() => null))?.error?.type ?? `http_${response.status}`
console.error(`validation skipped: ${failure} request ${response.headers.get('X-Request-Id')}`)
return { failure }
}
}
function describe(outcome) {
if (outcome.failure) return `Could not check right now (${outcome.failure}). Try again in a minute.`
const result = outcome.result
if (result.object === 'email') {
const lines = [`${result.input}`, `Status: ${result.status}`, `Reason: ${result.reason}`]
if (result.did_you_mean) lines.push(`Did you mean: ${result.did_you_mean}`)
return lines.join('\n')
}
if (result.status === 'unknown') return `${result.input}\nStatus: unknown. Add the + prefix, or a country code: /phone 06 12 34 56 78 FR`
if (result.status === 'invalid') return `${result.input}\nStatus: invalid for its numbering plan`
return [`${result.input}`, 'Status: valid', `E.164: ${result.e164}`, `Line type: ${result.line_type}`, `Country: ${result.country.name}`].join('\n')
}
async function handle(update) {
const message = update.message
if (!message?.text?.startsWith('/')) return
const [first, ...rest] = message.text.trim().split(/\s+/)
const command = first.split('@')[0].toLowerCase()
if (command !== '/email' && command !== '/phone' && command !== '/start') return
const userId = String(message.from?.id ?? '')
if (!allowed.has(userId)) {
console.log(`refused user ${userId}`)
await telegram('sendMessage', { chat_id: message.chat.id, text: 'This bot is private.' })
return
}
if (command === '/start' || rest.length === 0) {
await telegram('sendMessage', { chat_id: message.chat.id, text: 'Send /email jane@example.com or /phone +14155550123' })
return
}
let outcome
if (command === '/email') {
outcome = await verify('email', { email: rest[0] })
} else {
const last = rest[rest.length - 1]
const country = rest.length > 1 && /^[A-Za-z]{2}$/.test(last) ? last.toUpperCase() : null
const phone = (country ? rest.slice(0, -1) : rest).join(' ')
outcome = await verify('phone', country ? { phone, country } : { phone })
}
await telegram('sendMessage', {
chat_id: message.chat.id,
text: describe(outcome),
reply_parameters: { message_id: message.message_id },
})
}
createServer((request, response) => {
if (request.method !== 'POST' || request.url !== '/telegram') {
response.writeHead(404).end()
return
}
if (!secretMatches(request.headers['x-telegram-bot-api-secret-token'])) {
response.writeHead(401).end()
return
}
const chunks = []
request.on('data', (chunk) => chunks.push(chunk))
request.on('end', () => {
response.writeHead(200).end()
let update
try {
update = JSON.parse(Buffer.concat(chunks).toString('utf8'))
} catch {
return
}
handle(update).catch((error) => console.error('update failed', error.message))
})
}).listen(Number(process.env.PORT) || 8080)
What each part does:
secretMatchescompares the header with your secret in constant time and refuses the request with401before reading its body.- The server answers
200as soon as the body has arrived, then handles the update. Telegram repeats a request that does not get a 2xx answer, so answering late could make it send the same command twice. - Commands are matched on their first word, with any
@YourBotsuffix removed, so the bot also works when you mention it in a group. - The email check runs in the default
fullmode, mailbox check included, because nothing waits on the reply: see the email reference. A phone number without+takes a country as its last word, as in/phone 06 12 34 56 78 FR: see the phone reference. - Replies are plain text, with no
parse_mode, so an address full of underscores or asterisks is shown exactly as typed.
4. Register the webhook
Point Telegram at your server and give it the secret. allowed_updates limits deliveries to new messages:
curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
-H "Content-Type: application/json" \
-d "{\"url\": \"https://bot.example.com/telegram\", \"secret_token\": \"$TELEGRAM_WEBHOOK_SECRET\", \"allowed_updates\": [\"message\"]}"
Telegram answers {"ok":true,...}. Call getWebhookInfo the same way to see the last delivery error if the bot stays silent.
5. Add the command menu
Optional: list the commands so Telegram suggests them when you type /:
curl "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setMyCommands" \
-H "Content-Type: application/json" \
-d '{"commands": [{"command": "email", "description": "Verify an email address"}, {"command": "phone", "description": "Validate a phone number"}]}'
6. Test it
With a test key, send /email disposable@example.com: the bot answers risky with the reason disposable. /email undeliverable@example.com gives undeliverable. Phone numbers are parsed for real even with a test key, so /phone +14155550123 returns the true E.164 format and line type.
Read the reply
| Reply | Meaning | What to do |
|---|---|---|
Email deliverable |
The mail server accepted the mailbox | Use it |
Email undeliverable |
Bad syntax, no domain or no mailbox | Ask for another address, or use the suggestion |
Email risky |
Disposable inbox, catch-all domain or full mailbox | Read the reason before deciding |
Email unknown |
The checks could not conclude | Not a bad address: try again later |
Phone valid |
Fits its numbering plan | Store the E.164 form; a landline often cannot receive SMS |
Phone invalid |
Does not fit the plan | Ask for the number again |
Phone unknown |
No + and no country |
Send it again with a country code |
| Could not check | The API was unreachable or refused the call | The log has the error type and request id |
Handle errors and rate limits
Nothing is billed on errors. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key, 402 insufficient_credits an empty balance: the bot replies "Could not check" and logs the error type with the X-Request-Id. 429 rate_limited, 500, 502 and 503 are retried after Retry-After, capped at five seconds. A key allows 200 requests per 10 seconds. Each email check costs 1 credit and each basic phone check 1. See Errors and Rate limits.
On Telegram's side, a call that exceeds its flood limits returns ok: false with parameters.retry_after, the number of seconds to wait. A private bot used by a few people stays far from those limits; the bot logs the failure and moves on. If you rotate the webhook secret, call setWebhook again with the new value before you deploy the server that expects it.
Related
Frequently asked questions
Why check the X-Telegram-Bot-Api-Secret-Token header?
Can strangers use my bot?
Why does the server answer Telegram before running the check?
More in Calls & messaging
All integrationsPut this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time