{"id":16236,"library":"telegram","title":"GramJS - Telegram Client","description":"GramJS is a JavaScript-based client library for interacting with the Telegram MTProto API, designed to function across both Node.js environments and web browsers. It is currently in active development, with version 2.26.22 being the latest stable release at the time of writing, showing a pattern of frequent updates. Key differentiators include its core architecture, which is based on the popular Python Telethon library, providing a robust and feature-rich foundation. It allows developers to build userbots and custom Telegram applications by directly accessing the MTProto API, handling session management, and offering mechanisms for sending messages and invoking raw API methods. The library supports persistent sessions, either via string-based or file-based storage, to avoid repeated logins. It also provides dedicated guidance for browser integration, typically requiring webpack for bundling.","status":"active","version":"2.26.22","language":"javascript","source_language":"en","source_url":"https://github.com/gram-js/gramjs","tags":["javascript","telegram","mtproto","userbot","api","typescript"],"install":[{"cmd":"npm install telegram","lang":"bash","label":"npm"},{"cmd":"yarn add telegram","lang":"bash","label":"yarn"},{"cmd":"pnpm add telegram","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"GramJS primarily uses ES Modules. For CommonJS, bundlers like Webpack or Babel are recommended, or ensure correct `type: \"module\"` in package.json.","wrong":"const TelegramClient = require('telegram').TelegramClient;","symbol":"TelegramClient","correct":"import { TelegramClient } from 'telegram';"},{"note":"Session classes like `StringSession` and `StoreSession` are imported from the `telegram/sessions` subpath, not directly from the main `telegram` package.","wrong":"import { StringSession } from 'telegram';","symbol":"StringSession","correct":"import { StringSession } from 'telegram/sessions';"},{"note":"Similar to `StringSession`, `StoreSession` is located in the `telegram/sessions` subpath. Using `require` for this subpath might work with certain bundlers but is not the idiomatic ESM approach.","wrong":"const { StoreSession } = require('telegram/sessions');","symbol":"StoreSession","correct":"import { StoreSession } from 'telegram/sessions';"},{"note":"To call raw Telegram API methods, import specific request classes (e.g., `GetUsers`) from `telegram/tl/api` or directly use `Api` namespace if imported. Then, pass an instance of the request class to `client.invoke()`.","symbol":"Request Classes (e.g., Api.users.GetUsers)","correct":"await client.invoke(new Api.users.GetUsers({ id: [...] }));"}],"quickstart":{"code":"import { TelegramClient } from \"telegram\";\nimport { StringSession } from \"telegram/sessions\";\nimport readline from \"readline\";\n\nconst apiId = parseInt(process.env.TELEGRAM_API_ID ?? '0');\nconst apiHash = process.env.TELEGRAM_API_HASH ?? '';\nconst sessionString = process.env.TELEGRAM_SESSION ?? '';\nconst stringSession = new StringSession(sessionString);\n\nif (!apiId || !apiHash) {\n  console.error(\"Error: TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables are required.\");\n  console.error(\"You can obtain them from https://my.telegram.org/\");\n  process.exit(1);\n}\n\nconst rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout,\n});\n\n(async () => {\n  console.log(\"Loading interactive example...\");\n  const client = new TelegramClient(stringSession, apiId, apiHash, {\n    connectionRetries: 5,\n  });\n\n  try {\n    await client.start({\n      phoneNumber: async () =>\n        new Promise((resolve) =>\n          rl.question(\"Please enter your number: \", resolve)\n        ),\n      password: async () =>\n        new Promise((resolve) =>\n          rl.question(\"Please enter your password: \", resolve)\n        ),\n      phoneCode: async () =>\n        new Promise((resolve) =>\n          rl.question(\"Please enter the code you received: \", resolve)\n        ),\n      onError: (err) => console.error(\"Login error:\", err),\n    });\n    console.log(\"You should now be connected.\");\n    const currentSessionString = client.session.save();\n    console.log(\"Save this session string to avoid logging in again:\\n\", currentSessionString);\n    console.log(`To use it automatically next time, set environment variable: export TELEGRAM_SESSION='${currentSessionString}'`);\n\n    await client.sendMessage(\"me\", { message: \"Hello from GramJS!\" });\n    console.log(\"Message sent to 'me'.\");\n\n  } catch (error) {\n    console.error(\"An error occurred during client interaction:\", error);\n  } finally {\n    rl.close();\n    if (client.connected) {\n      await client.disconnect();\n    }\n  }\n})();","lang":"javascript","description":"This example demonstrates how to initialize the `TelegramClient`, authenticate using phone number/password/code (or a saved session string from `TELEGRAM_SESSION` environment variable), and send a message to 'me'. It requires `TELEGRAM_API_ID` and `TELEGRAM_API_HASH` environment variables."},"warnings":[{"fix":"Use `import` statements for all GramJS modules. If using Node.js without a bundler, ensure your project's `package.json` has `\"type\": \"module\"`.","message":"GramJS primarily uses ES Modules (ESM). Direct CommonJS `require()` statements might lead to issues unless you use a bundler (like Webpack) or configure Node.js with `\"type\": \"module\"` in your `package.json`.","severity":"breaking","affected_versions":">=2.0.0"},{"fix":"Always use environment variables (e.g., `process.env.TELEGRAM_API_ID`), a secure configuration management system, or dedicated secrets managers for these credentials.","message":"Sensitive API ID, API Hash, and session strings should NEVER be hardcoded or shared publicly. Compromising these details can lead to unauthorized access to your Telegram account and applications.","severity":"gotcha","affected_versions":"*"},{"fix":"Refer to the 'Running GramJS inside browsers' section in the official documentation, which typically involves using `webpack` or a similar bundler to create a browser-compatible build.","message":"When running GramJS in a browser environment, special considerations apply. It requires bundling with tools like Webpack and uses `localStorage` for caching. Direct usage without proper bundling will likely fail.","severity":"gotcha","affected_versions":"*"},{"fix":"Always refer to the official documentation at `gram.js.org` or the beta documentation at `gram.js.org/beta` for the most current and accurate information.","message":"The older documentation on `painor.gitbook.io/gramjs` will be removed in the future. Relying on this older resource may lead to outdated information.","severity":"deprecated","affected_versions":"*"},{"fix":"Consult resources like the provided Gist 'My ISP blocks Telegram. How can I still use GramJS?' for potential solutions, which often involve using proxies or VPNs, configurable via the `connection` option in `TelegramClient`.","message":"Users in regions where Telegram is blocked by ISPs might encounter connection issues. GramJS inherits these network restrictions and may fail to connect.","severity":"gotcha","affected_versions":"*"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Change `const telegram = require('telegram');` to `import { TelegramClient } from 'telegram';` and ensure your `package.json` has `\"type\": \"module\"` or use a bundler like Webpack/Rollup.","cause":"Attempting to `require()` an ES Module package directly in a CommonJS context without proper configuration or bundling.","error":"Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'telegram' imported from ..."},{"fix":"Ensure you are running the correct build for your target environment. For Node.js, ensure you're not using browser-specific configurations. For browsers, use a bundler like Webpack as described in the GramJS documentation.","cause":"Attempting to run browser-specific GramJS code (which uses `localStorage` for caching) in a Node.js environment, or in a browser environment without proper Webpack bundling.","error":"ReferenceError: localStorage is not defined"},{"fix":"Double-check your `TELEGRAM_API_ID` and `TELEGRAM_API_HASH` values obtained from my.telegram.org. If using a session string (`TELEGRAM_SESSION`), ensure it's valid and not corrupted. Try logging in fresh if issues persist.","cause":"The API ID and API Hash are incorrect, or the session string is invalid/expired, leading to a failure in authenticating with the Telegram servers.","error":"Telegram API error: AUTH_KEY_UNREGISTERED (caused by GetConfigRequest)"},{"fix":"Ensure the `TelegramClient` object is correctly instantiated and accessible within the scope where `start()` is invoked. Verify that `await` is used correctly with async functions and that the client object exists.","cause":"The `TelegramClient` instance was not properly initialized or is out of scope when `client.start()` is called, often due to incorrect async/await handling or variable scoping.","error":"TypeError: Cannot read properties of undefined (reading 'start')"}],"ecosystem":"npm"}