Code Monkey home page Code Monkey logo

telegram-mtproto's Introduction

‼️ Better use @mtproto/core

telegram-mtproto

npm version

Telegram Mobile Protocol (MTProto) library in es6

About MTProto..

MTProto is the Telegram Messenger protocol "designed for access to a server API from applications running on mobile devices".

The Mobile Protocol is subdivided into three components (from the official site):

  • High-level component (API query language): defines the method whereby API queries and responses are converted to binary messages.

  • Cryptographic (authorization) layer: defines the method by which messages are encrypted prior to being transmitted through the transport protocol.

  • Transport component: defines the method for the client and the server to transmit messages over some other existing network protocol (such as, http, https, tcp, udp).

telegram-mtproto in short..

No more additional libs. The telegram-mtproto library implements the Mobile Protocol and provides all features for work with telegram protocol:

  • A high level api for server connection

  • Promise-based API

  • HTTP connections implemented in the transport layer

  • Web worker support for blazing fast crypto math works in background

  • A cipher implementation for AES and RSA encryption in the security layer

  • Both plain-text and encrypted message to communicate data with the server

  • Diffie-Hellman key exchange supported by the prime factorization function implemented in the security layer

  • MTProto TL-Schema compilation as javascript classes and functions

  • Custom async storage support for saving user data between sessions

Installation

$ npm install --save telegram-mtproto@beta

Usage

import MTProto from 'telegram-mtproto'

const phone = {
  num : '+9996620001',
  code: '22222'
}

const api = {
  layer          : 57,
  initConnection : 0x69796de9,
  api_id         : 49631
}

const server = {
  dev: true //We will connect to the test server.
}           //Any empty configurations fields can just not be specified

const client = MTProto({ server, api })

async function connect(){
  const { phone_code_hash } = await client('auth.sendCode', {
    phone_number  : phone.num,
    current_number: false,
    api_id        : 49631,
    api_hash      : 'fb050b8f6771e15bfda5df2409931569'
  })
  const { user } = await client('auth.signIn', {
    phone_number   : phone.num,
    phone_code_hash: phone_code_hash,
    phone_code     : phone.code
  })

  console.log('signed as ', user)
}

connect()

Above we used two functions from the API.

type auth.sendCode = (phone_number: string, sms_type: int,
  api_id: int, api_hash: string, lang_code: string) => {
    phone_registered: boolean,
    phone_code_hash: string,
    send_call_timeout: int,
    is_password: boolean
  }

type auth.signIn = (phone_number: string, phone_code_hash: string, phone_code: string) => {
  expires: int,
  user: User
}

More about them, as well as about many other methods, you can read in the official documentation.

Additional examples can be obtained from examples folder.

Storage

You can use your own storages like localForage for saving data. Module accepts the following interface

interface AsyncStorage {
  get(key: string): Promise<any>;
  set(key: string, value: any): Promise<void>;
  remove(...keys: string[]): Promise<void>;
  clear(): Promise<void>;
}
import { MTProto } from 'telegram-mtproto'
import { api } from './config'
import CustomStorage from './storage'

const client = MTProto({
  api,
  app: {
    storage: CustomStorage
  }
})

License

The project is released under the Mit License

telegram-mtproto's People

Contributors

andreasgassmann avatar dimapaloskin avatar goodmind avatar koloboid avatar leonerd avatar nexoscp avatar piterden avatar vetm avatar vodnicearv avatar zerobias 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telegram-mtproto's Issues

Incoming "updates" messages stop after first outbound API call

I have some proof-of-concept client code which is able to send or receive messages from Telegram. When I start it up, it performs the updates.getState call which enables the receipt of "updates" messages, and my client processes those to handle incoming messages. But the first time I make an outbound API call, perhaps to send a message, the incoming updates stop working.

Tested with both the current stable build + my one-line "emit" patch (cf17f2b) and with the upstream "development" branch as installed by npm install [email protected].

Requests debounce

Requests frequency should not exceed a certain threshold, even user do its all parallel.
E.g glitchy long polls flood wouldn't threat error at all. #31

Possible needs to make priority queue

MT[401] AUTH_KEY_EMPTY

I was testing telegram-mtproto with a script derived from example.
Node.JS version 7.7.3
Library version telegram-mtproto@beta latest

