Skip to content

Calls & messaging

Post risky signup alerts to Discord

Send an embed to a Discord channel webhook when a signup email is undeliverable or disposable, and add an optional /verify slash command with discord.js.

Updated 2026-11-26

This recipe posts a Discord embed to a channel each time your signup backend finds an undeliverable or disposable email address, so your team sees suspicious accounts as they arrive. An optional second part adds a /verify slash command, built with discord.js, that checks an email or a phone number on demand. There is no Qelka Discord app: the alerts need only a channel webhook, and the command runs as a bot of your own.

What you need

  • A Discord server where you have the Manage Webhooks permission on the alert channel.
  • A backend that already checks signups, for example as in the Node.js integration. The alert code runs on Node.js 18 or later.
  • For the slash command: an application created in the Discord Developer Portal and a host that keeps a Node.js process running.
  • A Qelka API key. A sk_test_ key returns simulated results and never spends credits: see Test mode. Give the bot its own key restricted to email and phone in the dashboard: see Restricted keys.

Steps

1. Create the channel webhook

Open the alert channel's settings, go to Integrations, then Webhooks, and create a webhook. Give it a name such as Signup checks and copy its URL. Store it as an environment variable on your backend:

bash
DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/123456789012345678/your-webhook-token

Prefer a private channel: each alert contains a personal email address.

2. Post the alert

Call this function after your signup check, with the email and the API result. It returns without waiting for Discord, so a Discord outage never slows down or blocks a signup:

javascript
const colors = { undeliverable: 0xd92d20, risky: 0xf79009 }

const clip = (text, length = 1024) => String(text).slice(0, length)

export function alertIfRisky(email, result) {
  const disposable = result.status === 'risky' && result.reason === 'disposable'
  if (result.status !== 'undeliverable' && !disposable) return
  const shown = result.reason === 'invalid_syntax' ? '(invalid syntax, not shown)' : email
  const payload = {
    username: 'Signup checks',
    allowed_mentions: { parse: [] },
    embeds: [
      {
        title: disposable ? 'Disposable email at signup' : 'Undeliverable email at signup',
        color: colors[result.status],
        fields: [
          { name: 'Email', value: clip(shown), inline: true },
          { name: 'Reason', value: result.reason, inline: true },
          { name: 'Suggestion', value: clip(result.did_you_mean ?? 'none'), inline: true },
        ],
        footer: { text: result.id },
        timestamp: new Date().toISOString(),
      },
    ],
  }
  send(payload).catch((error) => console.error('discord alert failed', error.message))
}

async function send(payload, attempt = 1) {
  const response = await fetch(process.env.DISCORD_WEBHOOK_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
    signal: AbortSignal.timeout(5000),
  })
  if (response.status === 429 && attempt < 3) {
    const body = await response.json().catch(() => ({}))
    const wait = Number(body.retry_after ?? response.headers.get('Retry-After') ?? 1)
    await new Promise((resolve) => setTimeout(resolve, Math.min(wait, 10) * 1000))
    return send(payload, attempt + 1)
  }
  if (response.status === 404) console.error('discord webhook deleted: create a new one')
  else if (!response.ok) console.error(`discord webhook answered ${response.status}`)
}

A few details carry weight here:

  • allowed_mentions with an empty parse list stops Discord from turning text into mentions. The email comes from a stranger, so never let it ping @everyone.
  • Embed fields render Markdown, masked links included. An address that failed the syntax check can carry the brackets and parentheses of a link, so shown hides it; a well-formed address cannot contain them.
  • Discord limits an embed field value to 1,024 characters and refuses the whole message beyond it, hence clip. These limits are Discord's and may change: see its message documentation.
  • A 429 carries retry_after, in seconds, in the body and a Retry-After header. The code waits and tries twice more, then gives up.
  • A 404 means the webhook was deleted. Discord asks clients to stop calling a webhook that answers 404, so replace the URL rather than retrying.

3. Test it

With a test key, disposable@example.com returns risky with the reason disposable, and nomx@example.com returns undeliverable with domain_no_mx, in both full and fast mode. Sign up with both on a staging environment and two embeds appear in the channel. To test the webhook alone, send it a request from your terminal:

bash
curl -X POST "$DISCORD_WEBHOOK_URL" \
  -H "Content-Type: application/json" \
  -d '{"content": "Webhook test", "allowed_mentions": {"parse": []}}'

Optional: a /verify slash command

4. Create the bot

In the Discord Developer Portal, create an application, open its Bot page and reset the token to copy it. Install the application in your server with the bot and applications.commands scopes. Store three values on the host that runs the bot:

bash
DISCORD_TOKEN=your-bot-token
DISCORD_CLIENT_ID=your-application-id
DISCORD_GUILD_ID=your-server-id
QELKA_API_KEY=sk_test_your_key

Install discord.js and mark the project as an ES module:

bash
npm install discord.js
npm pkg set type=module

5. Register the command

Save as deploy-commands.js and run it once with node deploy-commands.js:

