浏览代码

Add "chat" result to session cache

painor 3 年之前
父节点
当前提交
03ff441369

+ 1 - 1
README.md

@@ -31,7 +31,7 @@ you can find all the requests and types at https://gram.js.org/
 
 ## Docs
 
-you can find the docs at https://painor.gitbook.io/gramjs/ or https://gram.js.org/  which has all the functions with a usage example
+you can find the docs at https://painor.gitbook.io/gramjs/ or https://gram.js.org/ which has all the functions with a usage example
 
 ## Asking questions
 

+ 4 - 1
gramjs/Utils.ts

@@ -89,7 +89,10 @@ export function getInputPeer(
     if (entity instanceof Api.User) {
         if (entity.self && allowSelf) {
             return new Api.InputPeerSelf();
-        } else if ((entity.accessHash !== undefined && !entity.min) || !checkHash) {
+        } else if (
+            (entity.accessHash !== undefined && !entity.min) ||
+            !checkHash
+        ) {
             return new Api.InputPeerUser({
                 userId: entity.id,
                 accessHash: entity.accessHash || bigInt(0),

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.8.5";
+export const version = "1.8.6";

+ 12 - 13
gramjs/client/downloads.ts

@@ -152,12 +152,12 @@ export async function downloadFile(
                                 location: inputLocation,
                                 offset,
                                 limit,
-                                precise: isPrecise || undefined
+                                precise: isPrecise || undefined,
                             })
                         ),
                         sleep(REQUEST_TIMEOUT).then(() =>
                             Promise.reject(new Error("REQUEST_TIMEOUT"))
-                        )
+                        ),
                     ]);
 
                     if (progressCallback) {
@@ -200,8 +200,7 @@ class Foreman {
     private deferred: Deferred | undefined;
     private activeWorkers = 0;
 
-    constructor(private maxWorkers: number) {
-    }
+    constructor(private maxWorkers: number) {}
 
     requestWorker() {
         this.activeWorkers++;
@@ -231,7 +230,7 @@ function createDeferred(): Deferred {
 
     return {
         promise,
-        resolve: resolve!
+        resolve: resolve!,
     };
 }
 
@@ -328,20 +327,20 @@ export async function _downloadDocument(
             id: doc.id,
             accessHash: doc.accessHash,
             fileReference: doc.fileReference,
-            thumbSize: size ? size.type : ""
+            thumbSize: size ? size.type : "",
         }),
         {
             fileSize:
                 size && !(size instanceof Api.PhotoSizeEmpty)
                     ? size instanceof Api.PhotoSizeProgressive
-                    ? Math.max(...size.sizes)
-                    : size.size
+                        ? Math.max(...size.sizes)
+                        : size.size
                     : doc.size,
             progressCallback: args.progressCallback,
             start: args.start,
             end: args.end,
             dcId: doc.dcId,
-            workers: args.workers
+            workers: args.workers,
         }
     );
 }
@@ -424,7 +423,7 @@ export async function _downloadPhoto(
             id: photo.id,
             accessHash: photo.accessHash,
             fileReference: photo.fileReference,
-            thumbSize: size.type
+            thumbSize: size.type,
         }),
         {
             dcId: photo.dcId,
@@ -432,7 +431,7 @@ export async function _downloadPhoto(
                 size instanceof Api.PhotoSizeProgressive
                     ? Math.max(...size.sizes)
                     : size.size,
-            progressCallback: args.progressCallback
+            progressCallback: args.progressCallback,
         }
     );
 }
