If you want to use gramjs in a browser please check the advanced installation page.
Once you've installed gramjs you'll need an API ID and an API hash (read more in Authorization). Get them from https://my.telegram.org/apps:
Afterward, you can use the following code to send a message to yourself.
hello.js
const { TelegramClient } =require('telegram')const { StringSession } =require('telegram/sessions')constinput=require('input') // npm i inputconstapiId=123456constapiHash='123456abcdfg'conststringSession=newStringSession(''); // fill this later with the value from session.save()(async () => {console.log('Loading interactive example...')constclient=newTelegramClient(stringSession, apiId, apiHash, { connectionRetries:5 })awaitclient.start({phoneNumber:async () =>awaitinput.text('number ?'),password:async () =>awaitinput.text('password?'),phoneCode:async () =>awaitinput.text('Code ?'),onError: (err) =>console.log(err), });console.log('You should now be connected.')console.log(client.session.save()) // Save this string to avoid logging in againawaitclient.sendMessage('me', { message:'Hello!' });})()
hello.ts
import { TelegramClient } from'telegram'import { StringSession } from'telegram/sessions'import input from'input'; // npm i inputconstapiId=123456constapiHash='123456abcdfg'conststringSession=newStringSession(''); // fill this later with the value from session.save()(async () => {console.log('Loading interactive example...');constclient=newTelegramClient(stringSession, apiId, apiHash, { connectionRetries:5 });awaitclient.start({phoneNumber:async () =>awaitinput.text('number ?'),password:async () =>awaitinput.text('password?'),phoneCode:async () =>awaitinput.text('Code ?'),onError: (err) =>console.log(err), });console.log('You should now be connected.');console.log(client.session.save()) // Save this string to avoid logging in againawaitclient.sendMessage('me', { message:'Hello!' });})()
Using session strings is the most reliable way to save your session for now.
Full API
gramjs is still in its early stages but it can access all API methods from telegram using the following
fullapi.js
const {Api} =require("telegram/tl");constresult=awaitclient.invoke(newApi.channels.CheckUsername({ username:"testing"}));console.log("Result is ",result);
fullapi.ts
import {Api} from"telegram/tl";constresult=awaitclient.invoke(newApi.channels.CheckUsername({ username:"testing"}));console.log("Result is ",result);
All methods and classes are accessible under Api. for a full list of them check out https://gram.js.org/