javascript
import { InteractionContextType, PermissionFlagsBits, REST, Routes, SlashCommandBuilder } from 'discord.js'

const command = new SlashCommandBuilder()
  .setName('verify')
  .setDescription('Check an email address or a phone number')
  .addStringOption((option) =>
    option.setName('value').setDescription('An email, or a phone number with its + prefix').setRequired(true),
  )
  .addStringOption((option) =>
    option.setName('country').setDescription('Two-letter country for a number without +').setMinLength(2).setMaxLength(2),
  )
  .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild)
  .setContexts(InteractionContextType.Guild)

const rest = new REST().setToken(process.env.DISCORD_TOKEN)
await rest.put(Routes.applicationGuildCommands(process.env.DISCORD_CLIENT_ID, process.env.DISCORD_GUILD_ID), {
  body: [command.toJSON()],
})
console.log('registered /verify')

A guild command is registered for your server only. setDefaultMemberPermissions hides it from members without Manage Server until an admin changes that.

6. Answer it

Save as bot.js and keep it running with node bot.js (under a process manager or on a platform that runs workers):

javascript
import { Client, EmbedBuilder, Events, GatewayIntentBits, MessageFlags } from 'discord.js'

const client = new Client({ intents: [GatewayIntentBits.Guilds] })
const retryable = new Set([429, 500, 502, 503])

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 { 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 toEmbed(value, outcome) {
  const embed = new EmbedBuilder().setTitle(value.slice(0, 256))
  if (outcome.failure) return embed.setDescription(`Could not check right now (${outcome.failure}).`)
  const result = outcome.result
  if (result.object === 'email') {
    return embed.addFields(
      { name: 'Status', value: result.status, inline: true },
      { name: 'Reason', value: result.reason, inline: true },
      { name: 'Suggestion', value: result.did_you_mean ?? 'none', inline: true },
    )
  }
  return embed.addFields(
    { name: 'Status', value: result.status, inline: true },
    { name: 'E.164', value: result.e164 ?? 'none', inline: true },
    { name: 'Line type', value: result.line_type, inline: true },
  )
}

client.on(Events.InteractionCreate, async (interaction) => {
  if (!interaction.isChatInputCommand() || interaction.commandName !== 'verify') return
  try {
    await interaction.deferReply({ flags: MessageFlags.Ephemeral })
    const value = interaction.options.getString('value', true).trim()
    const country = interaction.options.getString('country')?.toUpperCase()
    const outcome = value.includes('@')
      ? await verify('email', { email: value })
      : await verify('phone', country ? { phone: value, country } : { phone: value })
    await interaction.editReply({ embeds: [toEmbed(value, outcome)] })
  } catch (error) {
    console.error('verify command failed', error.message)
  }
})

client.once(Events.ClientReady, (ready) => console.log(`logged in as ${ready.user.tag}`))
client.login(process.env.DISCORD_TOKEN)

Discord wants an acknowledgement within three seconds. deferReply sends it at once and shows "thinking", and the discord.js guide notes that a deferred reply leaves 15 minutes to edit it, plenty for a full email check with its 15-second timeout. The Guilds intent is all a slash command bot needs: it reads no messages.

Read the result

Result Meaning What to do
Email undeliverable Bad syntax, no domain or no mailbox Alert posted: contact the person another way, or offer the suggestion
Email risky, reason disposable A throwaway inbox Alert posted: no free trial or credit until confirmed
Email risky, other reasons Catch-all domain or full mailbox No alert; watch bounces
Email deliverable or unknown Accepted, or not conclusive No alert. unknown is not a bad address
Phone valid Fits its numbering plan Use e164; check line_type before sending SMS
Phone invalid Does not fit the plan Ask for the number again
Phone unknown No + and no country Run the command again with country

Decide what to block in your signup code, not in Discord: see Block disposable email signups. The email reference lists every reason.

Handle errors and rate limits

Nothing is billed on errors. 401 invalid_api_key, 403 forbidden and 402 insufficient_credits end as "Could not check" in the command, with the error type and the X-Request-Id in the bot's log. 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 Discord's side, webhooks have their own per-webhook rate limits, and Discord temporarily blocks an IP address that sends too many requests answered 401, 403 or 429. If signups arrive in bursts, group alerts into one message with several embeds (Discord accepts up to ten per message) rather than sending one request per address.

Frequently asked questions

Do I need a bot for the alerts?
No. A channel webhook is enough: your backend sends one HTTPS request per alert, with no bot account, no gateway connection and no library. You need a bot only for the optional /verify slash command, because Discord sends slash commands to an application, not to a webhook.
Is the webhook URL a secret?
Yes. The URL contains the webhook's token, and anyone who has it can post in your channel under the webhook's name. Keep it in an environment variable or a secret store, never in client code or a public repository. If it leaks, delete the webhook in the channel's settings and create a new one.
Who can run the /verify command?
The command below is registered for one server and, by default, only for members with the Manage Server permission, because each check spends credits and returns personal data. Server admins can change who may use it in the server's Integrations settings. The answer is ephemeral: only the person who ran it sees it.

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