@@ -463,7 +462,7 @@ export async function downloadProfilePhoto(
         loc = new Api.InputPeerPhotoFileLocation({
             peer: utils.getInputPeer(entity),
             photoId: photo.photoId,
-            big: fileParams.isBig
+            big: fileParams.isBig,
         });
     } else {
         return Buffer.alloc(0);
@@ -471,6 +470,6 @@ export async function downloadProfilePhoto(
     return client.downloadFile(loc, {
         dcId,
         fileSize: 2 * 1024 * 1024,
-        workers: 1
+        workers: 1,
     });
 }

+ 0 - 1
gramjs/client/messageParse.ts

@@ -23,7 +23,6 @@ export const DEFAULT_DELIMITERS: {
     "```": Api.MessageEntityPre,
 };
 
-
 export interface ParseInterface {
     parse: (message: string) => [string, Api.TypeMessageEntity[]];
     unparse: (text: string, entities: Api.TypeMessageEntity[]) => string;

+ 1 - 1
gramjs/client/telegramBaseClient.ts

@@ -192,7 +192,7 @@ export class TelegramBaseClient {
             this._log = clientParams.baseLogger;
         }
         this._log.debug("Running gramJS version " + version);
-        if (session && typeof session=="string"){
+        if (session && typeof session == "string") {
             session = new StoreSession(session);
         }
         if (!(session instanceof Session)) {

+ 5 - 6
gramjs/client/updates.ts

@@ -36,7 +36,7 @@ export function removeEventHandler(
     callback: CallableFunction,
     event: EventBuilder
 ) {
-    client._eventBuilders = client._eventBuilders.filter(function(item) {
+    client._eventBuilders = client._eventBuilders.filter(function (item) {
         return item !== [event, callback];
     });
 }
@@ -59,7 +59,7 @@ export function _handleUpdate(
     if (typeof update === "number") {
         if ([-1, 0, 1].includes(update)) {
             _dispatchUpdate(client, {
-                update: new UpdateConnectionState(update)
+                update: new UpdateConnectionState(update),
             });
             return;
         }
@@ -98,7 +98,7 @@ export function _processUpdate(
     update._entities = entities || new Map();
     const args = {
         update: update,
-        others: others
+        others: others,
     };
 
     _dispatchUpdate(client, args);
@@ -156,7 +156,7 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
         try {
             client._sender!.send(
                 new Api.Ping({
-                    pingId: bigInt(rnd)
+                    pingId: bigInt(rnd),
                 })
             );
         } catch (e) {
@@ -174,8 +174,7 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
         ) {
             try {
                 await client.invoke(new Api.updates.GetState());
-            } catch (e) {
-            }
+            } catch (e) {}
         }
     }
 }

+ 25 - 31
gramjs/client/users.ts

@@ -151,13 +151,12 @@ export async function getEntity(
     const lists = new Map<number, any[]>([
         [_EntityType.USER, []],
         [_EntityType.CHAT, []],
-        [_EntityType.CHANNEL, []]
+        [_EntityType.CHANNEL, []],
     ]);
     for (const x of inputs) {
         try {
             lists.get(_entityType(x))!.push(x);
-        } catch (e) {
-        }
+        } catch (e) {}
     }
     let users = lists.get(_EntityType.USER)!;
     let chats = lists.get(_EntityType.CHAT)!;
@@ -166,7 +165,7 @@ export async function getEntity(
     if (users.length) {
         users = await client.invoke(
             new Api.users.GetUsers({
-                id: users
+                id: users,
             })
         );
     }
@@ -223,8 +222,7 @@ export async function getInputEntity(
     try {
         return utils.getInputPeer(peer);
         // eslint-disable-next-line no-empty
-    } catch (e) {
-    }
+    } catch (e) {}
     // Next in priority is having a peer (or its ID) cached in-memory
     try {
         // 0x2d45687 == crc32(b'Peer')
@@ -238,8 +236,7 @@ export async function getInputEntity(
             }
         }
         // eslint-disable-next-line no-empty
-    } catch (e) {
-    }
+    } catch (e) {}
     // Then come known strings that take precedence
     if (typeof peer == "string") {
         if (["me", "this", "self"].includes(peer)) {
@@ -253,8 +250,7 @@ export async function getInputEntity(
             return client.session.getInputEntity(peer);
         }
         // eslint-disable-next-line no-empty
-    } catch (e) {
-    }
+    } catch (e) {}
     // Only network left to try
     if (typeof peer === "string") {
         return utils.getInputPeer(await _getEntityFromString(client, peer));
@@ -270,9 +266,9 @@ export async function getInputEntity(
                 id: [
                     new Api.InputUser({
                         userId: peer.userId,
-                        accessHash: bigInt.zero
-                    })
-                ]
+                        accessHash: bigInt.zero,
+                    }),
+                ],
             })
         );
         if (users.length && !(users[0] instanceof Api.UserEmpty)) {
@@ -287,7 +283,7 @@ export async function getInputEntity(
         }
     } else if (peer instanceof Api.PeerChat) {
         return new Api.InputPeerChat({
-            chatId: peer.chatId
+            chatId: peer.chatId,
         });
     } else if (peer instanceof Api.PeerChannel) {
         try {
@@ -296,9 +292,9 @@ export async function getInputEntity(
                     id: [
                         new Api.InputChannel({
                             channelId: peer.channelId,
-                            accessHash: bigInt.zero
-                        })
-                    ]
+                            accessHash: bigInt.zero,
+                        }),
+                    ],
                 })
             );
 
