Skip to content

Calls & messaging

Validate emails and phone numbers in Slack

Build a Slack app with Bolt for JavaScript that answers /verify with an email or phone check, and post an alert to a channel when a signup email is bad.

Updated 2026-11-26

This recipe builds a small Slack app with two jobs. Your team types /verify jane@example.com or /verify +14155550123 in any channel and gets the answer back privately. Your signup backend posts an alert to a channel when a new account uses an undeliverable or disposable email address. There is no Qelka app in the Slack Marketplace: you run this app yourself, with Bolt for JavaScript, Slack's official framework.

What you need

  • A Slack workspace where you may create and install apps. Some workspaces require an admin to approve new apps.
  • Node.js 20 or later. Bolt for JavaScript 5 requires it.
  • A host with a public HTTPS address for the slash command's Request URL. While you build, Socket Mode avoids the public address (step 4).
  • A Qelka API key. A sk_test_ key returns simulated results and never spends credits: see Test mode. For the app, create a key restricted to email and phone in the dashboard, so a leak cannot start a bulk job on your balance: see Restricted keys.

Steps

1. Create the Slack app

At api.slack.com/apps, select Create New App and start from scratch in your workspace. Then:

  1. Under OAuth & Permissions, add the bot token scopes commands and chat:write.
  2. Under Slash Commands, select Create New Command. Set Command to /verify, Request URL to https://your-host.example.com/slack/events, a short description and the usage hint email or phone number.
  3. Install the app to your workspace. Copy the Bot User OAuth Token (it starts with xoxb-) from OAuth & Permissions, and the Signing Secret from Basic Information.

Bolt checks the signing secret on every request, so a forged request to your Request URL is refused before your code runs.

2. Store the secrets

Set three environment variables on the host, never in the code:

bash
SLACK_BOT_TOKEN=xoxb-your-bot-token
SLACK_SIGNING_SECRET=your-signing-secret
QELKA_API_KEY=sk_test_your_key

On a platform such as Fly.io, Render, Railway, Heroku or a cloud provider, use its secrets settings. Locally, keep them in a .env file that is listed in .gitignore and start Node with node --env-file=.env app.js.

3. Write the check

Install Bolt and mark the project as an ES module:

bash
npm install @slack/bolt @slack/web-api
npm pkg set type=module

Save as validation.js. It reads the command text, picks the endpoint, retries what can be retried and never throws:

javascript
const retryable = new Set([429, 500, 502, 503])

export function parseInput(text) {
  const parts = text.trim().split(/\s+/)
  if (parts[0].includes('@')) return { kind: 'email', body: { email: parts[0] } }
  const last = parts[parts.length - 1]
  if (parts.length > 1 && /^[A-Za-z]{2}$/.test(last)) {
    return { kind: 'phone', body: { phone: parts.slice(0, -1).join(' '), country: last.toUpperCase() } }
  }
  return { kind: 'phone', body: { phone: parts.join(' ') } }
}

export async function verify({ kind, body }) {
  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(body),
        signal: AbortSignal.timeout(15000),
      })
    } catch {
      return { checked: false, failure: 'unreachable' }
    }
    if (response.ok) return { checked: true, 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 { checked: false, failure }
  }
}

export function describe(input, outcome) {
  if (!outcome.checked) return `Could not check ${input} right now (${outcome.failure}). Try again in a minute.`
  const result = outcome.result
  if (result.object === 'email') {
    const hint = result.did_you_mean ? `, did you mean ${result.did_you_mean}?` : ''
    return `${result.input}: ${result.status} (${result.reason})${hint}`
  }
  if (result.status === 'valid') return `${result.input}: valid, ${result.e164}, ${result.line_type}, ${result.country.name}`
  if (result.status === 'unknown') return `${result.input}: unknown. Add the + prefix, or a country code after the number: /verify 415 555 0123 US`
  return `${result.input}: not a valid number in its numbering plan`
}

A person waits for this answer, so the email check runs in the default full mode, mailbox check included, with a 15-second timeout. A phone number written without + needs a country, which the command accepts as a last word: /verify 06 12 34 56 78 FR. See the email reference and the phone reference.

4. Answer the slash command

Save as app.js:

javascript
import { App } from '@slack/bolt'
import { describe, parseInput, verify } from './validation.js'

const app = new App({
  token: process.env.SLACK_BOT_TOKEN,
  signingSecret: process.env.SLACK_SIGNING_SECRET,
})

app.command('/verify', async ({ command, ack, respond }) => {
  await ack()
  const input = command.text.trim()
  const text = input
    ? describe(input, await verify(parseInput(input)))
    : 'Usage: /verify jane@example.com or /verify +14155550123'
  try {
    await respond({ response_type: 'ephemeral', text })
  } catch (error) {
    console.error('respond failed', error.message)
  }
})