index.js

'use strict';

const MTProto = require('telegram-mtproto').MTProto
const repl = require('repl');

const api = {
    invokeWithLayer: 0xda9b0d0d,
    layer: 62,
    initConnection: 0x69796de9,
    api_id: 24275
}

const server = {
    dev: false
}

const schema = require('./tlscheme/api-62.json')

global.client = MTProto({server, api, schema, app: {}})

/*    client('auth.importBotAuthorization', {
        api_id:[scrubbed],
        api_hash:'[scrubbed]',
        bot_auth_token:'[scrubbed]:[scrubbed]'
    })
    .then((auth) => {
        //global.auth = auth
        console.log(auth)
    })
*/

client('auth.sendCode', {
        api_id:[scrubbed],
        api_hash:'[scrubbed]',
        phone_number: '[scrubbed]',
        current_number: false
    })
    .then((phone_code_hash) => {
        //global.auth = auth
        console.log(phone_code_hash)
    })
repl.start('MTProto> ')

Error Log

brainbush@brainbush-linode:~/wfjsw/telegram-mtproto-test$ DEBUG=* node index
MTProto> [0.430] mtpAuth
[0.432] Send req_pq 2340af17ba0f16a2c23e2c054059d3a9
  follow-redirects options { maxRedirects: 21,
  protocol: 'http:',
  hostname: '149.154.167.51',
  port: null,
  path: '/apiw1',
  method: 'post',
  headers: { 'User-Agent': 'axios/0.15.3', 'Content-Length': 40 },
  agent: undefined,
  auth: undefined } +0ms
  telegram-mtproto:tl:types [int] auth_key_id:long[low] 0 0 +562ms
  telegram-mtproto:tl:types [int] auth_key_id:long[high] 0 0 +3ms
  telegram-mtproto:tl:types [int] msg_id:long[low] e4ecf001 3840733185 +1ms
  telegram-mtproto:tl:types [int] msg_id:long[high] 58cd5ec2 1489854146 +0ms
  telegram-mtproto:tl:types [int] msg_len:int 40 64 +0ms
  telegram-mtproto:tl:types [int] ResPQ[id] 5162463 85337187 +1ms
  telegram-mtproto:tl:types [int] ResPQ[resPQ][server_public_key_fingerprints][id] 1cb5c415 481674261 +4ms
  telegram-mtproto:tl:types [int] ResPQ[resPQ][server_public_key_fingerprints][count] 1 1 +0ms
  telegram-mtproto:tl:types [int] ResPQ[resPQ][server_public_key_fingerprints][0]:long[low] 6ce86b21 1827171105 +1ms
  telegram-mtproto:tl:types [int] ResPQ[resPQ][server_public_key_fingerprints][0]:long[high] c3b42b02 3283364610 +0ms
[1.024] Got ResPQ 10e04bd1438bb49eadda4ba41d80483c 1b27c1d042a62881 [ '14101943622620965665' ]
[1.026] PQ factorization start Uint8Array [ 27, 39, 193, 208, 66, 166, 40, 129 ]
[3.561] PQ factorization done 62952
[3.589] Send req_DH_params
  follow-redirects options { maxRedirects: 21,
  protocol: 'http:',
  hostname: '149.154.167.51',
  port: null,
  path: '/apiw1',
  method: 'post',
  headers: { 'User-Agent': 'axios/0.15.3', 'Content-Length': 340 },
  agent: undefined,
  auth: undefined } +3s
  telegram-mtproto:tl [int bytes]  [1.021]  2340af17ba0f16a2c23e2c054059d3a9 ResPQ[resPQ][nonce]:int128 +9ms
  telegram-mtproto:tl [int bytes]  [1.023]  10e04bd1438bb49eadda4ba41d80483c ResPQ[resPQ][server_nonce]:int128 +1ms
  telegram-mtproto:tl [bytes]  [1.023]  1b27c1d042a62881 ResPQ[resPQ][pq]:bytes +0ms
  telegram-mtproto:tl:types [int] auth_key_id:long[low] 0 0 +535ms
  telegram-mtproto:tl:types [int] auth_key_id:long[high] 0 0 +3ms
  telegram-mtproto:tl:types [int] msg_id:long[low] 8189801 135829505 +1ms
  telegram-mtproto:tl:types [int] msg_id:long[high] 58cd5ec6 1489854150 +0ms
  telegram-mtproto:tl:types [int] msg_len:int 278 632 +0ms
  telegram-mtproto:tl:types [int] RESPONSE[id] d0e8075c 3504867164 +1ms
  telegram-mtproto:tl:types [int] Server_DH_inner_data[id] b5890dba 3045658042 +16ms
  telegram-mtproto:tl:types [int] Server_DH_inner_data[server_DH_inner_data][g]:int 3 3 +14ms
  telegram-mtproto:tl:types [int] Server_DH_inner_data[server_DH_inner_data][server_time]:int 58cd5ec6 1489854150 +9ms
