Переглянути джерело

Propagate floodwait error properly in requests.
Add optional sender param to .invoke

painor 3 роки тому
батько
коміт
0225d5aaa8

+ 13 - 10
README.md

@@ -4,11 +4,12 @@ A Telegram client written in JavaScript for Node.js and browsers, with its core
 [Telethon](https://github.com/LonamiWebs/Telethon).
 
 ## How to get started
-Here you'll learn how to obtain necessary information to create telegram application, authorize into your account and send yourself a message. 
 
->**Note** that if you want to use a GramJS inside of a browser, refer to [this instructions](https://gram.js.org/introduction/advanced-installation). 
- 
-Install GramJS: 
+Here you'll learn how to obtain necessary information to create telegram application, authorize into your account and send yourself a message.
+
+> **Note** that if you want to use a GramJS inside of a browser, refer to [this instructions](https://gram.js.org/introduction/advanced-installation).
+
+Install GramJS:
 
 ```bash
 $ npm i telegram -D
@@ -21,13 +22,14 @@ $ npm i input -D
 ```
 
 After installation, you'll need to obtain an API ID and hash:
+
 1. Login into your [telegram account](https://my.telegram.org/)
 2. Then click "API development tools" and fill your application details (only app title and short name required)
 3. Finally, click "Create application"
 
 > **Never** share any API/authorization details, that will compromise your application and account.
 
-When you've successfully created the application, change `apiId` and `apiHash` on what you got from telegram. 
+When you've successfully created the application, change `apiId` and `apiHash` on what you got from telegram.
 
 Then run this code to send a message to yourself.
 
@@ -55,17 +57,17 @@ const stringSession = new StringSession(""); // fill this later with the value f
   console.log("You should now be connected.");
   console.log(client.session.save()); // Save this string to avoid logging in again
   await client.sendMessage("me", { message: "Hello!" });
-})(); 
+})();
 ```
+
 > **Note** that you can also save auth key to a folder instead of a string, change `stringSession` into this:
+>
 > ```javascript
 > const storeSession = new StoreSession("folder_name");
 > ```
 
 Be sure to save output of `client.session.save()` into `stringSession` or `storeSession` variable to avoid logging in again.
 
-
-
 ## Running GramJS inside browsers
 
 GramJS works great in combination with frontend libraries such as React, Vue and others.
@@ -79,11 +81,12 @@ NODE_ENV=production npx webpack
 ```
 
 ## Calling the raw API
+
 To use raw telegram API methods use [invoke function](https://gram.js.org/beta/classes/TelegramClient.html#invoke).
 
 ```javascript
-await client.invoke(new RequestClass(args))
-``` 
+await client.invoke(new RequestClass(args));
+```
 
 ## Documentation
 

+ 6 - 2
gramjs/client/TelegramClient.ts

@@ -1158,6 +1158,7 @@ export class TelegramClient extends TelegramBaseClient {
      * Generally this should only be used when there isn't a friendly method that does what you need.<br/>
      * All available requests and types are found under the `Api.` namespace.
      * @param request - The request to send. this should be of type request.
+     * @param sender - Optional sender to use to send the requests. defaults to main sender.
      * @return The response from Telegram.
      * @example
      * ```ts
@@ -1169,8 +1170,11 @@ export class TelegramClient extends TelegramBaseClient {
      *
      * ```
      */
-    invoke<R extends Api.AnyRequest>(request: R): Promise<R["__response"]> {
-        return userMethods.invoke(this, request);
+    invoke<R extends Api.AnyRequest>(
+        request: R,
+        sender?: MTProtoSender
+    ): Promise<R["__response"]> {
+        return userMethods.invoke(this, request, sender);
     }
 
     /**

+ 1 - 4
gramjs/client/telegramBaseClient.ts

@@ -137,10 +137,7 @@ const clientParamsDefault = {
     langCode: "en",
     systemLangCode: "en",
     _securityChecks: true,
-    useWSS:
-        isBrowser
-            ? window.location.protocol == "https:"
-            : false,
+    useWSS: isBrowser ? window.location.protocol == "https:" : false,
 };
 
 export abstract class TelegramBaseClient {

+ 12 - 8
gramjs/client/users.ts

@@ -12,6 +12,7 @@ import { errors, utils } from "../";
 import type { TelegramClient } from "../";
 import bigInt from "big-integer";
 import { LogLevel } from "../extensions/Logger";
+import { MTProtoSender } from "../network";
 
 // UserMethods {
 // region Invoking Telegram request
@@ -19,22 +20,27 @@ import { LogLevel } from "../extensions/Logger";
 /** @hidden */
 export async function invoke<R extends Api.AnyRequest>(
     client: TelegramClient,
-    request: R
+    request: R,
+    sender?: MTProtoSender
 ): Promise<R["__response"]> {
     if (request.classType !== "request") {
         throw new Error("You can only invoke MTProtoRequests");
     }
-    if (client._sender == undefined) {
+    if (!sender) {
+        sender = client._sender;
+    }
+    if (sender == undefined) {
         throw new Error(
             "Cannot send requests while disconnected. You need to call .connect()"
         );
     }
+
     await request.resolve(client, utils);
     client._lastRequest = new Date().getTime();
     let attempt: number;
     for (attempt = 0; attempt < client._requestRetries; attempt++) {
         try {
-            const promise = client._sender.send(request);
+            const promise = sender.send(request);
             const result = await promise;
             client.session.processEntities(result);
             client._entityCache.add(result);
@@ -277,11 +283,9 @@ export async function getInputEntity(
         // eslint-disable-next-line no-empty
     } catch (e) {}
     // Only network left to try
-    try {
-        if (typeof peer === "string") {
-            return utils.getInputPeer(await _getEntityFromString(client, peer));
-        }
-    } catch (e) {}
+    if (typeof peer === "string") {
+        return utils.getInputPeer(await _getEntityFromString(client, peer));
+    }
 
     // If we're a bot and the user has messaged us privately users.getUsers
     // will work with accessHash = 0. Similar for channels.getChannels.

+ 2 - 2
package-lock.json

@@ -1,12 +1,12 @@
 {
   "name": "telegram",
-  "version": "2.5.1",
+  "version": "2.5.2",
   "lockfileVersion": 2,
   "requires": true,
   "packages": {
     "": {
       "name": "telegram",
-      "version": "2.5.1",
+      "version": "2.5.2",
       "license": "MIT",
       "dependencies": {
         "@cryptography/aes": "^0.1.1",

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
   "name": "telegram",
-  "version": "2.5.1",
+  "version": "2.5.2",
   "description": "NodeJS/Browser MTProto API Telegram client library,",
   "main": "index.js",
   "types": "index.d.ts",

+ 1 - 1
type_doc.js

@@ -2,5 +2,5 @@ module.exports = {
   sort: ["source-order"],
   excludeExternals: true,
   excludePrivate: true,
-  internalNamespace: "custom"
+  internalNamespace: "custom",
 };