censor-tg-bot

command module
v0.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Censor Telegram Bot

A plugin-based antispam bot for Telegram groups, written in Go.

Report Bug · Request Feature

Table of Contents

About The Project

Censor Telegram Bot helps group administrators automatically detect and remove unwanted messages — spam, abuse, scams, flooding, forwarded content, and other policy violations.

A plugin system lets you choose which checks to run, in what order, and whether to execute them sequentially or in parallel. Built-in Prometheus metrics and a pre-configured Grafana dashboard give visibility into filtering effectiveness and plugin performance.

Features

  • Plugin-based architecture — extend with custom filtering logic
  • 8 built-in plugins:
    • Keyword — block messages containing blacklisted words (case-insensitive, Unicode-normalized)
    • Regex — block messages matching regular expression patterns
    • Rate Limit — limit messages per user within a time window
    • Forwarded — restrict forwarded messages by allowed user/chat IDs
    • Duplicate — detect and block repeated messages from a user
    • Users — blacklist/whitelist specific user IDs
    • LLM — analyze message content via an external LLM API
    • Decisions — structured decisions with calibrated probabilities via a decisions API
  • Photo moderation — photos are downloaded once per message; the duplicate plugin compares SHA-256 digests and the LLM plugin sends the image to the model. The configured model must support image input: with a text-only model the photo request fails and the message falls back to CENSOR__ERROR_ACTION (default block)
  • Sequential or parallel execution strategies
  • Automatic user banning after configurable violation threshold
  • Admin notifications — real-time alerts with plugin details for blocked messages and bans
  • Prometheus metrics — plugin evaluations, durations, errors, and bot actions
  • Grafana dashboard — pre-configured monitoring dashboard
  • Dockerized — ready for containerized deployment
  • Cross-platform builds — Linux, macOS, Windows via GoReleaser

Built With

  • Go
  • telegram-bot-api — Telegram Bot API wrapper
  • openai-go — OpenAI-compatible API client for the LLM plugin
  • fx — dependency injection
  • Fiber — HTTP server for metrics endpoint
  • Prometheus — metrics and monitoring
  • Grafana — monitoring dashboards
  • Koanf — configuration management

Getting Started

Prerequisites
  • Go 1.25.5+ (for building from source)
  • Docker (for containerized deployment)
  • Prometheus & Grafana (optional, for monitoring)
Installation
docker run -d --name censor-tg-bot \
  --env-file .env \
  -v "$(pwd)/configs:/app/configs:ro" \
  ghcr.io/capcom6/censor-tg-bot
Docker Compose
services:
  bot:
    image: ghcr.io/capcom6/censor-tg-bot
    env_file: .env
    volumes:
      - ./configs:/app/configs:ro
    restart: unless-stopped

Both examples mount the host configs directory into the container working directory (/app), so CONFIG_PATH=configs/config.yml resolves inside the container. A file that is not mounted is silently ignored at startup.

From Source
git clone https://github.com/capcom6/censor-tg-bot.git
cd censor-tg-bot
go build -o censor-tg-bot .
./censor-tg-bot

Usage

Copy .env.example to .env, then set your bot token and admin ID.

The bot will process messages in groups where it has admin permissions. Blocked messages are deleted, the admin is notified with plugin details, and repeat offenders are automatically banned after exceeding the configured threshold.

# Run with hot reload during development
air

# Run tests
go test ./...

# Build
make build

Configuration

The application loads configuration from environment variables (via .env file) and optionally from a YAML file specified by the CONFIG_PATH environment variable. Sources are merged with process environment variables taking precedence over .env values, which in turn override the YAML file.

