gram-js / gramjs

NodeJS/Browser MTProto API Telegram client library,
MIT License
1.28k stars 179 forks source link

How to re-use the auth token to avoid the auth process again? #401

Closed velidan closed 2 years ago

velidan commented 2 years ago

Hi. I'm working with the library and trying to use it in the Nest.js framework. I managed to log in as a user and start the app however every time when I change the source code the app should be restarted and in this way, I must enter the phone number/confirmation code every time when it happens. My question is: How can I reuse the auth token to automatically log in the user without constant manual re-authorization? I could save this token in some file whatever however I don't see any method to be able to sign in via it.

Thanks for any help

Here is the code example, not sure if it's useful

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

const { TelegramClient } = require('telegram');
const { StringSession } = require('telegram/sessions');
const input = require('input'); // npm i input

import { TelegramProvider } from './TelegramProvider';

// just need to connect to telegram from CLI before app starts
// cause I don't know how to do it in other way
const stringSession = new StringSession('');
(async () => {
  console.log('Loading interactive example...');
  TelegramProvider.client = new TelegramClient(
    stringSession,
    Number(process.env.TELEGRAM_APP_ID),
    process.env.TELEGRAM_APP_API_HASH,
    {
      connectionRetries: 5,
    },
  );

  console.log('events', TelegramProvider.client.events);
  await TelegramProvider.client.start({
    phoneNumber: async () => await input.text('Please enter your number: '),
    password: async () => await input.text('Please enter your password: '),
    phoneCode: async () =>
      await input.text('Please enter the code you received: '),
    onError: (err) => console.log(err),
  });
  TelegramProvider.client.session.save(); // Save this string to avoid logging in again but it doesn't work
  await TelegramProvider.client.sendMessage('me', { message: 'Hello!' });
  await bootstrap();
})();

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}

The TelegramProvider is a very simple container for the gram.js client

import { Injectable } from '@nestjs/common';

@Injectable()
export class TelegramProvider {
  static client;
}
painor commented 2 years ago

You just need to save the the result of TelegramProvider.client.session.save(); somewhere (it's a string) and then put it inside new StringSession('');

velidan commented 2 years ago

Gush, thank you so much. I've spent a few hours struggling with this silly issue.