await app.start(Number(process.env.PORT) || 3000)

ack() answers Slack at once, which is what Slack's 3-second rule asks for. The check runs afterwards and respond() posts the answer to the command's response_url. Bolt listens on /slack/events, the path you gave as Request URL.

To develop without a public address, turn on Socket Mode in the app settings, generate an app-level token with the connections:write scope under Basic Information, and construct the app with socketMode: true and appToken: process.env.SLACK_APP_TOKEN instead of signingSecret. Then app.start() needs no port. Switch back to the Request URL for production.

5. Post an alert from your signup backend

Your signup backend already checks each new email, as in the Node.js integration. Pass the result to this function. It posts to a channel when the address is undeliverable or disposable, and it never waits for Slack, so a Slack problem can never slow down or block a signup:

javascript
import { WebClient } from '@slack/web-api'

const slack = new WebClient(process.env.SLACK_BOT_TOKEN, { retryConfig: { retries: 0 } })

const escape = (text) => String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')

export function alertIfRisky(email, result) {
  const disposable = result.status === 'risky' && result.reason === 'disposable'
  if (result.status !== 'undeliverable' && !disposable) return
  const label = disposable ? 'Disposable email at signup' : 'Undeliverable email at signup'
  slack.chat
    .postMessage({
      channel: process.env.SLACK_ALERT_CHANNEL,
      text: `${label}: ${escape(email)} (${result.reason})`,
      blocks: [
        { type: 'section', text: { type: 'mrkdwn', text: `*${label}*` } },
        {
          type: 'section',
          fields: [
            { type: 'mrkdwn', text: `*Email*\n${escape(email)}` },
            { type: 'mrkdwn', text: `*Reason*\n${result.reason}` },
            { type: 'mrkdwn', text: `*Suggestion*\n${escape(result.did_you_mean ?? 'none')}` },
            { type: 'mrkdwn', text: `*Lookup*\n${result.id}` },
          ],
        },
      ],
    })
    .catch((error) => console.error('slack alert failed', error.data?.error ?? error.message))
}

Set SLACK_ALERT_CHANNEL to the channel ID, which you can copy from the channel's details in Slack, and invite the app to that channel, or Slack answers not_in_channel. The escape function matters: the email comes from a stranger, and Slack reads < and > as control sequences, which could otherwise turn an address into a channel-wide mention.

Read the answer

Answer Meaning What to do
Email deliverable The mail server accepted the mailbox Nothing
Email undeliverable Bad syntax, no domain or no mailbox Reach the person another way, or offer the suggestion
Email risky with disposable A throwaway inbox Treat the account with care: no free trial, no credit
Email risky, other reasons Catch-all domain or full mailbox Keep it, watch for bounces
Email unknown The checks could not conclude Not a bad address: check again later
Phone valid Fits its numbering plan Use the e164 form; check the line type before sending SMS
Phone invalid Does not fit the plan Ask for the number again
Phone unknown No + and no country Run it again with a country code
Could not check The API was unreachable or refused the call Nothing is blocked; the log line has the reason and request id

The alert is for people, not a gate: decide in your signup code what to block, as in Block disposable email signups.

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 command then answers "Could not check" and the log names the error type and 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, whether a person or the backend asks. See Errors and Rate limits.

On the Slack side, respond() throws when the response_url has expired or been used too often, and the app logs it. The alert client does not retry, and Slack rate-limits chat.postMessage per channel: if signups come in bursts, send one digest message every few minutes instead of one message per address. An alert contains a personal email address, so post it to a private channel limited to the people who need it.

Frequently asked questions

Why does Slack show operation_timeout when I run /verify?
Slack expects the app to acknowledge a slash command within 3 seconds, and a full email check can take longer because it waits for the recipient's mail server. The app below calls ack() first and sends the answer afterwards through respond(), which posts to the command's response_url. Slack documents that a response_url accepts up to 5 responses within 30 minutes.
Where do I keep the Slack tokens and the API key?
In environment variables or the secret store of the host that runs the app: SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET and the API key. Never commit them, and never put the API key in a Slack message, a workflow step or a canvas. Give the app a restricted key that can only call /email and /phone, separate from the key your signup backend uses.
Can everyone in the channel see the result?
No. respond() sends an ephemeral message by default, visible only to the person who ran the command. You can send response_type in_channel instead, but think twice: the answer contains a personal email address or phone number, and a channel message stays in its history.

More in Calls & messaging

All integrations

Put 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