Environment Variables
Variable Required Default Description
BOT__ADMIN_ID Yes — Telegram user ID of the administrator
TELEGRAM__TOKEN Yes — Bot token from @BotFather
BOT__BAN_THRESHOLD No 3 Number of violations before automatic ban
BOT__MEDIA__MAX_BYTES No 10485760 Maximum size of a downloaded photo (10 MiB)
BOT__MEDIA__TIMEOUT No 5s Photo content download deadline (file metadata lookup uses TELEGRAM__TIMEOUT)
CENSOR__ENABLED_ONLY No true Only run plugins marked as enabled
CENSOR__ERROR_ACTION No block Default action when a plugin errors (block or allow)
CENSOR__SKIP_ACTION No allow Default action when all plugins skip (block or allow)
CENSOR__STRATEGY No sequential Execution strategy (sequential or parallel)
CENSOR__TIMEOUT No 30s Time budget for evaluating one message across all plugins
CACHE__SWEEP_INTERVAL No 1m How often the cachefx sweeper evicts expired cache entries
CACHE__URL No memory://?max_entries=1000 App-wide cache backend shared by plugins (memory://[?max_entries=N] or redis://...; LRU cap applies per cache)
CONFIG_PATH No — Path to YAML configuration file
DEBUG No false Enable debug logging and Telegram API request logging (true)
HTTP__ADDRESS No 127.0.0.1:3000 Metrics endpoint address
HTTP__PROXIES No — Trusted proxy IPs — a single IP or a JSON array (e.g. ["127.0.0.1"]); comma-separated lists are not split
HTTP__PROXY_HEADER No X-Forwarded-For Proxy header for trusted proxies
STORAGE__TTL No 5m Sliding idle-window for user violation counters (ban threshold)
TELEGRAM__PROXY_URL No — SOCKS5 proxy URL
TELEGRAM__TIMEOUT No 60s Timeout for Telegram API requests (raised to a 70s minimum)
YAML Configuration

Create a config.yml file and set the CONFIG_PATH environment variable to load it:

telegram:
  proxy_url: "socks5://user:pass@127.0.0.1:1080"
  timeout: "90s"

bot:
  media:
    max_bytes: 10485760 # maximum size of a downloaded photo (10 MiB)
    timeout: 5s # deadline for a single photo download

censor:
  strategy: sequential
  timeout: 30s
  enabled_only: true
  error_action: block
  skip_action: allow

http:
  address: "127.0.0.1:3000"
  proxy_header: "X-Forwarded-For"
  proxies: []
Plugin Configuration

Plugins are configured under censor.plugins in YAML:

censor:
  plugins:
    keyword:
      enabled: true
      priority: 20
      config:
        blacklist:
          - spam
          - scam
          - phishing

    ratelimit:
      enabled: true
      priority: 15
      config:
        max_messages: 5
        window: "1m"

    regex:
      enabled: false
      priority: 25
      config:
        patterns:
          - 'https?://[\w\-\.]+\.xyz'
          - '\b\d{16}\b'

    forwarded:
      enabled: false
      priority: 10
      config:
        allowed_user_ids:
          - 123456789
        allowed_chat_ids:
          - -1001234567890

    duplicate:
      enabled: true
      priority: 150
      config:
        max_duplicates: 1
        window: "5m"

    users:
      enabled: true
      priority: 5
      config:
        blacklist: []
        whitelist: []

    llm:
      enabled: false
      priority: 260
      config:
        api_key: "<your-api-key>"
        model: "nvidia/nemotron-3.5-super-vl:free"
        confidence_threshold: 0.8
        timeout: 30s
        prompt: "Analyze the following message..."
        temperature: 0.1

    decisions:
      enabled: false
      priority: 250
      config:
        api_key: "<your-api-key>"
        model: "perplexity/pplx-decider-v1.3:free"
        block_threshold: 0.7
        timeout: 30s

Note: Provide your API key through an environment variable (e.g., CENSOR__PLUGINS__LLM__CONFIG__API_KEY) or an uncommitted local config file to avoid committing secrets.

Keyword Plugin

Blocks messages containing blacklisted keywords with case-insensitive matching and Unicode normalization.

Config Key Type Default Description
blacklist []string — Keywords to block

Use Cases: Blocking profanity, filtering promotional keywords, preventing specific terminology.


Rate Limit Plugin

Prevents spam by limiting the number of messages a user can send within a time window.

Config Key Type Default Description
max_messages int 5 Maximum messages allowed per window
window string "1m" Time window (e.g., 30s, 5m, 1h)

Use Cases: Preventing message flooding, limiting bot abuse, protecting against rapid-fire spam.


Regex Plugin

Blocks messages matching regular expression patterns.

Config Key Type Default Description
patterns []string — Array of regex patterns

Use Cases: Blocking URL patterns, detecting credit card numbers, filtering complex patterns.


Forwarded Plugin

Blocks forwarded messages from non-exception sources. Only messages forwarded from allowed user IDs or chat IDs pass through.

