Giter Site home page Giter Site logo

alik0211 / mtproto-core Goto Github PK

View Code? Open in Web Editor NEW
613.0 17.0 109.0 968 KB

Telegram API JS (MTProto) client library for Node.js and browser

Home Page: https://mtproto-core.js.org

License: GNU General Public License v3.0

JavaScript 100.00%
telegram telegram-api mtproto tdlib browser client library lib api messenger

mtproto-core's People

Contributors

alexpts avatar alik0211 avatar pogudin-sergey avatar ruslanasadov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mtproto-core's Issues

Login without confirmation (not first time)

I need to be able to log in once, and then logging in automatically (without receiving SMS or another confirmations). Is it possible?
Use is planned in Electron application

when i am printing the user variable it does not have value

``const { MTProto, getSRPParams } = require('@mtproto/core');
const prompt = require('prompt');

const mtproto = new MTProto({
api_id: 10562,
api_hash: '85b72864f343b7346733c84720197',

test: false,
});

const phone = '+918085614';
const code = '2222';
// const password = 'hellojs';

function sendCode(phone) {
// console.log("hello");
return mtproto.call('auth.sendCode', {
api_id: 1056862,
api_hash: '85b72864f343b7346733c847201',
phone_number: phone,
settings: {
_: 'codeSettings',
},
})
// .catch(error=>{console.log(error)});
}

sendCode(phone)
.catch(error => {
if (error.error_message.includes('MIGRATE')) {
const [type, nextDcId] = error.error_message.split('MIGRATE');

  mtproto.setDefaultDc(+nextDcId);

  return sendCode(phone);
}

})
.then( result => {
f1(result.phone_code_hash);

})

async function f1(phone_code_hash){
prompt.start();
await prompt.get(['username'], async function (err, result) {
if (err) { console.log(err); }
else{
// console.log(phone,phone_code_hash,result.username);
// console.log(typeof(result.username));

 		const { user } = await mtproto.call('auth.signIn', {
			phone_number   : phone,
			phone_code_hash: phone_code_hash,
			phone_code     : result.username
		}).catch(function(err){console.log(err);});
		console.log("hi"+user);
	
 }
});

}

Serialize error at request with params

When do any request with params, eg

mtproto
    .call('messages.getDialogs', {
      offset_id: 0,
      offset_date: 0,
      limit: 20,
    })
    .then((r) => {
      console.log(`result:`, r)
    })
    .catch((e) => {
      console.log(`error:`, e)
    })

I get the following error

Uncaught (in promise) TypeError: Cannot read property '_' of undefined
    at TLSerializer.predicate (serializer.js:153)
    at serializer.js:100
    at Array.forEach (<anonymous>)
    at TLSerializer.method (serializer.js:85)
    at MTProto.call (main.js:384)
    at main.js:246
    at Array.forEach (<anonymous>)
    at MTProto.sendWaitMessages (main.js:239)
    at MTProto.handleTransportOpen (main.js:110)
    at Transport.emit (events.js:141)
    at Transport.handleOpen (transport.js:34)

I use mtproto-core 2.0.2 in chrome 81

Global error event

Is there anyway to get globals connection errors events? Sometimes i get "transport error". I Revoked a session an i got "SESSION_REVOKED" from methods. Global event handling for connection problems will help with this issues.

Error when call "messages.getDialogs".

Seems that there is a bug when you try to call messages.getDialogs:

function call:

// handling updates client.updates.on('updateShortMessage', message => { console.log("changed update:", message); // get messages client.call('messages.getDialogs', { limit: 100 }).then(results => { console.log("dialog results", results); }); });

error:

(node:8394) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_' of undefined at TLSerializer.predicate (/Users/flaviolacer/Projects/edi-telegram/node_modules/@mtproto/core/src/tl/serializer/index.cjs:130:71) at /Users/flaviolacer/Projects/edi-telegram/node_modules/@mtproto/core/src/tl/serializer/index.cjs:81:12 at Array.forEach (<anonymous>) at TLSerializer.method (/Users/flaviolacer/Projects/edi-telegram/node_modules/@mtproto/core/src/tl/serializer/index.cjs:68:23) at RPC.call (/Users/flaviolacer/Projects/edi-telegram/node_modules/@mtproto/core/src/rpc/index.cjs:463:16) at MTProto.call (/Users/flaviolacer/Projects/edi-telegram/node_modules/@mtproto/core/src/index.cjs:72:28)

Error after using some time

I don't know how to generate, but i'm getting this error after working sometime:
/app/telegram it´s my local application path.

You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
5|telegram  | Error: bad_server_salt. Not found message with id 6827092132166629724
5|telegram  |     at RPC.handleDecryptedMessage (/app/telegram/node_modules/@mtproto/core/src/rpc/index.cjs:376:17)
5|telegram  |     at RPC.handleEncryptedMessage (/app/telegram/node_modules/@mtproto/core/src/rpc/index.cjs:351:10)
5|telegram  |     at processTicksAndRejections (internal/process/task_queues.js:97:5)