[4.181] Done decrypting answer
[4.182] Verifying DH params
[4.182] dhPrime cmp OK
[4.191] 2^{2048-64} < gA < dhPrime-2^{2048-64} OK
[4.193] Apply server time 1489854150 1489854250632 -100 true
[4.821] Send set_client_DH_params
  follow-redirects options { maxRedirects: 21,
  protocol: 'http:',
  hostname: '149.154.167.51',
  port: null,
  path: '/apiw1',
  method: 'post',
  headers: { 'User-Agent': 'axios/0.15.3', 'Content-Length': 396 },
  agent: undefined,
  auth: undefined } +643ms
  telegram-mtproto:tl [int bytes]  [4.140]  2340af17ba0f16a2c23e2c054059d3a9 RESPONSE[server_DH_params_ok][nonce]:int128 +2ms
  telegram-mtproto:tl [int bytes]  [4.141]  10e04bd1438bb49eadda4ba41d80483c RESPONSE[server_DH_params_ok][server_nonce]:int128 +0ms
  telegram-mtproto:tl [bytes]  [4.142]  891a9882ad4f06311ebaad3b467ac1ed0c338bab7d88e6c1b3 RESPONSE[server_DH_params_ok][encrypted_answer]:by +1ms
  telegram-mtproto:tl [int bytes]  [4.158]  2340af17ba0f16a2c23e2c054059d3a9 Server_DH_inner_data[server_DH_inner_data][nonce]: +0ms
  telegram-mtproto:tl [int bytes]  [4.159]  10e04bd1438bb49eadda4ba41d80483c Server_DH_inner_data[server_DH_inner_data][server_ +0ms
  telegram-mtproto:tl [bytes]  [4.171]  c71caeb9c6b1c9048e6c522f70f13f73980d40238e3e21c149 Server_DH_inner_data[server_DH_inner_data][dh_prim +1ms
  telegram-mtproto:tl [bytes]  [4.172]  7b7d3b8ab9cf40815f38a13026b2049a22cfca64f57a790a99 Server_DH_inner_data[server_DH_inner_data][g_a]:by +0ms
  telegram-mtproto:tl:types [int] auth_key_id:long[low] 0 0 +732ms
  telegram-mtproto:tl:types [int] auth_key_id:long[high] 0 0 +0ms
  telegram-mtproto:tl:types [int] msg_id:long[low] 73062401 1929782273 +0ms
  telegram-mtproto:tl:types [int] msg_id:long[high] 58cd5ec7 1489854151 +0ms
  telegram-mtproto:tl:types [int] msg_len:int 34 52 +0ms
  telegram-mtproto:tl:types [int] Set_client_DH_params_answer[id] 3bcbf734 1003222836 +1ms
[6.007] Got Set_client_DH_params_answer dh_gen_ok
  follow-redirects options { maxRedirects: 21,
  protocol: 'http:',
  hostname: '149.154.167.51',
  port: null,
  path: '/apiw1',
  method: 'post',
  headers: { 'User-Agent': 'axios/0.15.3', 'Content-Length': 184 },
  agent: undefined,
  auth: undefined } +464ms
  telegram-mtproto:tl [int bytes]  [5.559]  2340af17ba0f16a2c23e2c054059d3a9 Set_client_DH_params_answer[dh_gen_ok][nonce]:int1 +2ms
  telegram-mtproto:tl [int bytes]  [5.559]  10e04bd1438bb49eadda4ba41d80483c Set_client_DH_params_answer[dh_gen_ok][server_nonc +1ms
  telegram-mtproto:tl [int bytes]  [5.560]  f96b408acd831f0527852a241c1c07cf Set_client_DH_params_answer[dh_gen_ok][new_nonce_h +0ms
  telegram-mtproto:networker [Api call]  [6.018]  help.getNearestDc {} 6398874859608284188 1 { dcID: 2,
  createNetworker: true,
  resultType: 'NearestDc',
  messageID: '6398874859608284188' } +192ms
  telegram-mtproto:networker [Container]  [6.020]  6398874859608284188,6398874859614735564 6398874859614851332 4 +2ms
  telegram-mtproto:tl:types [int] message_id:long[low] 9c998001 2627305473 +510ms
  telegram-mtproto:tl:types [int] message_id:long[high] 58cd5ec8 1489854152 +0ms
  telegram-mtproto:tl:types [int] seq_no:int 4 4 +0ms
  telegram-mtproto:tl:types [int] message_data[length]:int 60 96 +1ms
  telegram-mtproto:tl:types [int] INPUT[id] 73f1f8dc 1945237724 +2ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][count] 2 2 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][msg_id]:long[low] 74ed1401 1961694209 +1ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][msg_id]:long[high] 58cd5ec8 1489854152 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][seqno]:int 1 1 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][bytes]:int 1c 28 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][id] 9ec20908 2663516424 +1ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][new_session_created][first_msg_id]:long[low] 39211c1c 958471196 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][new_session_created][first_msg_id]:long[high] 58cd5ec8 1489854152 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][new_session_created][unique_id]:long[low] 7c99f3ab 2090464171 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][new_session_created][unique_id]:long[high] be2f31a8 3190763944 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][new_session_created][server_salt]:long[low] 6c21dafe 1814158078 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][0][message][body][new_session_created][server_salt]:long[high] cc4d2b6f 3427609455 +1ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][msg_id]:long[low] 75ef9801 1978636289 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][msg_id]:long[high] 58cd5ec8 1489854152 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][seqno]:int 3 3 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][bytes]:int 1c 28 +1ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][body][id] f35c6d01 4082920705 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][body][rpc_result][req_msg_id]:long[low] 39211c1c 958471196 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][body][rpc_result][req_msg_id]:long[high] 58cd5ec8 1489854152 +0ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][body][rpc_result][result][id] 8e1a1775 2384074613 +1ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][body][rpc_result][result][nearestDc][this_dc]:int 2 2 +1ms
  telegram-mtproto:tl:types [int] INPUT[msg_container][messages][1][message][body][rpc_result][result][nearestDc][nearest_dc]:int 5 5 +0ms