Config Key Type Default Description
allowed_user_ids []int64 [] User IDs whose forwards are allowed
allowed_chat_ids []int64 [] Chat/channel IDs whose forwards are allowed

Use Cases: Preventing unauthorized message forwarding, controlling content flow from specific channels.


Duplicate Plugin

Detects and blocks repetitive messages from a user within a time window. Messages are normalized (lowercased, whitespace-collapsed) before comparison.

Photos are compared by the SHA-256 digest of their content, so the same picture is detected even when its caption changes. The photo is downloaded once per message and counted under its own key, next to the text.

Config Key Type Default Valid Range Description
max_duplicates int 1 >= 0 Max duplicate messages allowed before blocking
window string "5m" 10s – 24h Time window for duplicate detection

Use Cases: Preventing copy-paste spam, blocking repeated promotional messages, reducing channel noise.


Users Plugin

Blocks or allows messages based on user IDs. Whitelisted users are always allowed; blacklisted users are always blocked; users in neither list are skipped.

Config Key Type Default Description
blacklist []int [] User IDs to block
whitelist []int [] User IDs to always allow (overrides blacklist)

Use Cases: Blocking known spammers, creating VIP lists, implementing user-based access control.


LLM Plugin

Blocks messages containing potentially inappropriate content, spam, or violations by analyzing the message with an external LLM API. Supports response caching (TTL-bound, app-wide cache backend) to reduce API costs.

Photos are sent to the model as an image next to the caption, so a picture is evaluated even when it carries no text. The cache key contains the digest of the photo, so the same caption with a different image is a new request.

Config Key Type Default Valid Range Description
base_url string "https://openrouter.ai/api/v1" — LLM API base URL
api_key string "" — API key (required)
model string "nvidia/nemotron-3.5-super-vl:free" — Model identifier (must support image input)
confidence_threshold float 0.8 0.0 – 1.0 Minimum confidence to block
timeout string "30s" 5s – 5m API call timeout
prompt string see default — LLM prompt
temperature float 0.1 0.0 – 2.0 LLM sampling temperature
cache_enabled bool true — Enable response caching
cache_ttl string "1h" 1m – 24h Cache entry TTL

Use Cases: Filtering semantic spam that evades keyword matching, multi-language moderation, context-sensitive content filtering.


Decisions Plugin

Blocks messages by asking an OpenRouter Decisions API a fixed set of atomic questions about the message. Unlike an LLM, a decisions model returns typed answers with calibrated probabilities instead of generated text: one request, parallel questions, no parsing of prose. The plugin is vendor-neutral: base_url points at any endpoint implementing POST /decisions.

The plugin sends one request with three questions and composes the answers in code:

Question Type Asks
category choice Main purpose of the message: spam, scam, abuse, other
spam noul Is this unsolicited advertising or self-promotion?
abuse noul Is this insulting, threatening, or harassing someone?

A message is blocked when a violation category (spam/scam/abuse) wins with probability ≥ block_threshold, or when the spam or abuse yes/no probability reaches block_threshold. Otherwise the plugin skips — it never returns allow, so it cannot override another plugin's block. The admin notification carries the category and probabilities (e.g. Reason: spam (p=0.97)).

Answers are cached (TTL-bound, app-wide cache backend); editing a question's text in config invalidates cached entries. Text-only: photo-only messages are skipped for now.

Config Key Type Default Valid Range Description
base_url string "https://openrouter.ai/api/alpha" — Base URL of the decisions API (appends /decisions)
api_key string "" — API key (required)
model string "perplexity/pplx-decider-v1.3:free" — Decision model (see models)
block_threshold float 0.7 0.0 – 1.0 Probability at or above which a violation blocks
timeout string "30s" 5s – 5m API call timeout
context string "" — Optional context added to the state (group topic, rules)
cache_enabled bool true — Enable answer caching
cache_ttl string "1h" 1m – 24h Cache entry TTL
questions map see below — Per-question instructions and criteria text overrides

The question text is configurable; question IDs, types, and option keys stay fixed in code. Omitted fields keep the defaults printed below:

config:
  context: "A group about cats"
  questions:
    category:
      instructions: "Which category best describes the main purpose of the message?"
      criteria:
        spam: "Unsolicited advertising, self-promotion, or promotional links; not ordinary conversation or a useful link"
        scam: "Phishing, fake giveaways, fake support agents, or requests for credentials and money"
        abuse: "Insults, threats, hate speech, or harassment aimed at a person"
        other: "Ordinary conversation, questions, reactions, or anything that fits none of the other categories"
    spam:
      instructions: "Is this message unsolicited advertising or self-promotion?"
      criteria:
        "true": "Unsolicited advertising, self-promotion, or a promotional link"
        "false": "Legitimate conversation or a useful, on-topic link"
    abuse:
      instructions: "Is this message insulting, threatening, or harassing someone?"
      criteria:
        "true": "Insults, threats, slurs, or personal attacks against a person"
        "false": "Friendly, neutral, or light banter with no target"

Use Cases: Low-latency spam and abuse gating with explicit confidence signals, tuning the policy without a redeploy, replacing prompt-engineered LLM checks with typed decisions.

Execution Strategies

The censor service supports two strategies:

Sequential (Default)

Plugins execute in priority order (lower number = earlier execution).

  • Each plugin runs sequentially
  • If a plugin returns ActionAllow, execution stops and the message is allowed
  • If a plugin returns ActionBlock, execution continues — later plugins may still ActionAllow
  • If all plugins skip, the configured skip_action is applied
  • If no plugin explicitly allows but at least one blocks, the message is blocked

Best for: Most use cases, efficient resource usage.

censor:
  strategy: sequential
Parallel

All plugins execute concurrently, results are aggregated.

  • All enabled plugins run simultaneously
  • If any plugin returns ActionAllow, the message is allowed
  • If no allow is found but any plugin returns ActionBlock, the message is blocked
  • If all plugins skip, the configured skip_action is applied

Best for: When all plugins must evaluate every message, high-throughput scenarios.

censor:
  strategy: parallel

Monitoring

Prometheus Metrics

The bot exposes metrics at http://localhost:3000/metrics:

Metric Type Description
censor_plugin_evaluations_total Counter Plugin evaluation counts by action
censor_plugin_duration_seconds Histogram Plugin execution duration
censor_plugin_errors_total Counter Plugin error counts
censor_evaluations_total Counter Message evaluations by final decision (allow/block)
censor_bot_processed_actions_total Counter Bot action counts (message processed, deletions, bans, notifications)
http_requests_total Counter HTTP requests by status code
http_request_duration_seconds Histogram HTTP request latency
Grafana Dashboard

Import the pre-configured dashboard from deployments/grafana/dashboard.json:

  1. Open Grafana
  2. Go to Dashboards → Import
  3. Upload deployments/grafana/dashboard.json
  4. Select your Prometheus datasource

Dashboard panels: bot action distribution, message filter rate over time, plugin performance metrics, HTTP request statistics.

Prometheus Alerts

Configure alerts using deployments/prometheus/alerts.yml:

Bot Alerts:

  • HighBotActionFailureRate — >10% of bot actions fail over 5 minutes
  • BotActionFailures — >5 bot actions fail in 5 minutes (critical)

Plugin Alerts:

  • HighPluginEvaluationFailureRate — >10% of plugin evaluations fail (warning)
  • HighPluginEvaluationFailures — >5 plugin evaluations fail in 5 minutes (critical)

Server Alerts:

  • HighHTTPErrorRate — >5% of HTTP requests return 5xx (warning)
  • HighHTTPRequestLatency — 95th percentile latency exceeds 1 second (warning)
  • HighHTTPThroughput — request rate exceeds 100 req/s (warning)

Creating Custom Plugins

The plugin architecture allows you to implement custom filtering logic by implementing the Plugin interface. See the Creating Custom Plugins guide for details.

Roadmap

See the open issues for a full list of proposed features and known issues.

Contributing

Contributions are welcome!

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Implement your changes with tests
  4. Ensure all tests pass (go test ./...)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request
Development Setup
go mod download
go test ./...
air                     # hot reload
make build              # build binary
make lint               # run golangci-lint
make coverage           # test with coverage

License

Distributed under the Apache-2.0 License. See LICENSE for more information.

Contact

Project maintainer: capcom6

Project link: https://github.com/capcom6/censor-tg-bot

Acknowledgments

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
internal
bot
cache
Package cache provides the application cache factory: cachefx's factory scoped to the "censor-tg-bot" prefix.
Package cache provides the application cache factory: cachefx's factory scoped to the "censor-tg-bot" prefix.
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址