How to return value

Im new in node js and I dont how to return value from mtproto.

const mtproto = new MTProto({
api_id,
api_hash,

// Use test servers
test: true,

});

const getCountry = async () => {
mtproto.call('help.getNearestDc').then((result) => {
return result.country;
});
};

const country = getCountry();
console.log(country);

when I run it return Error
Error: invalid ciphertext size (must be multiple of 16 bytes)

Current auth status

Is there any way to check current auth status? I'm getting AUTH_RESTART error trying to log in and being already logged in. It would be good to have something like isSignedIn: true in MTProto object.

localStorage is not defined when run this code

const { MTProto } = require('@mtproto/core');

const api_id = 'xxxxx';
const api_hash = 'xxxxxxxx';

// 1. Create an instance
const mtproto = new MTProto({
api_id,
api_hash,
test: true,
});

changing dcid issue

if i have migrated to dcid=5 then while signing in my crendiatals are on dcid 5 so when i am using method exportAuthorization and passing dcid=5 it throws an error dcid invalid

Refactor transport

  1. Auto reconnect into Transport
  2. Reconnect only for defaultDc
  3. All connects into MTProto constructor

Add type definitions

At some point, devs will need type definitions for better Intellisense. At this point, migrating to Typescript or creating a d.ts file manually are few of the options.
If the API is going to be minimal in the long term (like just client.call ) simple index.d.ts created manually should be enough

Add tests

  • deserializer
  • serializer
  • utils/common
  • utils/crypto
  • utils/pq
  • utils/rsa

Add support NodeJS

  • Storage (localStorage)
  • Transport (WebSocket)
  • navigator
  • crypto

Transport API

this.transport = new Transport(dcId);

this.transport.on('error', () => {});
this.transport.on('open', () => {});
this.transport.on('close', () => {});
this.transport.on('message', () => {});

this.transport.destroy();

this.transport.send();

Nothing happens after calling auth.signIn

I just copy login example, and have problem. Nothings happens after calling auth.signIn. All code which i try is below. I try it with such versions as

And then nothing happens after two minutes, even so Telegram send me message about new logged device

const { MTProto, getSRPParams } = require('@mtproto/core');
const readline = require('readline');
var cl = readline.createInterface( process.stdin, process.stdout );
var question = function(q) {
    return new Promise( (res, rej) => {
        cl.question( q, answer => {
            res(answer);
        })
    });
};

const mtproto = new MTProto({
  api_id: ,
  api_hash: '',
  test: false
});

const phone = '';
const password = '';

function sendCode(phone) {
  return mtproto.call('auth.sendCode', {
    phone_number: phone,
    settings: {
      _: 'codeSettings',
    },
  });
}

let code_hash

sendCode(phone)
  .catch(error => {
    if (error.error_message.includes('_MIGRATE_')) {
      const [type, nextDcId] = error.error_message.split('_MIGRATE_');

      mtproto.setDefaultDc(+nextDcId);

      return sendCode(phone);
    }
    else return sendCode(phone);
  })
  .then(result => {
      code_hash = result.phone_code_hash
      return question('Code')
  })
  .then(code => {
    return mtproto.call('auth.signIn', {
      phone_code: code,
      phone_number: phone,
      phone_code_hash: code_hash,
    });
   //after this part nothing happens
  })
  .catch(error => {
    if (error.error_message === 'SESSION_PASSWORD_NEEDED') {
      return mtproto.call('account.getPassword').then(async result => {
        const { srp_id, current_algo, srp_B } = result;
        const { salt1, salt2, g, p } = current_algo;

        const { A, M1 } = await getSRPParams({
          g,
          p,
          salt1,
          salt2,
          gB: srp_B,
          password,
        });

        return mtproto.call('auth.checkPassword', {
          password: {
            _: 'inputCheckPasswordSRP',
            srp_id,
            A,
            M1,
          },
        });
      });
    }
  })
  .then(result => {
    console.log('auth.authorization:', result);
  })

not a good update of v3.1.0

my all previous codes are not working and there is a bug i need to login every time beacuse it terminate previous session and has given me flood wait

more methods to save session

Issue

Both node and browser environments can save sessions in their localstorage as of now, which may work fine for general use cases. but if user is on temporary device like Heroku or even Electron, the current storage will not work, and will get destroyed on each restart.

One alternative I can suggest is using "String Session" like telethon does in python. it's basically emitting a string that contains our sessions information which user can store anywhere he want, and when he wants to log back in, he just provides that string to session manager and lib restarts the session.

I believe there are other ways to tackle this as well, it's generally a good idea to let user decide where he wants to store his data.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.