Unhandled rejection Error: MT[401] AUTH_KEY_EMPTY:
    at ApiManager._ref2 (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/telegram-mtproto/lib/service/api-manager/index.js:129:43)
    at _ref2.next (<anonymous>)
    at step (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/telegram-mtproto/lib/service/api-manager/index.js:70:202)
    at /home/brainbush/wfjsw/telegram-mtproto-test/node_modules/telegram-mtproto/lib/service/api-manager/index.js:70:383
    at tryCatcher (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromiseCtx (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/promise.js:606:10)
    at Async._drainQueue (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/async.js:138:12)
    at Async._drainQueues (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (/home/brainbush/wfjsw/telegram-mtproto-test/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)

Both auth.importBotAuthorization and auth.sendCode were tested but got the same error.
L57 and L62 got the same error.
Test script located in this repo works fine.

More docs required - storage key names / types

The toplevel README makes a brief mention of the AsyncStorage API that can be used to persist values. However, it doesn't go into any detail about, for example, what key names are used by the library and what types their values are expected to be.

By observation of my local copy, I have determined at least the following key names:

TODO: storage gets dc
TODO: storage gets dc2_auth_key
TODO: storage gets dc2_server_salt

I can likely guess that there may be other key names relating to other DC numbers also. But what else?

Additionally I suspect there is a bug in the documentation of the set method, which is currently documented as:

set(obj: any): Promise;

However, in my observation the method is invoked with two values - a string key, and an associated value; for example:

TODO: storage sets dc2_server_salt to c5cc98f309474772

I expect the docs should have said

set(key: string, obj: any): Promise<void>;

contacts.importContacts

i'm using version 2.2.8 and i get this error when i try to import contacts:
[8.557] Error undefined undefined 2 4
any help?

Saving sessions with RethinkDB in pure JS

How can I save session in node to use it in future? I use RethinkDB. I don't find how to do it in example code. I think it saves it in cookie, but not sure.

I use pure JS (not TS, Babel, etc) so I can't use Interface like it's shown in readme.

Parralel api calls don't work?

tell me what am I doing wrong?

 //old api level, but works
client.callApi('messages.getDialogs', {offset: 0, max_id: 0, limit: 0}).then(result => {
	let chats = result.chats.list;
	if (false) { // fine code, but didn't work :( (endless waiting)
		return Promise.all(result.chats.list.map((elem) => {
			return client.callApi('messages.getFullChat', {chat_id: elem.id});
		}));
	} else { // ugly working code
		return chats.reduce((promise, elem) => {
			return promise.then((resArray) => {
				return client.callApi('messages.getFullChat', {chat_id: elem.id}).then((res) => {
					resArray.push(res);
					return Promise.resolve(resArray);
				});
			});
		}, Promise.resolve([]));
	}).then(results => {...})

More docs required - how to create API value objects

When making API calls, it seems that simple types like integers and strings can be passed as native javascript types. It doesn't seem clear how to pass other types, for example, a value whose MTProto type name is InputChannel, as the parameter for channels.getFullChannel.

My previous code, based on telegram.link worked by

client.channels.getFullChannel(new TelegramLink.type.InputChannel({props: {
  channel_id: id,
  access_hash: hash,
}});

Using your telegram-mtproto the API call is made a different way, but I'm not sure how to construct the value required:

client("channels.getFullChannel", {channel: BANANA})

What code do I write in BANANA above, given my channel ID and access hash values?

populate properties in api results with default values

when api returned object with default values (empty string, zero etc) in properties, objects, returned with callApi hasn't this properties. This make results unusable in next calls without additional manipulations.
for example client.callApi('auth.signIn', args) has result.user (for me):

   anonymous {
     _writeBuffers: null,
....
     mutual_contact: true,
     id: 8....8,
     access_hash: '0xf....f',
     first_name: 'Anton',
// here must be last_name and username, see https://core.telegram.org/constructor/userSelf
     phone: '7...9',
     photo: ...
...

initial project (https://github.com/goodmind/telegram-mt-node) has this properties populated.

running codes

a simple question,

how can we run es6 codes of this project, should we use babel or something like that?
do you have any example of running!

Nearly impossible usage of types with optional parameters

Flags fields demands to be preprocessed before type will created

The user should be able to leave optional parameters unspecified

#24 (comment)

messages.sendMessage with complicated type

messages.sentMessage#d1f4d35c id:int date:int pts:int seq:int = messages.SentMessage;
messages.sentMessageLink#e9db4a3f id:int date:int pts:int seq:int links:Vector<contacts.Link> = messages.SentMessage;
---functions---
messages.sendMessage#4cde0aab peer:InputPeer message:string random_id:long = messages.SentMessage;

should allow to be invoked this way

client('messages.sendMessage',{ 
    peer: {'_': 'inputPeerChat', chat_id:80247363},
    message: 'Hello msg from lib'}
)

Handling of `FILE_MIGRATE_x` errors

Since telegram-mtproto attempts to transparently handle the PHONE_MIGRATE_x class of errors when calling auth.sendCode, it would be consistent for it to also handle the FILE_MIGRATE_x class of errors as occurs when you attempt to uploads.getFile on a location indicating a different dc_id from the one you're currently connected to.

Currently these are passed up to the caller, looking like:

Unhandled rejection (<{"code":303,"type":"FILE_MIGRATE_2","d...>, no stack trace)

Given as additionally, the uploads.getFile call is exempt from the usual updates-directing logic in the servers as most other API calls are, it should be possible to handle this by transparently creating new connections without further disturbing the updates mechanism, as currently alluded to by #53

More docs required - handling incoming updates

I'm currently attempting to make use of incoming "updates" messages from telegram, and finding no examples for this.

Specifically, nothing in the toplevel readme, nor any of the files under the examples/ dir, show anything about, for example, how to react to an incoming UpdateShortChatMessage which contains a newly-received message in a chat.

By sourcediving, I do see that the toplevel MTProto appears to have a pair of on+emit methods, assigned by the constructor in lib/service/main/index.js itself but this exercise in reading the source hasn't so far lead me to discover what event names might be emitted, that I could register an interest in, nor what the shape of arguments they'd provide.

For reference, this is part of a code rewrite on matrix-appservice-tg to swap from using telegram.link to telegram-mtproto; the part of code currently in question starts with the call to client.registerOnUpdates at

https://github.com/matrix-org/matrix-appservice-tg/blob/master/lib/TelegramGhost.js#L81

App API ID is invalid

Hi all,

I have create an app in https://my.telegram.org/apps, I have given, App Title, Short name, URL, Platform as Desktop and description.

I have got api_id, api_hash etc, When i am trying to implement in code, i am getting API_ID_INVALID, I have tried with different API_ID but same result. Searched hard no luck.

api_id_error

Any help highly appreciated.
Thanks in advance.

Saving sessions with MongoDB

I'm trying to save sessions (for many users) in mongoDB, but the problem is keys generated by this library are not uniq,
this is my code and a db saved data example :

import db from 'db';

class AsyncStorage {

  async get(key) {
    let data = await db.sessions.findOne({
      key
    });

    if (data && data.value) {
      return data.value;
    }

    return null;
  };

  async set(key, value) {
    let session = {
      key,
      value
    };

    let pro = await new db.sessions(session).save();

    return pro;
  };
  async remove(keys) {
    let pro = await db.sessions.remove({
      key: {
        $in: keys
      }
    });

    return pro;
  };

  async clear() {
    let pro = await db.sessions.drop();

    return pro;
  };
}

module.exports = AsyncStorage;

Sample DB data :

/* 1 */
{
    "_id" : ObjectId("595dbc058724342c57b34de5"),
    "key" : "dc2_auth_key",
    "value" : "something",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("595dbc058724342c57b34de6"),
    "key" : "dc2_server_salt",
    "value" : "something",
    "__v" : 0
}

/* 3 */
{
    "_id" : ObjectId("595dbc078724342c57b34de7"),
    "key" : "dc2_server_salt",
    "value" : "something",
    "__v" : 0
}

/* 4 */
{
    "_id" : ObjectId("595dbc078724342c57b34de8"),
    "key" : "nearest_dc",
    "value" : 2,
    "__v" : 0
}

/* 5 */
{
    "_id" : ObjectId("595dbc078724342c57b34de9"),
    "key" : "dc",
    "value" : 2,
    "__v" : 0
}

if another user need to use his session to work with API, How can I implement it?

Cannot read property 'length' of undefined at NetMessage.size

Just saw this in log:

REQUEST
REQUEST
Unhandled rejection TypeError: Cannot read property 'length' of undefined
    at NetMessage.size (/home/telegramas/matrix-appservice-tg/node_modules/telegram-mtproto/lib/service/networker/net-message.js:60:91)
    at NetworkerThread.performSheduledRequest (/home/telegramas/matrix-appservice-tg/node_modules/telegram-mtproto/lib/service/networker/index.js:226:41)
    at _bluebird2.default.resolve.then (/home/telegramas/matrix-appservice-tg/node_modules/mtproto-shared/lib/timeout.js:40:96)
    at tryCatcher (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromiseCtx (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/promise.js:606:10)
    at Async._drainQueue (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/async.js:138:12)
    at Async._drainQueues (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/home/telegramas/matrix-appservice-tg/node_modules/bluebird/js/release/async.js:17:14)
    at tryOnImmediate (timers.js:543:15)
    at processImmediate [as _immediateCallback] (timers.js:523:5)

(Running version 3.0.6)

While auth.sendCode error on channel not found and channel.callMEthod

When i am trying to sendCode::
i am getting following error to add channel, i am create a channel and created a channel url to

client.setChannel(channel)

but i am getting error.

Uncaught (in promise) TypeError: channel.callMethod is not a function
    at TelegramClient.callApi 
  at connection.connect.then.then

Any suggestion should channel need to be added? mandatory?
and why is used for?

Thanks in advance.

How to add bot to the chat and/or start bot with api?

bot = {user_id: 120593101, access_hash: ''};
peerSelf = new telegram.schema.type.InputPeerSelf();
userBot = new telegram.schema.type.InputUser({props: bot});
	return client.callApi('messages.startBot', {bot: userBot, peer: peerSelf, random_id:123456, start_param:'start'});

returns error "error_code": 400, "error_message": "BOT_INVALID"
I tried peer self, or peer with existing chat - no difference

when i try to add bot to existing chat:
return client.callApi('messages.addChatUser', {chat_id: chat, user_id: userBot, fwd_limit:1});
it returns "error_message": "USER_ID_INVALID"

id is bot_id from contacts.search '@chgk_bot' (I also try some other bots, with same result)

Options to disable nearest DC detection & force dc_id

According to https://t.me/MadelineProto/21

#UndocumentedAPIChangeOfTheDay 
Bots can't execute the help.getNearestDC method with layer 66 anymore, which kinda makes sense since most bot accounts are used from the same datacenter, but then again, a changelog would've been nice.

There is a high possibility that the lib breaks in this change, therefore better error_handling or an option should be implemented.

Remove jsbn

jsbn library is really slow, and it should be replaced with included leemon library everywhere where it is possible.

[mtproto2] Directory structure

It would be great to keep "standard" directory structure for packages.

It means:

  • /source => /src
  • /source/smart-timeout => /src/utils/smart-timeout
  • /dist => /lib
  • /source/leemon.js => /src/vendor/leemon.js

etc

Error 401 AUTH_KEY_EMPTY trying to `auth.sendCode` on some phone numbers

Same server/code/etc... that works on some phone numbers (e.g. "+4477xxxxx") fails to work with others (e.g. "+131...")

[3.998] Error 401 AUTH_KEY_EMPTY 2 2
Failed: Error: MT[401] AUTH_KEY_EMPTY: 
Command failed: Error: MT[401] AUTH_KEY_EMPTY: 
Error: MT[401] AUTH_KEY_EMPTY: 
    at MTError (/home/telegramas/matrix-appservice-tg/node_modules/telegram-mtproto/lib/error.js:13:5)
    at AuthKeyError (/home/telegramas/matrix-appservice-tg/node_modules/telegram-mtproto/lib/error.js:61:5)
    at ApiManager._ref2 (/home/telegramas/matrix-appservice-tg/node_modules/telegram-mtproto/lib/service/api-manager/index.js:130:43)
    at next (native)
    ...

This is still with code that forces

{ dcID: 2 }

on the auth.sendCode call. Without forcing dcID, the code still prints an error message

[8.990] Error 401 AUTH_KEY_EMPTY 2 4
[9.208] Error 401 AUTH_KEY_UNREGISTERED 2 4

but the returned promise never completes, just spins away into the void...

mtproto2-browser.js use

I use mtproto2-browser.js

You can example how you can initiate the client and send any request

PHONE_NUMBER_UNOCCUPIED.

i try to sign after i receive the phone_hash_code that i got from sendCode method
but why it is returning error 400 PHONE_NUMBER_UNOCCUPIED.
any idea?

More docs required - handling 2FA

I've so far been unable to work out how to handle the SESSION_PASSWORD_NEEDED case for 2FA.

Right now, my code is printing

[14.279] Error 401 SESSION_PASSWORD_NEEDED 2 4

but no promises ever seem to get fulfilled or rejected; it's just sitting indefinitely.

From knowing the Telegram API, I know that I have to call account.getPassword then perform the SHA256 operation on the salt + password, before sending that into auth.checkPassword. I just don't see the bits in telegram-mtproto to let me do that.

Actual version of package in npm

Hi, can you publish last stable version of this package on npm?
I have some troubles with old version (1.0.5) and i see v2 without large issues.

Can't get photos not from my datacenter

I try to get avatar (upload.getFile) from dc4 and dc3, but I can't:

{ code: 303,
  type: 'FILE_MIGRATE_4',
  description: 'CODE#303 FILE_MIGRATE_4',
  originalError: 
   { _: 'rpc_error',
     error_code: 303,
     error_message: 'FILE_MIGRATE_4' } }

I think lib has hardcoded my data center (dc2) and by default ignore custom dc_id.

RangeError: Wrong length! Error. or Error: 400 PHONE_CODE_EXPIRED CODE#400 PHONE_CODE_EXPIRED

here is sample
when i receive activation code and use it to sign in telegram by below sample code get this error.
RangeError: Wrong length!
use babel for transcompile to es5.
code :

const login = async () => {
  try {

    const phone = '+98........................'

    const info = JSON.parse(fs.readFileSync('code.json'));
    const code = info.phoneCode;
    const phone_code_hash = info.phone_code_hash;

    const res = await telegram('auth.signIn', {
      phone_number: phone,
      phone_code_hash,
      phone_code: code
    })

    const { user } = res
    const {
      first_name = '',
      username = ''
    } = user

    console.log('signIn', first_name, username, user.phone)
    return first_name
  } catch (error) {
    console.error(error)
  }
}

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): RangeError: Wrong length!

Duplication / flooding of ping messages

I use you lib as layer for hybrid bot that use Bot API and TG API simultaneously (because of lib has not update manager). But after some hours (4-5) I got many error like NETWORK_BAD_REQUEST, Unhandled rejection undefined etc. Is it okay or it's normal for beta state?

Encrypted request failed { Error: MT[406] NETWORK_BAD_REQUEST: http://149.154.167.51/apiw1
    at MTError (\node_modules\telegram-mtproto\lib\error.js:13:5)
    at ErrorBadRequest (\node_modules\telegram-mtproto\lib\error.js:30:5)
    at NetworkerThread._ref20 (\node_modules\telegram-mtproto\lib\service\networker\index.js:1050:40)
    at throw (native)
    at step (\node_modules\telegram-mtproto\lib\service\networker\index.js:62:202)
    at \node_modules\telegram-mtproto\lib\service\networker\index.js:62:424
    at tryCatcher (\node_modules\bluebird\js\release\util.js:16:23)
    at Promise._settlePromiseFromHandler (\node_modules\bluebird\js\release\promise.js:512:31)
    at Promise._settlePromise (\node_modules\bluebird\js\release\promise.js:569:18)
    at Promise._settlePromise0 (\node_modules\bluebird\js\release\promise.js:614:10)
    at Promise._settlePromises (\node_modules\bluebird\js\release\promise.js:689:18)
    at Async._drainQueue (\node_modules\bluebird\js\release\async.js:133:16)
    at Async._drainQueues (\node_modules\bluebird\js\release\async.js:143:10)
    at Immediate.Async.drainQueues (\node_modules\bluebird\js\release\async.js:17:14)
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)
  code: 406,
  type: 'NETWORK_BAD_REQUEST',
  originalError: 
   { Error: Request failed with status code 429
       at createError (\node_modules\axios\lib\core\createError.js:15:15)
       at settle (\node_modules\axios\lib\core\settle.js:18:12)
       at IncomingMessage.handleStreamEnd (\node_modules\axios\lib\adapters\http.js:186:11)
       at emitNone (events.js:91:20)
       at IncomingMessage.emit (events.js:185:7)
       at endReadableNT (_stream_readable.js:974:12)
       at _combinedTickCallback (internal/process/next_tick.js:80:11)
       at process._tickDomainCallback (internal/process/next_tick.js:128:9)
     config: 
      { adapter: [Function: httpAdapter],
        transformRequest: [Object],
        transformResponse: [Object],
        timeout: 0,
        xsrfCookieName: 'XSRF-TOKEN',
        xsrfHeaderName: 'X-XSRF-TOKEN',
        maxContentLength: -1,
        validateStatus: [Function: validateStatus],
        headers: [Object],
        method: 'post',
        responseType: 'arraybuffer',
        url: 'http://149.154.167.51/apiw1',
        data: ArrayBuffer { byteLength: 904 } },
     response: 
      { status: 429,
        statusText: 'Too Many Requests',
        headers: [Object],
        config: [Object],
        request: [Object],
        data: <Buffer 3c 68 74 6d 6c 3e 0d 0a 3c 68 65 61 64 3e 3c 74 69 74 6c 65 3e 34 32 39 20 54 6f 6f 20 4d 61 6e 79 20 52 65 71 75 65 73 74 73 3c 2f 74 69 74 6c 65 3e ... > } } }

and:

. . .
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
Unhandled rejection undefined
. . .

Config validation

The library has an extensive complex configuration, so the invalid values or incorrect config settings must throw an obvious error

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.