Bläddra i källkod

Fix handling update

painor 3 år sedan
förälder
incheckning
d7c4d01c93

+ 0 - 3
gramjs/Helpers.ts

@@ -59,9 +59,6 @@ export function groupBy(list: any[], keyGetter: Function) {
 export function betterConsoleLog(object: { [key: string]: any }) {
     const toPrint: { [key: string]: any } = {};
     for (const key in object) {
-        console.log("key is",key);
-        console.log("key starts with _?",key.startsWith("_"));
-
         if (object.hasOwnProperty(key)) {
             if (!key.startsWith("_")) {
                 toPrint[key] = object[key];

+ 44 - 51
gramjs/Utils.ts

@@ -12,7 +12,7 @@ import { HTMLParser } from "./extensions/html";
 
 const USERNAME_RE = new RegExp(
     "@|(?:https?:\\/\\/)?(?:www\\.)?" +
-    "(?:telegram\\.(?:me|dog)|t\\.me)\\/(@|joinchat\\/)?",
+        "(?:telegram\\.(?:me|dog)|t\\.me)\\/(@|joinchat\\/)?",
     "i"
 );
 
@@ -26,7 +26,7 @@ const TG_JOIN_RE = new RegExp("tg:\\/\\/(join)\\?invite=", "i");
 
 const VALID_USERNAME_RE = new RegExp(
     "^([a-z]((?!__)[\\w\\d]){3,30}[a-z\\d]|gif|vid|" +
-    "pic|bing|wiki|imdb|bold|vote|like|coub)$",
+        "pic|bing|wiki|imdb|bold|vote|like|coub)$",
     "i"
 );
 
@@ -81,7 +81,7 @@ export function getInputPeer(
         } else if (entity.accessHash !== undefined || !checkHash) {
             return new Api.InputPeerUser({
                 userId: entity.id,
-                accessHash: entity.accessHash || bigInt(0)
+                accessHash: entity.accessHash || bigInt(0),
             });
         } else {
             throw new Error("User without accessHash cannot be input");
@@ -98,7 +98,7 @@ export function getInputPeer(
         if (entity.accessHash !== undefined || !checkHash) {
             return new Api.InputPeerChannel({
                 channelId: entity.id,
-                accessHash: entity.accessHash || bigInt(0)
+                accessHash: entity.accessHash || bigInt(0),
             });
         } else {
             throw new TypeError(
@@ -111,20 +111,20 @@ export function getInputPeer(
         // also not optional, we assume that this truly is the case.
         return new Api.InputPeerChannel({
             channelId: entity.id,
-            accessHash: entity.accessHash
+            accessHash: entity.accessHash,
         });
     }
 
     if (entity instanceof Api.InputUser) {
         return new Api.InputPeerUser({
             userId: entity.userId,
-            accessHash: entity.accessHash
+            accessHash: entity.accessHash,
         });
     }
     if (entity instanceof Api.InputChannel) {
         return new Api.InputPeerChannel({
             channelId: entity.channelId,
-            accessHash: entity.accessHash
+            accessHash: entity.accessHash,
         });
     }
     if (entity instanceof Api.UserEmpty) {
@@ -140,7 +140,7 @@ export function getInputPeer(
 
     if (entity instanceof Api.PeerChat) {
         return new Api.InputPeerChat({
-            chatId: entity.chatId
+            chatId: entity.chatId,
         });
     }
 
@@ -177,18 +177,14 @@ export function _getEntityPair(
     } catch (e) {
         try {
             inputEntity = getInputPeerFunction(inputEntity);
-        } catch (e) {
-        }
+        } catch (e) {}
     }
     return [entity, inputEntity];
 }
 
-export function getInnerText(
-    text: string,
-    entities: Api.TypeMessageEntity[]
-) {
+export function getInnerText(text: string, entities: Api.TypeMessageEntity[]) {
     const result: string[] = [];
-    entities.forEach(function(value, key) {
+    entities.forEach(function (value, key) {
         const start = value.offset;
         const end = value.offset + value.length;
         result.push(text.slice(start, end));
@@ -226,14 +222,14 @@ export function getInputChannel(entity: EntityLike) {
     ) {
         return new Api.InputChannel({
             channelId: entity.id,
-            accessHash: entity.accessHash || bigInt.zero
+            accessHash: entity.accessHash || bigInt.zero,
         });
     }
 
     if (entity instanceof Api.InputPeerChannel) {
         return new Api.InputChannel({
             channelId: entity.channelId,
-            accessHash: entity.accessHash
+            accessHash: entity.accessHash,
         });
     }
     _raiseCastFail(entity, "InputChannel");
@@ -269,7 +265,7 @@ export function getInputUser(entity: EntityLike): Api.InputPeerSelf {
         } else {
             return new Api.InputUser({
                 userId: entity.id,
-                accessHash: entity.accessHash || bigInt.zero
+                accessHash: entity.accessHash || bigInt.zero,
             });
         }
     }
@@ -290,7 +286,7 @@ export function getInputUser(entity: EntityLike): Api.InputPeerSelf {
     if (entity instanceof Api.InputPeerUser) {
         return new Api.InputUser({
             userId: entity.userId,
-            accessHash: entity.accessHash
+            accessHash: entity.accessHash,
         });
     }
 
@@ -359,13 +355,13 @@ export function getInputChatPhoto(photo: any): Api.TypeInputChatPhoto {
     } else if (photo.SUBCLASS_OF_ID === 0xe7655f1f) {
         // crc32(b'InputFile'):
         return new Api.InputChatUploadedPhoto({
-            file: photo
+            file: photo,
         });
     }
     photo = getInputPhoto(photo);
     if (photo instanceof Api.InputPhoto) {
         return new Api.InputChatPhoto({
-            id: photo
+            id: photo,
         });
     } else if (photo instanceof Api.InputPhotoEmpty) {
         return new Api.InputChatPhotoEmpty();
@@ -469,7 +465,7 @@ export function getInputPhoto(photo: any): Api.TypePhoto | Api.InputPhotoEmpty {
         return new Api.InputPhoto({
             id: photo.id,
             accessHash: photo.accessHash,
-            fileReference: photo.fileReference
+            fileReference: photo.fileReference,
         });
     }
     if (photo instanceof Api.PhotoEmpty) {
@@ -523,7 +519,7 @@ export function getInputDocument(
         return new Api.InputDocument({
             id: document.id,
             accessHash: document.accessHash,
-            fileReference: document.fileReference
+            fileReference: document.fileReference,
         });
     }
     if (document instanceof Api.DocumentEmpty) {
@@ -582,8 +578,7 @@ export function getExtension(media: any): string {
     try {
         getInputPhoto(media);
         return ".jpg";
-    } catch (e) {
-    }
+    } catch (e) {}
     if (
         media instanceof Api.UserProfilePhoto ||
         media instanceof Api.ChatPhoto
@@ -658,7 +653,7 @@ export function getAttributes(
         voiceNote = false,
         videoNote = false,
         supportsStreaming = false,
-        thumb = null
+        thumb = null,
     }: GetAttributesParams
 ) {
     const name: string =
@@ -670,7 +665,7 @@ export function getAttributes(
     attrObj.set(
         Api.DocumentAttributeFilename,
         new Api.DocumentAttributeFilename({
-            fileName: name.split(/[\\/]/).pop() || ""
+            fileName: name.split(/[\\/]/).pop() || "",
         })
     );
     if (isAudio(file)) {
@@ -682,7 +677,7 @@ export function getAttributes(
                     voice: voiceNote,
                     title: m.has("title") ? m.get("title") : undefined,
                     performer: m.has("author") ? m.get("author") : undefined,
-                    duration: Number.parseInt(m.get("duration") ?? "0")
+                    duration: Number.parseInt(m.get("duration") ?? "0"),
                 })
             );
         }
@@ -696,7 +691,7 @@ export function getAttributes(
                 w: Number.parseInt(m.get("width") ?? "0"),
                 h: Number.parseInt(m.get("height") ?? "0"),
                 duration: Number.parseInt(m.get("duration") ?? "0"),
-                supportsStreaming: supportsStreaming
+                supportsStreaming: supportsStreaming,
             });
         } else {
             if (thumb) {
@@ -708,7 +703,7 @@ export function getAttributes(
                     h: height,
                     w: width,
                     roundMessage: videoNote,
-                    supportsStreaming: supportsStreaming
+                    supportsStreaming: supportsStreaming,
                 });
             } else {
                 doc = new Api.DocumentAttributeVideo({
@@ -716,7 +711,7 @@ export function getAttributes(
                     h: 1,
                     w: 1,
                     roundMessage: videoNote,
-                    supportsStreaming: supportsStreaming
+                    supportsStreaming: supportsStreaming,
                 });
             }
         }
@@ -730,7 +725,7 @@ export function getAttributes(
                 Api.DocumentAttributeAudio,
                 new Api.DocumentAttributeAudio({
                     duration: 0,
-                    voice: true
+                    voice: true,
                 })
             );
         }
@@ -747,7 +742,7 @@ export function getAttributes(
 
     return {
         attrs: Array.from(attrObj.values()) as Api.TypeDocumentAttribute[],
-        mimeType: mimeType
+        mimeType: mimeType,
     };
 }
 
@@ -787,7 +782,6 @@ export interface GetInputMediaInterface {
     supportsStreaming?: boolean;
 }
 
-
 /**
  *
  Similar to :meth:`get_input_peer`, but for media.
@@ -811,7 +805,7 @@ export function getInputMedia(
         forceDocument = false,
         voiceNote = false,
         videoNote = false,
-        supportsStreaming = false
+        supportsStreaming = false,
     }: GetInputMediaInterface = {}
 ): any {
     if (media.SUBCLASS_OF_ID === undefined) {
@@ -836,7 +830,7 @@ export function getInputMedia(
     if (media instanceof Api.MessageMediaPhoto) {
         return new Api.InputMediaPhoto({
             id: getInputPhoto(media.photo),
-            ttlSeconds: media.ttlSeconds
+            ttlSeconds: media.ttlSeconds,
         });
     }
     if (
@@ -849,7 +843,7 @@ export function getInputMedia(
     if (media instanceof Api.MessageMediaDocument) {
         return new Api.InputMediaDocument({
             id: getInputDocument(media.document),
-            ttlSeconds: media.ttlSeconds
+            ttlSeconds: media.ttlSeconds,
         });
     }
     if (media instanceof Api.Document || media instanceof Api.DocumentEmpty) {
@@ -864,13 +858,13 @@ export function getInputMedia(
                 forceDocument: forceDocument,
                 voiceNote: voiceNote,
                 videoNote: videoNote,
-                supportsStreaming: supportsStreaming
+                supportsStreaming: supportsStreaming,
             });
             return new Api.InputMediaUploadedDocument({
                 file: media,
                 mimeType: mimeType,
                 attributes: attrs,
-                forceFile: forceDocument
+                forceFile: forceDocument,
             });
         }
     }
@@ -878,8 +872,8 @@ export function getInputMedia(
         return new Api.InputMediaGame({
             id: new Api.InputGameID({
                 id: media.game.id,
-                accessHash: media.game.accessHash
-            })
+                accessHash: media.game.accessHash,
+            }),
         });
     }
     if (media instanceof Api.MessageMediaContact) {
@@ -887,7 +881,7 @@ export function getInputMedia(
             phoneNumber: media.phoneNumber,
             firstName: media.firstName,
             lastName: media.lastName,
-            vcard: ""
+            vcard: "",
         });
     }
     if (media instanceof Api.MessageMediaGeo) {
@@ -900,12 +894,12 @@ export function getInputMedia(
             address: media.address,
             provider: media.provider,
             venueId: media.venueId,
-            venueType: ""
+            venueType: "",
         });
     }
     if (media instanceof Api.MessageMediaDice) {
         return new Api.InputMediaDice({
-            emoticon: media.emoticon
+            emoticon: media.emoticon,
         });
     }
     if (
@@ -943,12 +937,12 @@ export function getInputMedia(
             poll: media.poll,
             correctAnswers: correctAnswers,
             solution: media.results.solution,
-            solutionEntities: media.results.solutionEntities
+            solutionEntities: media.results.solutionEntities,
         });
     }
     if (media instanceof Api.Poll) {
         return new Api.InputMediaPoll({
-            poll: media
+            poll: media,
         });
     }
     _raiseCastFail(media, "InputMedia");
@@ -1029,8 +1023,7 @@ export function getPeer(peer: EntityLike) {
         } else if (peer instanceof Api.InputPeerChannel) {
             return new Api.PeerChannel({ channelId: peer.channelId });
         }
-    } catch (e) {
-    }
+    } catch (e) {}
     _raiseCastFail(peer, "peer");
 }
 
@@ -1212,7 +1205,7 @@ export function parseUsername(username: string): {
         if (m[1]) {
             return {
                 username: username,
-                isInvite: true
+                isInvite: true,
             };
         } else {
             username = rtrim(username, "/");
@@ -1221,12 +1214,12 @@ export function parseUsername(username: string): {
     if (username.match(VALID_USERNAME_RE)) {
         return {
             username: username.toLowerCase(),
-            isInvite: false
+            isInvite: false,
         };
     } else {
         return {
             username: undefined,
-            isInvite: false
+            isInvite: false,
         };
     }
 }

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.7.9";
+export const version = "1.7.12";

+ 60 - 30
gramjs/client/TelegramClient.ts

@@ -18,12 +18,13 @@ import type { EventBuilder } from "../events/common";
 import { MTProtoSender, UpdateConnectionState } from "../network";
 
 import { LAYER } from "../tl/AllTLObjects";
-import { IS_NODE } from "../Helpers";
+import { betterConsoleLog, IS_NODE } from "../Helpers";
 import { DownloadMediaInterface } from "./downloads";
 import type { Message } from "../tl/custom/message";
 import { NewMessage, NewMessageEvent } from "../events";
 import { _dispatchUpdate, _handleUpdate, _updateLoop } from "./updates";
 import { Session } from "../sessions";
+import { inspect } from "util";
 
 /**
  * The TelegramClient uses several methods in different files to provide all the common functionality in a nice interface.</br>
@@ -36,10 +37,8 @@ import { Session } from "../sessions";
  * ```
  *
  * You don't need to import any methods that are inside the TelegramClient class as they binding in it.
-*/
+ */
 export class TelegramClient extends TelegramBaseClient {
-
-
     /**
      * @param session - a session to be used to save the connection and auth key to. This can be a custom session that inherits MemorySession.
      * @param apiId - The API ID you obtained from https://my.telegram.org.
@@ -109,7 +108,6 @@ export class TelegramClient extends TelegramBaseClient {
         return authMethods.checkAuthorization(this);
     }
 
-
     /**
      * Logs in as a user. Should only be used when not already logged in.<br/>
      * This method will send a code when needed.<br/>
@@ -160,7 +158,6 @@ export class TelegramClient extends TelegramBaseClient {
         );
     }
 
-
     /**
      * Sends a telegram authentication code to the phone number.
      * @example
@@ -203,7 +200,6 @@ export class TelegramClient extends TelegramBaseClient {
         return authMethods.signInWithPassword(this, apiCredentials, authParams);
     }
 
-
     /**
      * Used to sign in as a bot.
      * @example
@@ -229,7 +225,6 @@ export class TelegramClient extends TelegramBaseClient {
         return authMethods.signInBot(this, apiCredentials, authParams);
     }
 
-
     //endregion auth
 
     //region bot
@@ -366,7 +361,7 @@ export class TelegramClient extends TelegramBaseClient {
     downloadProfilePhoto(
         entity: EntityLike,
         downloadProfilePhotoParams: downloadMethods.DownloadProfilePhotoParams = {
-            isBig: false
+            isBig: false,
         }
     ) {
         return downloadMethods.downloadProfilePhoto(
@@ -400,7 +395,11 @@ export class TelegramClient extends TelegramBaseClient {
         messageOrMedia: Api.Message | Api.TypeMessageMedia | Message,
         downloadParams: DownloadMediaInterface
     ) {
-        return downloadMethods.downloadMedia(this, messageOrMedia, downloadParams);
+        return downloadMethods.downloadMedia(
+            this,
+            messageOrMedia,
+            downloadParams
+        );
     }
 
     //endregion
@@ -440,7 +439,14 @@ export class TelegramClient extends TelegramBaseClient {
      * client.setParseMode(undefined);
      * await client.sendMessage("me","<u> this will be sent as it is</u> ** with no formatting **);
      */
-    setParseMode(mode: "md" | "markdown" | "html" | parseMethods.ParseInterface | undefined) {
+    setParseMode(
+        mode:
+            | "md"
+            | "markdown"
+            | "html"
+            | parseMethods.ParseInterface
+            | undefined
+    ) {
         if (mode) {
             this._parseMode = sanitizeParseMode(mode);
         } else {
@@ -575,11 +581,13 @@ export class TelegramClient extends TelegramBaseClient {
      *
      * ```
      */
-    sendMessage(entity: EntityLike, sendMessageParams: messageMethods.SendMessageParams) {
+    sendMessage(
+        entity: EntityLike,
+        sendMessageParams: messageMethods.SendMessageParams
+    ) {
         return messageMethods.sendMessage(this, entity, sendMessageParams);
     }
 
-
     /**
      * Forwards the given messages to the specified entity.<br/>
      *<br/>
@@ -613,7 +621,11 @@ export class TelegramClient extends TelegramBaseClient {
         entity: EntityLike,
         forwardMessagesParams: messageMethods.ForwardMessagesParams
     ) {
-        return messageMethods.forwardMessages(this, entity, forwardMessagesParams);
+        return messageMethods.forwardMessages(
+            this,
+            entity,
+            forwardMessagesParams
+        );
     }
 
     /**
@@ -640,7 +652,10 @@ export class TelegramClient extends TelegramBaseClient {
      *  await client.editMessage(chat,{message:message.id,text:"Hello!"}
      *  ```
      */
-    editMessage(entity: EntityLike, editMessageParams: messageMethods.EditMessageParams) {
+    editMessage(
+        entity: EntityLike,
+        editMessageParams: messageMethods.EditMessageParams
+    ) {
         return messageMethods.editMessage(this, entity, editMessageParams);
     }
 
@@ -752,11 +767,16 @@ export class TelegramClient extends TelegramBaseClient {
         return updateMethods.on(this, event);
     }
 
-
     /** @hidden */
-    addEventHandler(callback: { (event: NewMessageEvent): void }, event: NewMessage): void;
+    addEventHandler(
+        callback: { (event: NewMessageEvent): void },
+        event: NewMessage
+    ): void;
     /** @hidden */
-    addEventHandler(callback: { (event: any): void }, event?: EventBuilder): void;
+    addEventHandler(
+        callback: { (event: any): void },
+        event?: EventBuilder
+    ): void;
 
     /**
      * Registers a new event handler callback.<br/>
@@ -867,7 +887,10 @@ export class TelegramClient extends TelegramBaseClient {
      *  }))
      ```
      */
-    sendFile(entity: EntityLike, sendFileParams: uploadMethods.SendFileInterface) {
+    sendFile(
+        entity: EntityLike,
+        sendFileParams: uploadMethods.SendFileInterface
+    ) {
         return uploadMethods.sendFile(this, entity, sendFileParams);
     }
 
@@ -1044,7 +1067,8 @@ export class TelegramClient extends TelegramBaseClient {
             connectTimeout: this._timeout,
             authKeyCallback: this._authKeyCallback.bind(this),
             updateCallback: _handleUpdate.bind(this),
-            isMainSender: true
+            isMainSender: true,
+            client: this,
         });
 
         const connection = new this._connection(
@@ -1067,7 +1091,7 @@ export class TelegramClient extends TelegramBaseClient {
         await this._sender.send(
             new Api.InvokeWithLayer({
                 layer: LAYER,
-                query: this._initRequest
+                query: this._initRequest,
             })
         );
 
@@ -1105,7 +1129,8 @@ export class TelegramClient extends TelegramBaseClient {
             connectTimeout: this._timeout,
             authKeyCallback: this._authKeyCallback.bind(this),
             isMainSender: dcId === this.session.dcId,
-            senderCallback: this._removeSender.bind(this)
+            senderCallback: this._removeSender.bind(this),
+            client: this,
         });
         for (let i = 0; i < retries; i++) {
             try {
@@ -1121,11 +1146,11 @@ export class TelegramClient extends TelegramBaseClient {
                     );
                     this._initRequest.query = new Api.auth.ImportAuthorization({
                         id: auth.id,
-                        bytes: auth.bytes
+                        bytes: auth.bytes,
                     });
                     const req = new Api.InvokeWithLayer({
                         layer: LAYER,
-                        query: this._initRequest
+                        query: this._initRequest,
                     });
                     await sender.send(req);
                 }
@@ -1157,31 +1182,31 @@ export class TelegramClient extends TelegramBaseClient {
                     return {
                         id: 1,
                         ipAddress: "pluto.web.telegram.org",
-                        port: 443
+                        port: 443,
                     };
                 case 2:
                     return {
                         id: 2,
                         ipAddress: "venus.web.telegram.org",
-                        port: 443
+                        port: 443,
                     };
                 case 3:
                     return {
                         id: 3,
                         ipAddress: "aurora.web.telegram.org",
-                        port: 443
+                        port: 443,
                     };
                 case 4:
                     return {
                         id: 4,
                         ipAddress: "vesta.web.telegram.org",
-                        port: 443
+                        port: 443,
                     };
                 case 5:
                     return {
                         id: 5,
                         ipAddress: "flora.web.telegram.org",
-                        port: 443
+                        port: 443,
                     };
                 default:
                     throw new Error(
@@ -1197,7 +1222,7 @@ export class TelegramClient extends TelegramBaseClient {
                 return {
                     id: DC.id,
                     ipAddress: DC.ipAddress,
-                    port: 443
+                    port: 443,
                 };
             }
         }
@@ -1231,5 +1256,10 @@ export class TelegramClient extends TelegramBaseClient {
         return parseMethods._getResponseMessage(this, req, result, inputChat);
     }
 
+    /** @hidden */
+    [inspect.custom]() {
+        return betterConsoleLog(this);
+    }
+
     // endregion
 }

+ 1 - 1
gramjs/client/auth.ts

@@ -76,7 +76,7 @@ export async function start(
         apiHash: client.apiHash,
     };
 
-    await _authFlow(client,apiCredentials, authParams);
+    await _authFlow(client, apiCredentials, authParams);
 }
 /** @hidden */
 export async function checkAuthorization(client: TelegramClient) {

+ 1 - 5
gramjs/client/bots.ts

@@ -28,9 +28,5 @@ export async function inlineQuery(
             geoPoint: geoPoint,
         })
     );
-    return new InlineResults(
-        client,
-        result,
-        (entity ? peer : undefined)
-    );
+    return new InlineResults(client, result, entity ? peer : undefined);
 }

+ 1 - 1
gramjs/client/buttons.ts

@@ -1,5 +1,5 @@
 import { Api } from "../tl";
-import type { ButtonLike} from "../define";
+import type { ButtonLike } from "../define";
 import { Button } from "../tl/custom/button";
 import { MessageButton } from "../tl/custom/messageButton";
 import { isArrayLike } from "../Helpers";

+ 18 - 18
gramjs/client/chats.ts

@@ -38,7 +38,7 @@ class _ChatAction {
         document: new Api.SendMessageUploadDocumentAction({ progress: 1 }),
         file: new Api.SendMessageUploadDocumentAction({ progress: 1 }), // alias
 
-        cancel: new Api.SendMessageCancelAction()
+        cancel: new Api.SendMessageCancelAction(),
     };
 
     private _client: TelegramClient;
@@ -60,7 +60,7 @@ class _ChatAction {
         action: ValueOf<typeof _ChatAction._str_mapping>,
         params: ChatActionInterface = {
             delay: 4,
-            autoCancel: true
+            autoCancel: true,
         }
     ) {
         this._client = client;
@@ -76,7 +76,7 @@ class _ChatAction {
     async start() {
         this._request = new Api.messages.SetTyping({
             peer: this._chat,
-            action: this._action
+            action: this._action,
         });
         this._running = true;
         this._update();
@@ -88,7 +88,7 @@ class _ChatAction {
             await this._client.invoke(
                 new Api.messages.SetTyping({
                     peer: this._chat,
-                    action: new Api.SendMessageCancelAction()
+                    action: new Api.SendMessageCancelAction(),
                 })
             );
         }
@@ -125,21 +125,21 @@ export class _ParticipantsIter extends RequestIter {
     }
 
     async _init({
-                    entity,
-                    filter,
-                    search
-                }: ParticipantsIterInterface): Promise<boolean | void> {
+        entity,
+        filter,
+        search,
+    }: ParticipantsIterInterface): Promise<boolean | void> {
         if (filter && filter.constructor === Function) {
             if (
                 [
                     Api.ChannelParticipantsBanned,
                     Api.ChannelParticipantsKicked,
                     Api.ChannelParticipantsSearch,
-                    Api.ChannelParticipantsContacts
+                    Api.ChannelParticipantsContacts,
                 ].includes(filter)
             ) {
                 filter = new filter({
-                    q: ""
+                    q: "",
                 });
             } else {
                 filter = new filter();
@@ -169,7 +169,7 @@ export class _ParticipantsIter extends RequestIter {
         if (ty == helpers._EntityType.CHANNEL) {
             const channel = await this.client.invoke(
                 new Api.channels.GetFullChannel({
-                    channel: entity
+                    channel: entity,
                 })
             );
             if (!(channel.fullChat instanceof Api.ChatFull)) {
@@ -184,11 +184,11 @@ export class _ParticipantsIter extends RequestIter {
                     filter:
                         filter ||
                         new Api.ChannelParticipantsSearch({
-                            q: search || ""
+                            q: search || "",
                         }),
                     offset: 0,
                     limit: _MAX_PARTICIPANTS_CHUNK_SIZE,
-                    hash: 0
+                    hash: 0,
                 })
             );
         } else if (ty == helpers._EntityType.CHAT) {
@@ -199,7 +199,7 @@ export class _ParticipantsIter extends RequestIter {
             }
             const full = await this.client.invoke(
                 new Api.messages.GetFullChat({
-                    chatId: entity.chatId
+                    chatId: entity.chatId,
                 })
             );
 
@@ -265,7 +265,7 @@ export class _ParticipantsIter extends RequestIter {
             const participants = results[i];
             if (
                 participants instanceof
-                Api.channels.ChannelParticipantsNotModified ||
+                    Api.channels.ChannelParticipantsNotModified ||
                 !participants.users.length
             ) {
                 this.requests.splice(i, 1);
@@ -342,7 +342,7 @@ class _AdminLogIter extends RequestIter {
             Object.values(filterArgs).find((element) => element === true)
         ) {
             eventsFilter = new Api.ChannelAdminLogEventsFilter({
-                ...filterArgs
+                ...filterArgs,
             });
         }
         this.entity = await this.client.getInputEntity(entity);
@@ -359,7 +359,7 @@ class _AdminLogIter extends RequestIter {
             maxId: searchArgs?.maxId,
             limit: 0,
             eventsFilter: eventsFilter,
-            admins: adminList || undefined
+            admins: adminList || undefined,
         });
     }
 
@@ -416,7 +416,7 @@ export function iterParticipants(
         {
             entity: entity,
             filter: filter,
-            search: search
+            search: search,
         }
     );
 }

+ 13 - 14
gramjs/client/dialogs.ts

@@ -3,7 +3,7 @@ import { RequestIter } from "../requestIter";
 import { TelegramClient, utils } from "../index";
 import { Message } from "../tl/custom/message";
 import { Dialog } from "../tl/custom/dialog";
-import { DateLike, EntityLike} from "../define";
+import { DateLike, EntityLike } from "../define";
 import { TotalList } from "../Helpers";
 
 const _MAX_CHUNK_SIZE = 100;
@@ -24,7 +24,7 @@ function _dialogMessageKey(peer: Api.TypePeer, messageId: number): string {
         "" +
         [
             peer instanceof Api.PeerChannel ? peer.channelId : undefined,
-            messageId
+            messageId,
         ]
     );
 }
@@ -45,13 +45,13 @@ export class _DialogsIter extends RequestIter {
     private ignoreMigrated?: boolean;
 
     async _init({
-                    offsetDate,
-                    offsetId,
-                    offsetPeer,
-                    ignorePinned,
-                    ignoreMigrated,
-                    folder
-                }: DialogsIterInterface) {
+        offsetDate,
+        offsetId,
+        offsetPeer,
+        ignorePinned,
+        ignoreMigrated,
+        folder,
+    }: DialogsIterInterface) {
         this.request = new Api.messages.GetDialogs({
             offsetDate,
             offsetId,
@@ -59,7 +59,7 @@ export class _DialogsIter extends RequestIter {
             limit: 1,
             hash: 0,
             excludePinned: ignorePinned,
-            folderId: folder
+            folderId: folder,
         });
         if (this.limit <= 0) {
             // Special case, get a single dialog and determine count
@@ -112,7 +112,7 @@ export class _DialogsIter extends RequestIter {
             } catch (e) {
                 this.client._log.error(
                     "Got error while trying to finish init message with id " +
-                    m.id
+                        m.id
                 );
                 if (this.client._log.canSend("error")) {
                     console.error(e);
@@ -180,7 +180,6 @@ export class _DialogsIter extends RequestIter {
     }
 }
 
-
 /** interface for iterating and getting dialogs. */
 export interface IterDialogsParams {
     /**  How many dialogs to be retrieved as maximum. Can be set to undefined to retrieve all dialogs.<br/>
@@ -218,7 +217,7 @@ export function iterDialogs(
         ignorePinned = false,
         ignoreMigrated = false,
         folder = undefined,
-        archived = undefined
+        archived = undefined,
     }: IterDialogsParams
 ): _DialogsIter {
     if (archived != undefined) {
@@ -235,7 +234,7 @@ export function iterDialogs(
             offsetPeer,
             ignorePinned,
             ignoreMigrated,
-            folder
+            folder,
         }
     );
 }

+ 14 - 15
gramjs/client/downloads.ts

@@ -151,12 +151,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) {
@@ -199,8 +199,7 @@ class Foreman {
     private deferred: Deferred | undefined;
     private activeWorkers = 0;
 
-    constructor(private maxWorkers: number) {
-    }
+    constructor(private maxWorkers: number) {}
 
     requestWorker() {
         this.activeWorkers++;
@@ -230,7 +229,7 @@ function createDeferred(): Deferred {
 
     return {
         promise,
-        resolve: resolve!
+        resolve: resolve!,
     };
 }
 
@@ -271,19 +270,19 @@ export async function downloadMedia(
         }
     }
     if (media instanceof Api.MessageMediaPhoto || media instanceof Api.Photo) {
-        return _downloadPhoto(client,media, downloadParams);
+        return _downloadPhoto(client, media, downloadParams);
     } else if (
         media instanceof Api.MessageMediaDocument ||
         media instanceof Api.Document
     ) {
-        return _downloadDocument(client,media, downloadParams);
+        return _downloadDocument(client, media, downloadParams);
     } else if (media instanceof Api.MessageMediaContact) {
-        return _downloadContact(client,media, downloadParams);
+        return _downloadContact(client, media, downloadParams);
     } else if (
         media instanceof Api.WebDocument ||
         media instanceof Api.WebDocumentNoProxy
     ) {
-        return _downloadWebDocument(client,media, downloadParams);
+        return _downloadWebDocument(client, media, downloadParams);
     } else {
         return Buffer.alloc(0);
     }
@@ -325,7 +324,7 @@ export async function _downloadDocument(
             id: doc.id,
             accessHash: doc.accessHash,
             fileReference: doc.fileReference,
-            thumbSize: size ? size.type : ""
+            thumbSize: size ? size.type : "",
         }),
         {
             fileSize:
@@ -336,7 +335,7 @@ export async function _downloadDocument(
             start: args.start,
             end: args.end,
             dcId: doc.dcId,
-            workers: args.workers
+            workers: args.workers,
         }
     );
 }
@@ -421,12 +420,12 @@ export async function _downloadPhoto(
             id: photo.id,
             accessHash: photo.accessHash,
             fileReference: photo.fileReference,
-            thumbSize: size.type
+            thumbSize: size.type,
         }),
         {
             dcId: photo.dcId,
             fileSize: size.size,
-            progressCallback: args.progressCallback
+            progressCallback: args.progressCallback,
         }
     );
 }
@@ -457,7 +456,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);
@@ -465,6 +464,6 @@ export async function downloadProfilePhoto(
     return client.downloadFile(loc, {
         dcId,
         fileSize: 2 * 1024 * 1024,
-        workers: 1
+        workers: 1,
     });
 }

+ 8 - 10
gramjs/client/messageParse.ts

@@ -1,6 +1,6 @@
 import { getPeerId, sanitizeParseMode } from "../Utils";
 import { Api } from "../tl";
-import type { EntityLike} from "../define";
+import type { EntityLike } from "../define";
 import type { TelegramClient } from "./TelegramClient";
 import { utils } from "../index";
 import { _EntityType, _entityType, isArrayLike } from "../Helpers";
@@ -20,17 +20,14 @@ export const DEFAULT_DELIMITERS: {
     __: Api.MessageEntityItalic,
     "~~": Api.MessageEntityStrike,
     "`": Api.MessageEntityCode,
-    "```": Api.MessageEntityPre
+    "```": Api.MessageEntityPre,
 };
 
 // export class MessageParseMethods {
 
 export interface ParseInterface {
     parse: (message: string) => [string, Api.TypeMessageEntity[]];
-    unparse: (
-        text: string,
-        entities: Api.TypeMessageEntity[]
-    ) => string;
+    unparse: (text: string, entities: Api.TypeMessageEntity[]) => string;
 }
 
 export async function _replaceWithMention(
@@ -43,7 +40,7 @@ export async function _replaceWithMention(
         entities[i] = new Api.InputMessageEntityMentionName({
             offset: entities[i].offset,
             length: entities[i].length,
-            userId: await client.getInputEntity(user)
+            userId: await client.getInputEntity(user),
         });
         return true;
     } catch (e) {
@@ -136,7 +133,8 @@ export function _getResponseMessage(
         } else if (
             update instanceof Api.UpdateEditChannelMessage &&
             "peer" in request &&
-            getPeerId(request.peer) == getPeerId((update.message as unknown as Message).peerId!)
+            getPeerId(request.peer) ==
+                getPeerId((update.message as unknown as Message).peerId!)
         ) {
             if (request.id == update.message.id) {
                 (update.message as unknown as Message)._finishInit(
@@ -163,10 +161,10 @@ export function _getResponseMessage(
                     peerId: utils.getPeerId(request.peer),
                     media: new Api.MessageMediaPoll({
                         poll: update.poll!,
-                        results: update.results
+                        results: update.results,
                     }),
                     message: "",
-                    date: 0
+                    date: 0,
                 });
                 m._finishInit(client, entities, inputChat);
                 return m;

+ 46 - 46
gramjs/client/messages.ts

@@ -6,7 +6,7 @@ import type {
     FileLike,
     MarkupLike,
     MessageIDLike,
-    MessageLike
+    MessageLike,
 } from "../define";
 import { RequestIter } from "../requestIter";
 import {
@@ -14,7 +14,7 @@ import {
     _entityType,
     TotalList,
     isArrayLike,
-    groupBy
+    groupBy,
 } from "../Helpers";
 import { getMessageId, getPeerId } from "../Utils";
 import type { TelegramClient } from "../";
@@ -51,17 +51,17 @@ export class _MessagesIter extends RequestIter {
     lastId?: number;
 
     async _init({
-                    entity,
-                    offsetId,
-                    minId,
-                    maxId,
-                    fromUser,
-                    offsetDate,
-                    addOffset,
-                    filter,
-                    search,
-                    replyTo
-                }: MessageIterParams) {
+        entity,
+        offsetId,
+        minId,
+        maxId,
+        fromUser,
+        offsetDate,
+        addOffset,
+        filter,
+        search,
+        replyTo,
+    }: MessageIterParams) {
         if (entity) {
             this.entity = await this.client.getInputEntity(entity);
         } else {
@@ -118,7 +118,7 @@ export class _MessagesIter extends RequestIter {
                 offsetRate: undefined,
                 offsetPeer: new Api.InputPeerEmpty(),
                 offsetId: offsetId,
-                limit: 1
+                limit: 1,
             });
         } else if (replyTo !== undefined) {
             this.request = new Api.messages.GetReplies({
@@ -130,7 +130,7 @@ export class _MessagesIter extends RequestIter {
                 limit: 0,
                 maxId: 0,
                 minId: 0,
-                hash: 0
+                hash: 0,
             });
         } else if (
             search !== undefined ||
@@ -155,7 +155,7 @@ export class _MessagesIter extends RequestIter {
                 maxId: 0,
                 minId: 0,
                 hash: 0,
-                fromId: fromUser
+                fromId: fromUser,
             });
             if (
                 filter instanceof Api.InputMessagesFilterEmpty &&
@@ -165,7 +165,7 @@ export class _MessagesIter extends RequestIter {
             ) {
                 for await (const m of this.client.iterMessages(this.entity, {
                     limit: 1,
-                    offsetDate: offsetDate
+                    offsetDate: offsetDate,
                 })) {
                     this.request.offsetId = m.id + 1;
                 }
@@ -179,7 +179,7 @@ export class _MessagesIter extends RequestIter {
                 minId: 0,
                 maxId: 0,
                 addOffset: addOffset,
-                hash: 0
+                hash: 0,
             });
         }
         if (this.limit <= 0) {
@@ -249,8 +249,7 @@ export class _MessagesIter extends RequestIter {
             try {
                 // if this fails it shouldn't be a big problem
                 message._finishInit(this.client, entities, this.entity);
-            } catch (e) {
-            }
+            } catch (e) {}
             message._entities = entities;
             this.buffer?.push(message);
         }
@@ -355,13 +354,13 @@ export class _IDsIter extends RequestIter {
                 r = await this.client.invoke(
                     new Api.channels.GetMessages({
                         channel: this._entity,
-                        id: ids
+                        id: ids,
                     })
                 );
             } catch (e) {
                 if (e.message == "MESSAGE_IDS_EMPTY") {
                     r = new Api.messages.MessagesNotModified({
-                        count: ids.length
+                        count: ids.length,
                     });
                 } else {
                     throw e;
@@ -370,7 +369,7 @@ export class _IDsIter extends RequestIter {
         } else {
             r = await this.client.invoke(
                 new Api.messages.GetMessages({
-                    id: ids
+                    id: ids,
                 })
             );
             if (this._entity) {
@@ -403,7 +402,7 @@ export class _IDsIter extends RequestIter {
     }
 }
 
- /**
+/**
  * Interface for iterating over messages. used in both {@link iterMessages} and {@link getMessages}.
  */
 export interface IterMessagesParams {
@@ -565,7 +564,7 @@ export function iterMessages(
         waitTime,
         ids,
         reverse = false,
-        replyTo
+        replyTo,
     }: IterMessagesParams
 ) {
     if (ids) {
@@ -580,11 +579,11 @@ export function iterMessages(
             idsArray.length,
             {
                 reverse: reverse,
-                waitTime: waitTime
+                waitTime: waitTime,
             },
             {
                 entity: entity,
-                ids: idsArray
+                ids: idsArray,
             }
         );
     }
@@ -593,7 +592,7 @@ export function iterMessages(
         limit || 1,
         {
             waitTime: waitTime,
-            reverse: reverse
+            reverse: reverse,
         },
         {
             entity: entity,
@@ -605,7 +604,7 @@ export function iterMessages(
             addOffset: addOffset,
             filter: filter,
             search: search,
-            replyTo: replyTo
+            replyTo: replyTo,
         }
     );
 }
@@ -654,13 +653,17 @@ export async function sendMessage(
         buttons,
         silent,
         supportStreaming,
-        schedule
+        schedule,
     }: SendMessageParams
 ) {
     if (file) {
         return client.sendFile(entity, {
             file: file,
-            caption: message ? (typeof message == "string" ? message : message.message) : "",
+            caption: message
+                ? typeof message == "string"
+                    ? message
+                    : message.message
+                : "",
             forceDocument: forceDocument,
             clearDraft: clearDraft,
             replyTo: replyTo,
@@ -671,9 +674,8 @@ export async function sendMessage(
             formattingEntities: formattingEntities,
             silent: silent,
             scheduleDate: schedule,
-            buttons: buttons
+            buttons: buttons,
         });
-
     }
     entity = await client.getInputEntity(entity);
     let markup, request;
@@ -712,7 +714,7 @@ export async function sendMessage(
             entities: message.entities,
             clearDraft: clearDraft,
             noWebpage: !(message.media instanceof Api.MessageMediaWebPage),
-            scheduleDate: schedule
+            scheduleDate: schedule,
         });
         message = message.message;
     } else {
@@ -737,7 +739,7 @@ export async function sendMessage(
             clearDraft: clearDraft,
             silent: silent,
             replyMarkup: client.buildReplyMarkup(buttons),
-            scheduleDate: schedule
+            scheduleDate: schedule,
         });
     }
     const result = await client.invoke(request);
@@ -751,7 +753,7 @@ export async function sendMessage(
             media: result.media,
             entities: result.entities,
             replyMarkup: request.replyMarkup,
-            ttlPeriod: result.ttlPeriod
+            ttlPeriod: result.ttlPeriod,
         });
         msg._finishInit(client, new Map(), entity);
         return msg;
@@ -784,8 +786,10 @@ export async function forwardMessages(
         }
     };
     const sent: Message[] = [];
-    for (let [chatId, chunk] of groupBy(messages, getKey) as Map<number,
-        Message[] | number[]>) {
+    for (let [chatId, chunk] of groupBy(messages, getKey) as Map<
+        number,
+        Message[] | number[]
+    >) {
         let chat;
         let numbers: number[] = [];
         if (typeof chunk[0] == "number") {
@@ -801,7 +805,7 @@ export async function forwardMessages(
             id: numbers,
             toPeer: entity,
             silent: silent,
-            scheduleDate: schedule
+            scheduleDate: schedule,
         });
         const result = await client.invoke(request);
         sent.push(
@@ -824,16 +828,12 @@ export async function editMessage(
         file,
         forceDocument,
         buttons,
-        schedule
+        schedule,
     }: EditMessageParams
 ) {
     entity = await client.getInputEntity(entity);
     if (formattingEntities == undefined) {
-        [text, formattingEntities] = _parseMessageText(
-            client,
-            text,
-            parseMode
-        );
+        [text, formattingEntities] = _parseMessageText(client, text, parseMode);
     }
     const request = new Api.messages.EditMessage({
         peer: entity,
@@ -843,7 +843,7 @@ export async function editMessage(
         entities: formattingEntities,
         //media: no media for now,
         replyMarkup: client.buildReplyMarkup(buttons),
-        scheduleDate: schedule
+        scheduleDate: schedule,
     });
     const result = await client.invoke(request);
     return client._getResponseMessage(request, result, entity) as Message;

+ 11 - 8
gramjs/client/telegramBaseClient.ts

@@ -2,7 +2,7 @@ import { version } from "../";
 import { IS_NODE } from "../Helpers";
 import {
     ConnectionTCPFull,
-    ConnectionTCPObfuscated
+    ConnectionTCPObfuscated,
 } from "../network/connection";
 import { Session } from "../sessions";
 import { Logger } from "../extensions";
@@ -111,9 +111,10 @@ const clientParamsDefault = {
     langCode: "en",
     systemLangCode: "en",
     baseLogger: "gramjs",
-    useWSS: typeof window !== "undefined"
-        ? window.location.protocol == "https:"
-        : false
+    useWSS:
+        typeof window !== "undefined"
+            ? window.location.protocol == "https:"
+            : false,
 };
 
 export class TelegramBaseClient {
@@ -208,13 +209,15 @@ export class TelegramBaseClient {
         this._connection = clientParams.connection;
         this._initRequest = new Api.InitConnection({
             apiId: this.apiId,
-            deviceModel: clientParams.deviceModel || os.type().toString() || "Unknown",
-            systemVersion: clientParams.systemVersion || os.release().toString() || "1.0",
+            deviceModel:
+                clientParams.deviceModel || os.type().toString() || "Unknown",
+            systemVersion:
+                clientParams.systemVersion || os.release().toString() || "1.0",
             appVersion: clientParams.appVersion || "1.0",
             langCode: clientParams.langCode,
             langPack: "", // this should be left empty.
             systemLangCode: clientParams.systemLangCode,
-            proxy: undefined // no proxies yet.
+            proxy: undefined, // no proxies yet.
         });
         this._eventBuilders = [];
 
@@ -275,7 +278,7 @@ export class TelegramBaseClient {
                 (promise: any) => {
                     return promise.then((sender: any) => sender.disconnect());
                 }
-            )
+            ),
         ]);
 
         this._eventBuilders = [];

+ 5 - 6
gramjs/client/updates.ts

@@ -33,7 +33,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];
     });
 }
@@ -53,7 +53,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;
         }
@@ -91,7 +91,7 @@ export function _processUpdate(
     update._entities = entities || new Map();
     const args = {
         update: update,
-        others: others
+        others: others,
     };
 
     _dispatchUpdate(client, args);
@@ -146,7 +146,7 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
         try {
             client._sender!.send(
                 new Api.Ping({
-                    pingId: bigInt(rnd)
+                    pingId: bigInt(rnd),
                 })
             );
         } catch (e) {
@@ -164,8 +164,7 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
         ) {
             try {
                 await client.invoke(new Api.updates.GetState());
-            } catch (e) {
-            }
+            } catch (e) {}
         }
     }
 }

+ 33 - 33
gramjs/client/uploads.ts

@@ -2,7 +2,7 @@ import { Api } from "../tl";
 
 import { TelegramClient } from "./TelegramClient";
 import { generateRandomBytes, readBigIntFromBuffer, sleep } from "../Helpers";
-import { getAppropriatedPartSize} from "../Utils";
+import { getAppropriatedPartSize } from "../Utils";
 import { EntityLike, FileLike, MarkupLike, MessageIDLike } from "../define";
 import path from "path";
 import { promises as fs } from "fs";
@@ -104,16 +104,16 @@ export async function uploadFile(
                     await sender.send(
                         isLarge
                             ? new Api.upload.SaveBigFilePart({
-                                fileId,
-                                filePart: j,
-                                fileTotalParts: partCount,
-                                bytes
-                            })
+                                  fileId,
+                                  filePart: j,
+                                  fileTotalParts: partCount,
+                                  bytes,
+                              })
                             : new Api.upload.SaveFilePart({
-                                fileId,
-                                filePart: j,
-                                bytes
-                            })
+                                  fileId,
+                                  filePart: j,
+                                  bytes,
+                              })
                     );
 
                     if (onProgress) {
@@ -132,7 +132,7 @@ export async function uploadFile(
                 await Promise.all(sendingParts),
                 sleep(UPLOAD_TIMEOUT * workers).then(() =>
                     Promise.reject(new Error("TIMEOUT"))
-                )
+                ),
             ]);
         } catch (err) {
             if (err.message === "TIMEOUT") {
@@ -146,16 +146,16 @@ export async function uploadFile(
     }
     return isLarge
         ? new Api.InputFileBig({
-            id: fileId,
-            parts: partCount,
-            name
-        })
+              id: fileId,
+              parts: partCount,
+              name,
+          })
         : new Api.InputFile({
-            id: fileId,
-            parts: partCount,
-            name,
-            md5Checksum: "" // This is not a "flag", so not sure if we can make it optional.
-        });
+              id: fileId,
+              parts: partCount,
+              name,
+              md5Checksum: "", // This is not a "flag", so not sure if we can make it optional.
+          });
 }
 
 /**
@@ -247,7 +247,7 @@ async function _fileToMedia(
         supportsStreaming = false,
         mimeType,
         asImage,
-        workers = 1
+        workers = 1,
     }: FileToMediaInterface
 ): Promise<{
     fileHandle?: any;
@@ -277,15 +277,15 @@ async function _fileToMedia(
                     forceDocument: forceDocument,
                     voiceNote: voiceNote,
                     videoNote: videoNote,
-                    supportsStreaming: supportsStreaming
+                    supportsStreaming: supportsStreaming,
                 }),
-                image: asImage
+                image: asImage,
             };
         } catch (e) {
             return {
                 fileHandle: undefined,
                 media: undefined,
-                image: isImage
+                image: isImage,
             };
         }
     }
@@ -321,7 +321,7 @@ async function _fileToMedia(
         fileHandle = await uploadFile(client, {
             file: createdFile,
             onProgress: progressCallback,
-            workers: workers
+            workers: workers,
         });
     } else if (file.startsWith("https://") || file.startsWith("http://")) {
         if (asImage) {
@@ -339,7 +339,7 @@ async function _fileToMedia(
         );
     } else if (asImage) {
         media = new Api.InputMediaUploadedPhoto({
-            file: fileHandle
+            file: fileHandle,
         });
     } else {
         // @ts-ignore
@@ -350,7 +350,7 @@ async function _fileToMedia(
             voiceNote: voiceNote,
             videoNote: videoNote,
             supportsStreaming: supportsStreaming,
-            thumb: thumb
+            thumb: thumb,
         });
         attributes = res.attrs;
         mimeType = res.mimeType;
@@ -389,7 +389,7 @@ async function _fileToMedia(
             }
             uploadedThumb = await uploadFile(client, {
                 file: uploadedThumb,
-                workers: 1
+                workers: 1,
             });
         }
         media = new Api.InputMediaUploadedDocument({
@@ -397,13 +397,13 @@ async function _fileToMedia(
             mimeType: mimeType,
             attributes: attributes,
             thumb: uploadedThumb,
-            forceFile: forceDocument && !isImage
+            forceFile: forceDocument && !isImage,
         });
     }
     return {
         fileHandle: fileHandle,
         media: media,
-        image: asImage
+        image: asImage,
     };
 }
 
@@ -428,7 +428,7 @@ export async function sendFile(
         silent,
         supportsStreaming = false,
         scheduleDate,
-        workers = 1
+        workers = 1,
     }: SendFileInterface
 ) {
     if (!file) {
@@ -461,7 +461,7 @@ export async function sendFile(
         voiceNote: voiceNote,
         videoNote: videoNote,
         supportsStreaming: supportsStreaming,
-        workers: workers
+        workers: workers,
     });
     if (media == undefined) {
         throw new Error(`Cannot use ${file} as file.`);
@@ -476,7 +476,7 @@ export async function sendFile(
         replyMarkup: markup,
         silent: silent,
         scheduleDate: scheduleDate,
-        clearDraft: clearDraft
+        clearDraft: clearDraft,
     });
     // todo get message
     const result = client.invoke(request);

+ 25 - 32
gramjs/client/users.ts

@@ -137,7 +137,6 @@ export async function getEntity(
         entityArray = entity;
     } else {
         entityArray.push(entity);
-
     }
 
     const inputs = [];
@@ -151,13 +150,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 +164,7 @@ export async function getEntity(
     if (users.length) {
         users = await client.invoke(
             new Api.users.GetUsers({
-                id: users
+                id: users,
             })
         );
     }
@@ -222,8 +220,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')
@@ -237,8 +234,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)) {
@@ -252,8 +248,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));
@@ -269,9 +264,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)) {
@@ -286,7 +281,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 {
@@ -295,9 +290,9 @@ export async function getInputEntity(
                     id: [
                         new Api.InputChannel({
                             channelId: peer.channelId,
-                            accessHash: bigInt.zero
-                        })
-                    ]
+                            accessHash: bigInt.zero,
+                        }),
+                    ],
                 })
             );
 
@@ -311,8 +306,8 @@ export async function getInputEntity(
     throw new Error(
         `Could not find the input entity for ${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."
     );
 }
 
@@ -325,7 +320,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)) {
@@ -339,7 +334,7 @@ export async function _getEntityFromString(
             if (e.message === "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;
@@ -351,13 +346,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;
@@ -421,7 +416,7 @@ export async function _getPeer(client: TelegramClient, peer: EntityLike) {
     return new cls({
         userId: i,
         channelId: i,
-        chatId: i
+        chatId: i,
     });
 }
 
@@ -434,13 +429,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,
     });
 }
 
@@ -452,10 +446,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),
     });
 }
 

+ 12 - 7
gramjs/events/NewMessage.ts

@@ -1,11 +1,16 @@
-import { _intoIdSet, DefaultEventInterface, EventBuilder, EventCommon } from "./common";
+import {
+    _intoIdSet,
+    DefaultEventInterface,
+    EventBuilder,
+    EventCommon,
+} from "./common";
 import type { Entity, EntityLike } from "../define";
 import type { TelegramClient } from "..";
 import { Api } from "../tl";
 import { Message } from "../tl/patched";
 import type { Message as CustomMessage } from "../tl/custom/message";
 
-export interface NewMessageInterface extends DefaultEventInterface{
+export interface NewMessageInterface extends DefaultEventInterface {
     func?: { (event: NewMessageEvent): boolean };
     /**
      * If set to `true`, only **incoming** messages will be handled.
@@ -84,7 +89,7 @@ export class NewMessage extends EventBuilder {
             fromUsers,
             forwards,
             pattern,
-            blacklistChats = false
+            blacklistChats = false,
         } = newMessageParams;
         if (incoming && outgoing) {
             incoming = outgoing = undefined;
@@ -108,7 +113,7 @@ export class NewMessage extends EventBuilder {
             outgoing,
             fromUsers,
             forwards,
-            pattern
+            pattern,
         ].every((v) => v == undefined);
     }
 
@@ -149,7 +154,7 @@ export class NewMessage extends EventBuilder {
                     fwdFrom: update.fwdFrom,
                     viaBotId: update.viaBotId,
                     replyTo: update.replyTo,
-                    entities: update.entities
+                    entities: update.entities,
                     // ttlPeriod:update.ttlPeriod
                 }),
                 update
@@ -169,7 +174,7 @@ export class NewMessage extends EventBuilder {
                     fwdFrom: update.fwdFrom,
                     viaBotId: update.viaBotId,
                     replyTo: update.replyTo,
-                    entities: update.entities
+                    entities: update.entities,
                     // ttlPeriod:update.ttlPeriod
                 }),
                 update
@@ -215,7 +220,7 @@ export class NewMessageEvent extends EventCommon {
         super({
             msgId: message.id,
             chatPeer: message.peerId,
-            broadcast: message.post
+            broadcast: message.post,
         });
         this.originalUpdate = originalUpdate;
         this.message = message;

+ 7 - 7
gramjs/events/common.ts

@@ -26,21 +26,21 @@ export async function _intoIdSet(
                 result.add(
                     utils.getPeerId(
                         new Api.PeerUser({
-                            userId: chat
+                            userId: chat,
                         })
                     )
                 );
                 result.add(
                     utils.getPeerId(
                         new Api.PeerChat({
-                            chatId: chat
+                            chatId: chat,
                         })
                     )
                 );
                 result.add(
                     utils.getPeerId(
                         new Api.PeerChannel({
-                            channelId: chat
+                            channelId: chat,
                         })
                     )
                 );
@@ -146,10 +146,10 @@ export class EventCommon extends ChatGetter {
     _messageId?: number;
 
     constructor({
-                    chatPeer = undefined,
-                    msgId = undefined,
-                    broadcast = undefined
-                }: EventCommonInterface) {
+        chatPeer = undefined,
+        msgId = undefined,
+        broadcast = undefined,
+    }: EventCommonInterface) {
         super({ chatPeer, broadcast });
         this._entities = new Map();
         this._client = undefined;

+ 1 - 1
gramjs/extensions/markdown.ts

@@ -1,5 +1,5 @@
 import { Api } from "../tl";
-import { DEFAULT_DELIMITERS} from "../client/messageParse";
+import { DEFAULT_DELIMITERS } from "../client/messageParse";
 
 export class MarkdownParser {
     // TODO maybe there is a better way :shrug:

+ 12 - 8
gramjs/network/MTProtoSender.ts

@@ -30,6 +30,7 @@ import {
     RPCMessageToError,
 } from "../errors";
 import { Connection, UpdateConnectionState } from "./";
+import type { TelegramClient } from "..";
 
 interface DEFAULT_OPTIONS {
     logger: any;
@@ -43,9 +44,7 @@ interface DEFAULT_OPTIONS {
     isMainSender: boolean;
     dcId: number;
     senderCallback?: any;
-}
-
-{
+    client: TelegramClient;
 }
 
 export class MTProtoSender {
@@ -69,7 +68,10 @@ export class MTProtoSender {
     private _connectTimeout: null;
     private _autoReconnect: boolean;
     private readonly _authKeyCallback: any;
-    private readonly _updateCallback: any;
+    private readonly _updateCallback: (
+        client: TelegramClient,
+        update: Api.TypeUpdate | number
+    ) => void;
     private readonly _autoReconnectCallback?: any;
     private readonly _senderCallback: any;
     private readonly _isMainSender: boolean;
@@ -85,6 +87,7 @@ export class MTProtoSender {
     private readonly _pendingAck: Set<any>;
     private readonly _lastAcks: any[];
     private readonly _handlers: any;
+    private readonly _client: TelegramClient;
 
     /**
      * @param authKey
@@ -104,6 +107,7 @@ export class MTProtoSender {
         this._autoReconnectCallback = args.autoReconnectCallback;
         this._isMainSender = args.isMainSender;
         this._senderCallback = args.senderCallback;
+        this._client = args.client;
 
         /**
          * Whether the user has explicitly connected or disconnected.
@@ -335,7 +339,7 @@ export class MTProtoSender {
             return;
         }
         if (this._updateCallback) {
-            this._updateCallback(-1);
+            this._updateCallback(this._client, -1);
         }
         this._log.info(
             "Disconnecting from %s...".replace(
@@ -450,7 +454,7 @@ export class MTProtoSender {
                     this._log.info("Broken authorization key; resetting");
                     if (this._updateCallback && this._isMainSender) {
                         // 0 == broken
-                        this._updateCallback(0);
+                        this._updateCallback(this._client, 0);
                     } else if (this._senderCallback && !this._isMainSender) {
                         // Deletes the current sender from the object
                         this._senderCallback(this._dcId);
@@ -636,7 +640,7 @@ export class MTProtoSender {
         }
         this._log.debug("Handling update " + message.obj.className);
         if (this._updateCallback) {
-            this._updateCallback(message.obj);
+            this._updateCallback(this._client, message.obj);
         }
     }
 
@@ -872,7 +876,7 @@ export class MTProtoSender {
                     await this._autoReconnectCallback();
                 }
                 if (this._updateCallback) {
-                    this._updateCallback(1);
+                    this._updateCallback(this._client, 1);
                 }
 
                 break;

+ 1 - 1
gramjs/sessions/StringSession.ts

@@ -102,7 +102,7 @@ export class StringSession extends MemorySession {
                     addressLengthBuffer,
                     addressBuffer,
                     portBuffer,
-                    key
+                    key,
                 ])
             )
         );

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 13348 - 12823
gramjs/tl/api.d.ts


+ 4 - 1
gramjs/tl/api.js

@@ -232,7 +232,10 @@ function compareType(value, type) {
             correct = typeof value === type;
             break;
         case "bigInt":
-            correct = bigInt.isInstance(value) || typeof value==="bigint" || value === undefined;
+            correct =
+                bigInt.isInstance(value) ||
+                typeof value === "bigint" ||
+                value === undefined;
             break;
         case "true":
             // true value is always correct

+ 4 - 4
gramjs/tl/custom/button.ts

@@ -44,7 +44,7 @@ export class Button {
         }
         return new Api.KeyboardButtonCallback({
             text: text,
-            data: data
+            data: data,
         });
     }
 
@@ -52,14 +52,14 @@ export class Button {
         return new Api.KeyboardButtonSwitchInline({
             text,
             query,
-            samePeer
+            samePeer,
         });
     }
 
     static url(text: string, url?: string) {
         return new Api.KeyboardButtonUrl({
             text: text,
-            url: url || text
+            url: url || text,
         });
     }
 
@@ -75,7 +75,7 @@ export class Button {
             url: url || text,
             bot: utils.getInputPeer(bot || new Api.InputUserSelf()),
             requestWriteAccess: writeAccess,
-            fwdText: fwdText
+            fwdText: fwdText,
         });
     }
 

+ 5 - 7
gramjs/tl/custom/draft.ts

@@ -30,18 +30,16 @@ export class Draft {
         this._entity = entity;
         this._inputEntity = entity ? getInputPeer(entity) : undefined;
         if (!draft || !(draft instanceof Api.DraftMessage)) {
-            draft
-                = new Api.DraftMessage({
+            draft = new Api.DraftMessage({
                 message: "",
-                date: -1
+                date: -1,
             });
         }
         if (!(draft instanceof Api.DraftMessageEmpty)) {
             this.linkPreview = !draft.noWebpage;
-            this._text = client.parseMode ? client.parseMode.unparse(
-                draft.message,
-                draft.entities|| [],
-            ) : draft.message;
+            this._text = client.parseMode
+                ? client.parseMode.unparse(draft.message, draft.entities || [])
+                : draft.message;
             this._rawText = draft.message;
             this.date = draft.date;
             this.replyToMsgId = draft.replyToMsgId;

+ 1 - 1
gramjs/tl/custom/inlineResult.ts

@@ -96,7 +96,7 @@ export class InlineResult {
             silent: silent,
             clearDraft: clearDraft,
             hideVia: hideVia,
-            replyToMsgId: replyId
+            replyToMsgId: replyId,
         });
         return await this._client.invoke(request);
     }

+ 5 - 1
gramjs/tl/custom/inlineResults.ts

@@ -23,7 +23,11 @@ export class InlineResults extends Array<InlineResult> {
         original: Api.messages.TypeBotResults,
         entity?: EntityLike
     ) {
-        super(...original.results.map((res) => new InlineResult(client, res, original.queryId, entity)));
+        super(
+            ...original.results.map(
+                (res) => new InlineResult(client, res, original.queryId, entity)
+            )
+        );
         this.result = original;
         this.queryId = original.queryId;
         this.cacheTime = original.cacheTime;

+ 45 - 47
gramjs/tl/custom/message.ts

@@ -53,7 +53,6 @@ interface MessageBaseInterface {
  * which means you have access to all their sender and chat properties and methods.
  */
 export class Message extends Mixin(SenderGetter, ChatGetter) {
-
     /**
      * Whether the message is outgoing (i.e. you sent it from
      * another session) or incoming (i.e. someone else sent it).
@@ -240,41 +239,41 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
     }
 
     constructor({
-                    id,
-                    peerId = undefined,
-                    date = undefined,
-
-                    out = undefined,
-                    mentioned = undefined,
-                    mediaUnread = undefined,
-                    silent = undefined,
-                    post = undefined,
-                    fromId = undefined,
-                    replyTo = undefined,
-
-                    message = undefined,
-
-                    fwdFrom = undefined,
-                    viaBotId = undefined,
-                    media = undefined,
-                    replyMarkup = undefined,
-                    entities = undefined,
-                    views = undefined,
-                    editDate = undefined,
-                    postAuthor = undefined,
-                    groupedId = undefined,
-                    fromScheduled = undefined,
-                    legacy = undefined,
-                    editHide = undefined,
-                    pinned = undefined,
-                    restrictionReason = undefined,
-                    forwards = undefined,
-                    replies = undefined,
-
-                    action = undefined,
-                    ttlPeriod = undefined,
-                    _entities = new Map<number, Entity>()
-                }: MessageBaseInterface) {
+        id,
+        peerId = undefined,
+        date = undefined,
+
+        out = undefined,
+        mentioned = undefined,
+        mediaUnread = undefined,
+        silent = undefined,
+        post = undefined,
+        fromId = undefined,
+        replyTo = undefined,
+
+        message = undefined,
+
+        fwdFrom = undefined,
+        viaBotId = undefined,
+        media = undefined,
+        replyMarkup = undefined,
+        entities = undefined,
+        views = undefined,
+        editDate = undefined,
+        postAuthor = undefined,
+        groupedId = undefined,
+        fromScheduled = undefined,
+        legacy = undefined,
+        editHide = undefined,
+        pinned = undefined,
+        restrictionReason = undefined,
+        forwards = undefined,
+        replies = undefined,
+
+        action = undefined,
+        ttlPeriod = undefined,
+        _entities = new Map<number, Entity>(),
+    }: MessageBaseInterface) {
         if (!id) throw new Error("id is a required attribute for Message");
         let senderId = undefined;
         if (fromId) {
@@ -392,10 +391,10 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                     entities.get(
                         utils.getPeerId(
                             new Api.PeerChannel({
-                                channelId: this.action.inviterId
+                                channelId: this.action.inviterId,
                             })
                         )
-                    )
+                    ),
                 ];
             } else if (
                 this.action instanceof Api.MessageActionChannelMigrateFrom
@@ -405,7 +404,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                         utils.getPeerId(
                             new Api.PeerChat({ chatId: this.action.chatId })
                         )
-                    )
+                    ),
                 ];
             }
         }
@@ -481,7 +480,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
         } catch (e) {
             this._client._log.error(
                 "Got error while trying to finish init message with id " +
-                this.id
+                    this.id
             );
             if (this._client._log.canSend("error")) {
                 console.error(e);
@@ -683,7 +682,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
     get toId() {
         if (this._client && !this.out && this.isPrivate) {
             return new Api.PeerUser({
-                userId: _selfId(this._client)!
+                userId: _selfId(this._client)!,
             });
         }
         return this.peerId;
@@ -693,7 +692,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
         let ent = this.entities;
         if (!ent || ent.length == 0) return;
 
-        if (cls){
+        if (cls) {
             ent = ent.filter((v: any) => v instanceof cls);
         }
 
@@ -716,7 +715,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                 await this._client.getMessages(
                     this.isChannel ? await this.getInputChat() : undefined,
                     {
-                        ids: new Api.InputMessageReplyTo({ id: this.id })
+                        ids: new Api.InputMessageReplyTo({ id: this.id }),
                     }
                 )
             )[0];
@@ -730,7 +729,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
                     await this._client.getMessages(
                         this.isChannel ? this._inputChat : undefined,
                         {
-                            ids: this.replyToMsgId
+                            ids: this.replyToMsgId,
                         }
                     )
                 )[0];
@@ -763,7 +762,7 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
             entity = await this._client.getInputEntity(entity);
             const params = {
                 messages: [this.id],
-                fromPeer: (await this.getInputChat())!
+                fromPeer: (await this.getInputChat())!,
             };
 
             return this._client.forwardMessages(entity, params);
@@ -928,5 +927,4 @@ export class Message extends Mixin(SenderGetter, ChatGetter) {
     }
 }
 
-export interface Message extends ChatGetter, SenderGetter {
-}
+export interface Message extends ChatGetter, SenderGetter {}

+ 1 - 1
package.json

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

+ 3 - 5
type_doc.js

@@ -6,11 +6,9 @@ module.exports = {
     "**/example/**/*",
     "**/extensions/**/*",
     "**/*+(Password|Version|RequestIter|entityCache).ts",
-    "**/*.js"
-  ],
-  sort: [
-    "source-order"
+    "**/*.js",
   ],
+  sort: ["source-order"],
   excludeExternals: true,
-  excludePrivate: true
+  excludePrivate: true,
 };

Vissa filer visades inte eftersom för många filer har ändrats