RepoPilotOpen in app →

yagop/node-telegram-bot-api

Telegram Bot API for NodeJS

Healthy

Healthy across the board

weakest axis
Use as dependencyHealthy

Permissive license, no critical CVEs, actively maintained — safe to depend on.

Fork & modifyHealthy

Has a license, tests, and CI — clean foundation to fork and modify.

Learn fromHealthy

Documented and popular — useful reference codebase to read through.

Deploy as-isHealthy

No critical CVEs, sane security posture — runnable as-is.

  • Last commit 5w ago
  • 26+ active contributors
  • MIT licensed
  • CI configured
  • Tests present
  • Concentrated ownership — top contributor handles 56% of recent commits

Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests

Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.

Embed the "Healthy" badge

Paste into your README — live-updates from the latest cached analysis.

Variant:
RepoPilot: Healthy
[![RepoPilot: Healthy](https://repopilot.app/api/badge/yagop/node-telegram-bot-api)](https://repopilot.app/r/yagop/node-telegram-bot-api)

Paste at the top of your README.md — renders inline like a shields.io badge.

Preview social card (1200×630)

This card auto-renders when someone shares https://repopilot.app/r/yagop/node-telegram-bot-api on X, Slack, or LinkedIn.

Onboarding doc

Onboarding: yagop/node-telegram-bot-api

Generated by RepoPilot · 2026-05-07 · Source

🤖Agent protocol

If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:

  1. Verify the contract. Run the bash script in Verify before trusting below. If any check returns FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding.
  2. Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
  3. Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/yagop/node-telegram-bot-api shows verifiable citations alongside every claim.

If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.

🎯Verdict

GO — Healthy across the board

  • Last commit 5w ago
  • 26+ active contributors
  • MIT licensed
  • CI configured
  • Tests present
  • ⚠ Concentrated ownership — top contributor handles 56% of recent commits

<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>

Verify before trusting

This artifact was generated by RepoPilot at a point in time. Before an agent acts on it, the checks below confirm that the live yagop/node-telegram-bot-api repo on your machine still matches what RepoPilot saw. If any fail, the artifact is stale — regenerate it at repopilot.app/r/yagop/node-telegram-bot-api.

What it runs against: a local clone of yagop/node-telegram-bot-api — the script inspects git remote, the LICENSE file, file paths in the working tree, and git log. Read-only; no mutations.

| # | What we check | Why it matters | |---|---|---| | 1 | You're in yagop/node-telegram-bot-api | Confirms the artifact applies here, not a fork | | 2 | License is still MIT | Catches relicense before you depend on it | | 3 | Default branch master exists | Catches branch renames | | 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code | | 5 | Last commit ≤ 62 days ago | Catches sudden abandonment since generation |

<details> <summary><b>Run all checks</b> — paste this script from inside your clone of <code>yagop/node-telegram-bot-api</code></summary>
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of yagop/node-telegram-bot-api. If you don't
# have one yet, run these first:
#
#   git clone https://github.com/yagop/node-telegram-bot-api.git
#   cd node-telegram-bot-api
#
# Then paste this script. Every check is read-only — no mutations.

set +e
fail=0
ok()   { echo "ok:   $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }

# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "FAIL: not inside a git repository. cd into your clone of yagop/node-telegram-bot-api and re-run."
  exit 2
fi

# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "yagop/node-telegram-bot-api(\\.git)?\\b" \\
  && ok "origin remote is yagop/node-telegram-bot-api" \\
  || miss "origin remote is not yagop/node-telegram-bot-api (artifact may be from a fork)"

# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
   || grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
  && ok "license is MIT" \\
  || miss "license drift — was MIT at generation time"

# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
  && ok "default branch master exists" \\
  || miss "default branch master no longer exists"

# 4. Critical files exist
test -f "index.js" \\
  && ok "index.js" \\
  || miss "missing critical file: index.js"
test -f "src/telegram.js" \\
  && ok "src/telegram.js" \\
  || miss "missing critical file: src/telegram.js"
test -f "src/telegramPolling.js" \\
  && ok "src/telegramPolling.js" \\
  || miss "missing critical file: src/telegramPolling.js"
test -f "src/telegramWebHook.js" \\
  && ok "src/telegramWebHook.js" \\
  || miss "missing critical file: src/telegramWebHook.js"
test -f "src/utils.js" \\
  && ok "src/utils.js" \\
  || miss "missing critical file: src/utils.js"

# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 62 ]; then
  ok "last commit was $days_since_last days ago (artifact saw ~32d)"
else
  miss "last commit was $days_since_last days ago — artifact may be stale"
fi

echo
if [ "$fail" -eq 0 ]; then
  echo "artifact verified (0 failures) — safe to trust"
else
  echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/yagop/node-telegram-bot-api"
  exit 1
fi

Each check prints ok: or FAIL:. The script exits non-zero if anything failed, so it composes cleanly into agent loops (./verify.sh || regenerate-and-retry).

</details>

TL;DR

A Node.js library that wraps the official Telegram Bot API, enabling developers to build Telegram bots programmatically without writing raw HTTP requests. It supports both polling (long-polling) and webhook (HTTP POST) update mechanisms, handles file uploads, and provides event-driven APIs for message handling. Currently tracking Bot API v9.6. Single-package structure: src/ contains core modules (telegram.js as main class, telegramPolling.js and telegramWebHook.js as transport layers, utils.js for helpers, errors.js for error types). Built via Babel to lib/ for distribution. Examples in examples/ show polling, webhook, and game patterns. Tests in test/ mirror source structure.

👥Who it's for

Node.js developers building Telegram bots who need a lightweight abstraction over the Telegram Bot API. Users range from hobbyists building simple command bots to teams deploying bots at scale across multiple chat instances.

🌱Maturity & risk

Production-ready and actively maintained. The library is at v0.68.0 with 278KB of JavaScript, comprehensive test coverage (istanbul configured), CI/CD via Travis, and supports Node 0.12+. Regular updates track official Telegram API changes. Well-established with a dedicated Telegram channel and community.

Low risk for core functionality but watch for: dependency on @cypress/request which may diverge from upstream request library, minimal dev team (single author Yago Perez visible), and the 0.x version suggests API stability not yet guaranteed. Last build/commit recency not visible in provided data but changelog and docs appear current.

Active areas of work

Active development against the development branch; experimental features on experimental branch; master tracks releases. Recent work includes API v9.6 support, Babel transpilation setup, and ESLint standardization. Changelog and PR templates present indicating organized release cycle.

🚀Get running

git clone https://github.com/yagop/node-telegram-bot-api.git
cd node-telegram-bot-api
npm install
npm test

Daily commands: Development: npm run build && npm run eslint && npm test. Doc generation: npm run doc (generates doc/api.md via jsdoc2md). Examples: node examples/polling.js (requires TELEGRAM_TOKEN env var) or webhook examples with Express.

🗺️Map of the codebase

  • index.js — Entry point that exports the main TelegramBot class; all external consumers depend on this
  • src/telegram.js — Core TelegramBot class implementing all API methods and request handling; the largest and most critical file
  • src/telegramPolling.js — Polling strategy for receiving updates; essential for long-polling mode bots
  • src/telegramWebHook.js — Webhook strategy for receiving updates; required for webhook-based deployment
  • src/utils.js — Utility functions for formatting and sending data; heavily used across the codebase
  • package.json — Defines dependencies, build pipeline, and publishing configuration
  • src/errors.js — Custom error classes for API and polling errors; critical for error handling

🧩Components & responsibilities

  • TelegramBot (src/telegram.js) (Node.js http/https, EventEmitter) — Main class; exposes all Telegram Bot API methods as instance methods; manages authentication, request/response lifecycle, event emission
    • Failure mode: Invalid API token, Telegram API errors, network timeouts—throws TelegramError with response details
  • TelegramPolling (src/telegramPolling.js) _(setTimeout loops, TelegramBot.request()) — Implements long-polling strategy; periodically calls getUpdates(), parses responses, emits update events
    • Failure mode: Network errors, Telegram API rate limits—logs errors but continues polling with backoff
  • TelegramWebHook (src/telegramWebHook.js) (Node.js https server, crypto for request validation) — Implements webhook strategy; starts HTTPS server, listens for POST requests from Telegram, validates and emits updates
    • Failure mode: Invalid webhook signature, malformed JSON—responds with 400; unhandled exceptions crash server
  • Utils (src/utils.js) (fs (file I/O), mime type detection, form-data encoding) — Formats request data, handles file uploads (multipart), builds query parameters, sanitizes inputs
    • Failure mode: Missing files, invalid MIME types—throws Error with descriptive message

🔀Data flow

  • Telegram UserTelegram Servers — User sends message/command via Telegram client
  • Telegram ServersTelegramPolling or TelegramWebHook — Update delivered via getUpdates() polling or webhook POST request
  • TelegramPolling / TelegramWebHookTelegramBot (EventEmitter) — Parsed update emitted as 'message', 'callback_query', etc. event
  • User handler (bot.on('message'))TelegramBot.sendMessage() or other send methods — Application code processes event and calls API method to send response

🛠️How to make changes

Add a new Telegram Bot API method

  1. Add the method to the TelegramBot class in src/telegram.js following the naming convention (e.g., sendMessage, getChat) (src/telegram.js)
  2. Use formatSendData from src/utils.js to prepare request parameters and handle file uploads if needed (src/utils.js)
  3. Call _request() with the method name and formatted data; handle response and errors (src/telegram.js)
  4. Add unit tests in test/telegram.js to verify the method works with mocked Telegram API responses (test/telegram.js)
  5. Run npm run doc to regenerate API documentation from JSDoc comments (doc/api.md)

Deploy bot with webhook instead of polling

  1. Create a new bot instance with webhook mode in your index file, passing webhook options to the constructor (index.js)
  2. TelegramBot will instantiate TelegramWebHook internally; configure the Express/HTTP server to receive POST at your webhook path (src/telegramWebHook.js)
  3. Use setWebHook() method to register the webhook URL with Telegram's servers (src/telegram.js)
  4. Reference examples/webhook/express.js or examples/webhook/heroku.js for implementation patterns (examples/webhook/express.js)

Handle file uploads (photo, audio, document, etc.)

  1. Call the relevant send method (sendPhoto, sendAudio, sendDocument) with file path, Stream, or Buffer (src/telegram.js)
  2. formatSendData in src/utils.js detects file types and prepares multipart/form-data with proper MIME types (src/utils.js)
  3. The _request method handles streaming or attaching the file to the HTTP request body (src/telegram.js)
  4. Verify with test files in test/data/ (e.g., test/data/photo.png, test/data/audio.mp3) (test/data)

🔧Why these technologies

  • Node.js + JavaScript — Lightweight, event-driven runtime ideal for asynchronous long-polling and webhook handling; easy dependency management via npm
  • Babel transpiler — Enables ES6 syntax in src/ while maintaining backward compatibility with older Node.js versions
  • Mocha + Istanbul coverage — Standard Node.js testing and coverage reporting; integrates well with CI/CD pipelines
  • JSDoc + jsdoc2md — Auto-generates API documentation from inline comments; reduces documentation maintenance burden

⚖️Trade-offs already made

  • Polling vs Webhook as separate update strategies

    • Why: Polling is simpler for development/testing; webhooks are more efficient in production. Library supports both.
    • Consequence: Users must choose strategy upfront; switching requires code changes. Complexity in maintaining two parallel strategies.
  • Minimal external dependencies (no axios, mostly native http)

    • Why: Reduces bloat and dependency conflicts for consumer applications
    • Consequence: Manual HTTP request handling increases code complexity; less abstraction from low-level details
  • Single TelegramBot class handling all API methods

    • Why: Simple, centralized interface; easy to discover available methods
    • Consequence: src/telegram.js becomes very large (~1000+ LOC); harder to maintain and test individual methods

🚫Non-goals (don't propose these)

  • Does not provide authentication/authorization beyond Telegram's native bot token validation
  • Does not handle persistent state or database integration (user responsibility)
  • Not a framework—only an API wrapper; no middleware, routing, or plugin system built-in
  • Does not support inline bots or other Telegram client types (only bot account types)

🪤Traps & gotchas

Bot token must be passed as constructor argument or TELEGRAM_TOKEN env var in examples; no built-in rate limiting (Telegram applies 30 msg/sec per user). Webhook examples require HTTPS and public domain; polling blocks on getUpdates timeout (default 30s). File uploads expect fs.createReadStream, not Buffer. Test data (audio.mp3, sticker.webp) committed to repo for integration tests. EventEmitter3 used instead of Node's built-in EventEmitter (different semantics for once/removeListener).

🏗️Architecture

💡Concepts to learn

  • Long Polling — Fundamental update delivery mechanism in TelegramPolling; trades latency for simplicity and NAT traversal, essential to understand for production deployments
  • Webhook (HTTP POST callbacks) — Alternative transport in TelegramWebHook; lower latency and resource usage but requires HTTPS, public domain, and stateless design—key trade-off vs polling
  • EventEmitter pattern — Core pub/sub model used throughout via EventEmitter3; bots listen for 'message', 'callback_query', etc. events rather than returning values
  • Multipart/form-data file uploads — Required for sending files (photos, documents, voice messages) to Telegram API; handled by utils.js and @cypress/request; understanding form boundaries crucial for debugging
  • Callback queries — Telegram inline button interaction model; sent as callback_query events rather than messages, enabling stateless button handling without polling text
  • Babel transpilation and ES2015 target — Library is written in modern JS (classes, spread, destructuring) but transpiled to ES5 for Node 0.12 compatibility; understanding .babelrc essential for contributing
  • telegraf/telegraf — Alternative Telegram bot framework for Node.js with middleware support and more active development; direct competitor
  • TelegramBots/Telegram.Bot — Official Telegram Bot API wrapper for C#/.NET; reference implementation showing API surface design patterns
  • python-telegram-bot/python-telegram-bot — Python equivalent library; shares same API design philosophy and serves similar developer audience in different language
  • types/node-telegram-bot-api — DefinitelyTyped package providing TypeScript type definitions for this library; essential for TypeScript users
  • awesome-telegram/awesome-telegram — Curated list of Telegram bots and libraries; helps discover ecosystem and learn patterns from real-world bot projects

🪄PR ideas

To work on one of these in Claude Code or Cursor, paste: Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.

Add comprehensive unit tests for src/utils.js

The repo has test/utils.js but examination of the file structure suggests it may only contain utility test helpers rather than comprehensive tests of src/utils.js functions themselves. Given that src/utils.js is a core utility module used throughout the codebase, it lacks dedicated test coverage. This would improve reliability of utility functions that support all bot API interactions.

  • [ ] Review src/utils.js to identify all exported functions and their signatures
  • [ ] Create comprehensive unit tests in test/test.utils.js covering edge cases (empty inputs, invalid types, null values)
  • [ ] Add tests for data formatting functions used in telegram.js
  • [ ] Ensure test coverage reaches >90% for utils module
  • [ ] Update test/README.md to document the new test suite

Migrate from Istanbul/Mocha to GitHub Actions with Node.js matrix testing

The repo uses .travis.yml (legacy Travis CI) and Istanbul for coverage. GitHub Actions is now standard and would provide faster, more integrated CI/CD. The package.json engines field shows support for Node >=0.12, but testing likely needs to verify multiple modern Node versions (14, 16, 18, 20). Adding a GitHub Action workflow would modernize the pipeline and catch version compatibility issues.

  • [ ] Create .github/workflows/test.yml with Node.js matrix strategy (test against Node 14, 16, 18, 20)
  • [ ] Configure the workflow to run: npm run eslint && npm run test
  • [ ] Add codecov/codecov-action step for coverage reporting
  • [ ] Add workflow status badge to README.md
  • [ ] Test that the workflow passes with current codebase

Add integration tests for webhook and polling transport layers in test/

The codebase has src/telegramPolling.js and src/telegramWebHook.js as separate transport mechanisms, but test/telegram.js likely focuses on core API methods. These transport layers handle different connection models and error scenarios that need dedicated testing. Adding integration tests would ensure reliability of both polling and webhook modes in production environments.

  • [ ] Create test/test.polling.js with tests for src/telegramPolling.js covering: start/stop polling, error handling, reconnection logic, update processing
  • [ ] Create test/test.webhook.js with tests for src/telegramWebHook.js covering: server initialization, request validation, HTTPS support, update parsing
  • [ ] Add tests for edge cases: network timeouts, malformed updates, concurrent requests
  • [ ] Ensure tests can run in CI without requiring actual Telegram API credentials (use mocks/stubs)
  • [ ] Update test/README.md with instructions for running transport-specific tests

🌿Good first issues

  • Add comprehensive JSDoc type annotations to src/telegram.js method signatures (currently minimal) to improve IDE autocomplete and enable better @types/node-telegram-bot-api integration
  • Write integration test suite in test/test.integration.js covering webhook transport (currently only unit tests; integration examples exist but untested)
  • Implement automatic retry logic with exponential backoff for polling and webhook failures in src/telegramPolling.js and src/telegramWebHook.js (currently no retry)

Top contributors

Click to expand

📝Recent commits

Click to expand
  • a7c9ef6 — feat: savePreparedKeyboardButton (danielperez9430)
  • f604d37 — feat: Support Bot API v9.6 (danielperez9430)
  • 24fb242 — feat: Added missing methods (danielperez9430)
  • 68e944a — feat: Add timestamps to console.error messages (danielperez9430)
  • cd1c4a1 — chore(Readme): upgrade bot api version (danielperez9430)
  • 93383ea — feat: Bot API v9.6 (danielperez9430)
  • 3d73374 — feat: Bot api v9.3 support (danielperez9430)
  • 4b97158 — feat: sendMessageDraft (#1290) (xjx0106)
  • 5d95b43 — release: v0.67.0 (GochoMugo)
  • 8208490 — doc: update docs (GochoMugo)

🔒Security observations

  • High · Outdated and Vulnerable Dependencies — package.json - dependencies section. The package.json contains several outdated dependencies with known vulnerabilities. Specifically: '@cypress/request' (^3.0.10) and '@cypress/request-promise' (^5.0.0) are based on the deprecated 'request' library which has multiple known security issues. Additionally, 'file-type' (^3.9.0) is significantly outdated (current version is 16+) and may contain unpatched vulnerabilities. The 'babel-eslint' (^8.0.3) is no longer maintained. Fix: Update all dependencies to their latest stable versions. Replace '@cypress/request' with 'axios' or 'node-fetch'. Update 'file-type' to version 16+ and migrate away from 'babel-eslint' to '@babel/eslint-parser'. Run 'npm audit' and address all reported vulnerabilities.
  • High · Minimum Node.js Version is Extremely Old — package.json - engines field. The package.json specifies 'engines': {'node': '>=0.12'}, which was released in 2015. Node.js 0.12 has been EOL since 2016 and contains numerous security vulnerabilities. This allows users to run the bot with severely outdated and insecure Node.js versions. Fix: Update minimum Node.js requirement to at least 14.x or preferably 16.x+. Set 'engines': {'node': '>=14.0.0'} to ensure users have access to security patches.
  • Medium · SSL/TLS Test Certificates Included — examples/ssl/crt.pem, examples/ssl/key.pem. The repository includes SSL/TLS certificates and keys in the examples directory (examples/ssl/crt.pem and examples/ssl/key.pem). While these appear to be test certificates for development examples, their presence in version control could be misused if they were ever real certificates. Fix: Verify these are self-signed test certificates. If they are, add them to .gitignore and regenerate them locally during setup. Document in README that users should never commit real certificates to version control. Consider adding a .gitignore rule: 'examples/ssl/*.pem'
  • Medium · Potential Security Configuration Gaps — .eslintrc - configuration file. The ESLint configuration (eslintrc) extends 'eslint-config-airbnb' (^6.2.0) which is outdated. Additionally, there is no evidence of security-focused linting rules (e.g., eslint-plugin-security) to catch common security issues during development. Fix: Update eslint-config-airbnb to the latest version. Add 'eslint-plugin-security' to devDependencies and extend its configuration in .eslintrc to catch security anti-patterns during linting. Example: 'extends': ['airbnb', 'plugin:security/recommended']
  • Medium · Missing Security Headers Documentation — examples/webhook/ - all webhook example files. The webhook examples (examples/webhook/) do not demonstrate security best practices such as validating Telegram bot updates or implementing rate limiting. There is no evident CSRF protection or input validation documentation. Fix: Add security documentation in CONTRIBUTING.md or a new SECURITY.md file. Include examples of: validating bot tokens, verifying Telegram signatures, implementing rate limiting, and handling user input safely. Add validation middleware examples to webhook files.
  • Low · Missing SECURITY.md File — Repository root. The repository does not contain a SECURITY.md file to document how to report security vulnerabilities, which is a best practice for open-source projects. Fix: Create a SECURITY.md file following GitHub's standard format. Include instructions for responsible disclosure and security contact information.
  • Low · Outdated Istanbul Coverage Tool — package.json - devDependencies. The devDependency 'istanbul' (^1.1.0-alpha.1) is using an alpha version and is outdated. The project should use 'nyc' (the modern replacement for Istanbul). Fix: Replace 'istanbul' with 'nyc' package. Update test script to use nyc instead of istanbul cover.

LLM-derived; treat as a starting point, not a security audit.


Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.

Healthy signals · yagop/node-telegram-bot-api — RepoPilot