瀏覽代碼

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

painor 3 年之前
父節點
當前提交
0225d5aaa8
共有 7 個文件被更改,包括 36 次插入28 次删除
  1. 13 10
      README.md
  2. 6 2
      gramjs/client/TelegramClient.ts
  3. 1 4
      gramjs/client/telegramBaseClient.ts
  4. 12 8
      gramjs/client/users.ts
  5. 2 2
      package-lock.json
  6. 1 1
      package.json
  7. 1 1
      type_doc.js

+ 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).
 [Telethon](https://github.com/LonamiWebs/Telethon).
 
 
 ## How to get started
 ## 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
 ```bash
 $ npm i telegram -D
 $ npm i telegram -D
@@ -21,13 +22,14 @@ $ npm i input -D
 ```
 ```
 
 
 After installation, you'll need to obtain an API ID and hash:
 After installation, you'll need to obtain an API ID and hash:
+
 1. Login into your [telegram account](https://my.telegram.org/)
 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)
 2. Then click "API development tools" and fill your application details (only app title and short name required)
 3. Finally, click "Create application"
 3. Finally, click "Create application"
 
 
 > **Never** share any API/authorization details, that will compromise your application and account.
 > **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.
 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("You should now be connected.");
   console.log(client.session.save()); // Save this string to avoid logging in again
   console.log(client.session.save()); // Save this string to avoid logging in again
   await client.sendMessage("me", { message: "Hello!" });
   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:
 > **Note** that you can also save auth key to a folder instead of a string, change `stringSession` into this:
+>
 > ```javascript
 > ```javascript
 > const storeSession = new StoreSession("folder_name");
 > 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.
 Be sure to save output of `client.session.save()` into `stringSession` or `storeSession` variable to avoid logging in again.
 
 
-
-
 ## Running GramJS inside browsers
 ## Running GramJS inside browsers
 
 
 GramJS works great in combination with frontend libraries such as React, Vue and others.
 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
 ## Calling the raw API
+
 To use raw telegram API methods use [invoke function](https://gram.js.org/beta/classes/TelegramClient.html#invoke).
 To use raw telegram API methods use [invoke function](https://gram.js.org/beta/classes/TelegramClient.html#invoke).
 
 
 ```javascript
 ```javascript
-await client.invoke(new RequestClass(args))
-``` 
+await client.invoke(new RequestClass(args));
+```
 
 
 ## Documentation
 ## 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/>
      * 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.
      * All available requests and types are found under the `Api.` namespace.
      * @param request - The request to send. this should be of type request.
      * @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.
      * @return The response from Telegram.
      * @example
      * @example
      * ```ts
      * ```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",
     langCode: "en",
     systemLangCode: "en",
     systemLangCode: "en",
     _securityChecks: true,
     _securityChecks: true,
-    useWSS:
-        isBrowser
-            ? window.location.protocol == "https:"
-            : false,
+    useWSS: isBrowser ? window.location.protocol == "https:" : false,
 };
 };
 
 
 export abstract class TelegramBaseClient {
 export abstract class TelegramBaseClient {

+ 12 - 8
gramjs/client/users.ts

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

+ 2 - 2
package-lock.json

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

+ 1 - 1
package.json

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

+ 1 - 1
type_doc.js

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