@@ -312,8 +308,8 @@ export async function getInputEntity(
     throw new Error(
         `Could not find the input entity for ${JSON.stringify(peer)}.
          Please read https://` +
-        "docs.telethon.dev/en/latest/concepts/entities.html to" +
-        " find out more details."
+            "docs.telethon.dev/en/latest/concepts/entities.html to" +
+            " find out more details."
     );
 }
 
@@ -327,7 +323,7 @@ export async function _getEntityFromString(
         try {
             const result = await client.invoke(
                 new Api.contacts.GetContacts({
-                    hash: 0
+                    hash: 0,
                 })
             );
             if (!(result instanceof Api.contacts.ContactsNotModified)) {
@@ -341,7 +337,7 @@ export async function _getEntityFromString(
             if (e.errorMessage === "BOT_METHOD_INVALID") {
                 throw new Error(
                     "Cannot get entity by phone number as a " +
-                    "bot (try using integer IDs, not strings)"
+                        "bot (try using integer IDs, not strings)"
                 );
             }
             throw e;
@@ -353,13 +349,13 @@ export async function _getEntityFromString(
         if (isInvite) {
             const invite = await client.invoke(
                 new Api.messages.CheckChatInvite({
-                    hash: username
+                    hash: username,
                 })
             );
             if (invite instanceof Api.ChatInvite) {
                 throw new Error(
                     "Cannot get entity from a channel (or group) " +
-                    "that you are not part of. Join the group and retry"
+                        "that you are not part of. Join the group and retry"
                 );
             } else if (invite instanceof Api.ChatInviteAlready) {
                 return invite.chat;
@@ -425,7 +421,7 @@ export async function _getPeer(client: TelegramClient, peer: EntityLike) {
     return new cls({
         userId: i,
         channelId: i,
-        chatId: i
+        chatId: i,
     });
 }
 
@@ -439,13 +435,12 @@ export async function _getInputDialog(client: TelegramClient, dialog: any) {
         } else if (dialog.SUBCLASS_OF_ID == 0xc91c90b6) {
             //crc32(b'InputPeer')
             return new Api.InputDialogPeer({
-                peer: dialog
+                peer: dialog,
             });
         }
-    } catch (e) {
-    }
+    } catch (e) {}
     return new Api.InputDialogPeer({
-        peer: dialog
+        peer: dialog,
     });
 }
 
@@ -458,10 +453,9 @@ export async function _getInputNotify(client: TelegramClient, notify: any) {
             }
             return notify;
         }
-    } catch (e) {
-    }
+    } catch (e) {}
     return new Api.InputNotifyPeer({
-        peer: await client.getInputEntity(notify)
+        peer: await client.getInputEntity(notify),
     });
 }
 

+ 1 - 1
gramjs/errors/RPCBaseErrors.ts

@@ -2,7 +2,7 @@
  * Base class for all Remote Procedure Call errors.
  */
 import { Api } from "../tl";
-import { CustomError } from 'ts-custom-error'
+import { CustomError } from "ts-custom-error";
 
 export class RPCError extends CustomError {
     protected code: number | undefined;

+ 0 - 1
gramjs/errors/index.ts

@@ -13,7 +13,6 @@ export function RPCMessageToError(
     rpcError: Api.RpcError,
     request: Api.AnyRequest
 ) {
-
     for (const [msgRegex, Cls] of rpcErrorRe) {
         const m = rpcError.errorMessage.match(msgRegex);
         if (m) {

+ 6 - 0
gramjs/sessions/Memory.ts

@@ -145,6 +145,12 @@ export class MemorySession extends Session {
                 if ("user" in tlo) {
                     entities.push(tlo.user);
                 }
+                if ("chat" in tlo) {
+                    entities.push(tlo.chat);
+                }
+                if ("channel" in tlo) {
+                    entities.push(tlo.channel);
+                }
                 if ("chats" in tlo && isArrayLike(tlo.chats)) {
                     entities = entities.concat(tlo.chats);
                 }

+ 2 - 2
gramjs/sessions/StoreSession.ts

@@ -9,9 +9,9 @@ export class StoreSession extends MemorySession {
     constructor(sessionName: string) {
         super();
         if (typeof localStorage === "undefined" || localStorage === null) {
-            const LocalStorage = require('node-localstorage').LocalStorage;
+            const LocalStorage = require("node-localstorage").LocalStorage;
             this.store = store.area("fs", new LocalStorage("./" + sessionName));
-        }else{
+        } else {
             this.store = store.area("fs", localStorage);
         }
         this.sessionName = sessionName + ":";

+ 2 - 2
package-lock.json

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

+ 1 - 1
package.json

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