GramJS - Telegram Client

2.26.22 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

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();
    }
  }
})();

view raw JSON →