Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Moderation and Security

Anti-Spam, AutoMod and Input Validation

Detect floods, duplicates, mention spam and unwanted links in chat bots, normalize tricky Unicode, validate command arguments and escape output for Telegram and Discord.

Every message a bot reads is input from strangers. Some of it is spam, some is abuse, and a little is crafted to break your bot. Two skills help: detecting bad behavior in streams of messages (anti-spam), and treating every single piece of text as untrusted before you use it (validation and escaping). This lesson builds small, testable versions of both.

Platforms also ship their own tools: Discord has AutoMod rules for keywords, spam and mention limits, and Telegram has admin settings and anti-spam features for large groups. Use them first; they run with no code and no delay. Your bot adds the rules they cannot express: community-specific words, custom escalation, and logging.

Rule detection is a pipeline

Run each message through small independent checks. Each returns a verdict or nothing. A final step turns verdicts into actions (delete, warn, mute) using the ladder from moderation commands. Small checks are easy to test and easy to tune.

Flood detection with a sliding window

A flood is "too many messages in a short time". Keep the timestamps of each user's recent messages and drop those outside the window.

Node.js Sliding-window flood detector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Memory note: delete entries for users who stop talking, or the Map grows forever (see the cleanup ideas in bot state in memory).

Normalizing text before matching

Spammers dodge word filters with look-alike characters, zero-width characters and spacing: fr\u200Bee, frะตะต (with Cyrillic ะต). Normalize first, then match.

Node.js Normalize, then filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Word filters always produce false positives (the "Scunthorpe problem") and can never be complete. Prefer to delete and warn politely, let moderators review, and keep a word list that is easy to edit without redeploying.

Typical rules and a few safe ways to write them:

  • Links: extract hosts with the URL class instead of ad-hoc regexes, then compare with an allow-list or block-list. Remember https://good.example.com.evil.test ends with evil.test, not good.example.com.
  • Invites: match Discord invite links to other servers and delete them unless the author has permission.
  • Mention spam: count @everyone, @here, role and user mentions per message. More than about five is rarely a normal message. Discord's AutoMod has a built-in mention limit.
  • Duplicate messages: hash the normalized text and see how often one user (or many users) sent it in the last minute.
Node.js Link and mention checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the look-alike domain example.org.evil.test is correctly rejected: the check uses the parsed hostname and requires an exact match or a real subdomain.

Validating command arguments

Anything after /command is input. Validate it as strictly as a web form:

  • Check the type (number, ID, duration), the range and the length.
  • Use allow-lists for choices. Discord slash command options can declare choices, min_value and max_length, and the client enforces them, but a request can be crafted, so check again on the server.
  • Parse durations with a strict pattern (30m, 2h, 7d) and cap them. A mute for 99999999999d should be refused.
Node.js Strict argument parsing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Escaping output

The reverse direction matters too. If your bot repeats user text, make sure the text cannot do things.

  • Telegram: with parse_mode: "HTML", escape &, < and > in user text, or the message fails with a parse error (and a user could inject links). With MarkdownV2 many punctuation characters need backslashes, which is error-prone; HTML is simpler.
  • Discord: control what a message may ping with allowed_mentions (for example { "parse": [] } to ping no one). Without it, a bot that echoes "@everyone" can ping the whole server. Escape Markdown characters when showing names, so a nickname like **bold** or a link cannot restyle your embed.
Node.js Escaping for Telegram HTML and Discord Markdown

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Never build SQL, shell commands or file paths from user text; use parameters (SQLite storage), argument arrays and allow-listed names.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the sliding-window flood detector, why filter old timestamps on every message?

    Only messages inside the window count toward the limit; old ones must be dropped.
  2. 2. Why normalize text before matching a word filter?

    Spammers insert invisible characters and similar-looking letters to avoid exact matches.
  3. 3. Which check correctly rejects https://example.org.evil.test?

    Substring checks are fooled by look-alike hosts; compare the parsed hostname structurally.
  4. 4. What does allowed_mentions: { parse: [] } do on Discord?

    It tells Discord not to resolve any mentions in the content into notifications.

Summary

  • Build moderation as a pipeline of small checks: flood, duplicates, links, mentions, words.
  • Use sliding windows for rates and normalize Unicode before matching words.
  • Parse URLs with URL, compare hostnames structurally, and keep allow-lists.
  • Validate every argument for type, range and length on the server, even when the client enforces it.
  • Escape output (Telegram HTML, Discord Markdown) and set allowed_mentions.

Next: Command handler architecture