GramJS - Telegram Client
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.
Common errors
-
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'telegram' imported from ...
cause Attempting to `require()` an ES Module package directly in a CommonJS context without proper configuration or bundling.fixChange `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
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.fixEnsure 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)
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.fixDouble-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')
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.fixEnsure 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.
Warnings
- breaking 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`.
- gotcha 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.
- gotcha 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.
- deprecated The older documentation on `painor.gitbook.io/gramjs` will be removed in the future. Relying on this older resource may lead to outdated information.
- gotcha Users in regions where Telegram is blocked by ISPs might encounter connection issues. GramJS inherits these network restrictions and may fail to connect.
Install
-
npm install telegram -
yarn add telegram -
pnpm add telegram
Imports
- TelegramClient
const TelegramClient = require('telegram').TelegramClient;import { TelegramClient } from 'telegram'; - StringSession
import { StringSession } from 'telegram';import { StringSession } from 'telegram/sessions'; - StoreSession
const { StoreSession } = require('telegram/sessions');import { StoreSession } from 'telegram/sessions'; - Request Classes (e.g., Api.users.GetUsers)
await client.invoke(new Api.users.GetUsers({ id: [...] }));
Quickstart
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();
}
}
})();