Registry / communication / telegram

telegram

JSON →
library0.0.1jsnpmunverified

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.

npm install telegram
INSTALL
IMPORT
SIG · TELEGRAM
T
telegram
communicationjavascriptv0.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TelegramClient
import { TelegramClient } from 'telegram';
const TelegramClient = require('telegram').TelegramClient;
GramJS primarily uses ES Modules. For CommonJS, bundlers like Webpack or Babel are recommended, or ensure correct `type: "module"` in package.json.
StringSession
import { StringSession } from 'telegram/sessions';
import { StringSession } from 'telegram';
Session classes like `StringSession` and `StoreSession` are imported from the `telegram/sessions` subpath, not directly from the main `telegram` package.
StoreSession
import { StoreSession } from 'telegram/sessions';
const { StoreSession } = require('telegram/sessions');
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.
Request Classes (e.g., Api.users.GetUsers)
await client.invoke(new Api.users.GetUsers({ id: [...] }));
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()`.

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.

import { TelegramClient } from "telegram"; import { StringSession } from "telegram/sessions"; import readline from "readline"; const apiId = parseInt(process.env.TELEGRAM_API_ID ?? '0'); const apiHash = process.env.TELEGRAM_API_HASH ?? ''; const sessionString = process.env.TELEGRAM_SESSION ?? ''; const stringSession = new StringSession(sessionString); if (!apiId || !apiHash) { console.error("Error: TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables are required."); console.error("You can obtain them from https://my.telegram.org/"); process.exit(1); } const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); (async () => { console.log("Loading interactive example..."); const client = new TelegramClient(stringSession, apiId, apiHash, { connectionRetries: 5, }); try { await client.start({ phoneNumber: async () => new Promise((resolve) => rl.question("Please enter your number: ", resolve) ), password: async () => new Promise((resolve) => rl.question("Please enter your password: ", resolve) ), phoneCode: async () => new Promise((resolve) => rl.question("Please enter the code you received: ", resolve) ), onError: (err) => console.error("Login error:", err), }); console.log("You should now be connected."); const currentSessionString = client.session.save(); console.log("Save this session string to avoid logging in again:\n", currentSessionString); console.log(`To use it automatically next time, set environment variable: export TELEGRAM_SESSION='${currentSessionString}'`); await client.sendMessage("me", { message: "Hello from GramJS!" }); console.log("Message sent to 'me'."); } catch (error) { console.error("An error occurred during client interaction:", error); } finally { rl.close(); if (client.connected) { await client.disconnect(); } } })();
Debug
Known issues
breakingGramJS 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`.
fix
Use `import` statements for all GramJS modules. If using Node.js without a bundler, ensure your project's `package.json` has `"type": "module"`.
affects: >=2.0.0
gotchaSensitive 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.
fix
Always use environment variables (e.g., `process.env.TELEGRAM_API_ID`), a secure configuration management system, or dedicated secrets managers for these credentials.
affects: *
gotchaWhen 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.
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.
affects: *
deprecatedThe older documentation on `painor.gitbook.io/gramjs` will be removed in the future. Relying on this older resource may lead to outdated information.
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.
affects: *
gotchaUsers in regions where Telegram is blocked by ISPs might encounter connection issues. GramJS inherits these network restrictions and may fail to connect.
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`.
affects: *
Errors
Common errors & fixes
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'telegram' imported from ...
Attempting to `require()` an ES Module package directly in a CommonJS context without proper configuration or bundling.
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.
ReferenceError: localStorage is not defined
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.
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.
Telegram API error: AUTH_KEY_UNREGISTERED (caused by GetConfigRequest)
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.
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.
TypeError: Cannot read properties of undefined (reading 'start')
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.
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.
Upgrade
Version history
0.0.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
54 hits · last 30 days
node
48
OpenAI (training)
1
Resources
telegram — npm install telegram · libregistry