瀏覽代碼

Update to layer 135

painor 3 年之前
父節點
當前提交
1a974da934

+ 19 - 7
gramjs/Helpers.ts

@@ -103,10 +103,10 @@ export function addSurrogate(text: string) {
  * @returns {Buffer}
  */
 export function toSignedLittleBuffer(
-    big: bigInt.BigInteger,
+    big: bigInt.BigInteger | string | number,
     number = 8
 ): Buffer {
-    const bigNumber = bigInt(big);
+    const bigNumber = returnBigInt(big);
     const byteArray = [];
     for (let i = 0; i < number; i++) {
         byteArray[i] = bigNumber.shiftRight(8 * i).and(255);
@@ -393,21 +393,33 @@ export function getByteArray(
     );
 }
 
+export function returnBigInt(num: bigInt.BigInteger | string | number) {
+    if (bigInt.isInstance(num)) {
+        return num;
+    }
+    if (typeof num == "number") {
+        return bigInt(num);
+    }
+    return bigInt(num);
+}
+
 /**
  * Helper function to return the smaller big int in an array
  * @param arrayOfBigInts
  */
-export function getMinBigInt(arrayOfBigInts: bigInt.BigInteger[]) {
+export function getMinBigInt(
+    arrayOfBigInts: (bigInt.BigInteger | string)[]
+): bigInt.BigInteger {
     if (arrayOfBigInts.length == 0) {
         return bigInt.zero;
     }
     if (arrayOfBigInts.length == 1) {
-        return arrayOfBigInts[0];
+        return returnBigInt(arrayOfBigInts[0]);
     }
-    let smallest = arrayOfBigInts[0];
+    let smallest = returnBigInt(arrayOfBigInts[0]);
     for (let i = 1; i < arrayOfBigInts.length; i++) {
-        if (arrayOfBigInts[i] < smallest) {
-            smallest = arrayOfBigInts[i];
+        if (returnBigInt(arrayOfBigInts[i]).lesser(smallest)) {
+            smallest = returnBigInt(arrayOfBigInts[i]);
         }
     }
     return smallest;

+ 47 - 27
gramjs/Utils.ts

@@ -20,6 +20,7 @@ export function* chunks<T>(arr: T[], size = 100): Generator<T[]> {
 
 import TypeInputFile = Api.TypeInputFile;
 import { HTMLParser } from "./extensions/html";
+import { returnBigInt } from "./Helpers";
 
 const USERNAME_RE = new RegExp(
     "@|(?:https?:\\/\\/)?(?:www\\.)?" +
@@ -145,7 +146,7 @@ export function getInputPeer(
         return new Api.InputPeerEmpty();
     }
     if (entity instanceof Api.UserFull) {
-        return getInputPeer(entity.user);
+        return getInputPeer(entity.id);
     }
 
     if (entity instanceof Api.ChatFull) {
@@ -179,8 +180,8 @@ export function _photoSizeByteCount(size: Api.TypePhotoSize) {
 }
 
 export function _getEntityPair(
-    entityId: number,
-    entities: Map<number, Entity>,
+    entityId: string,
+    entities: Map<string, Entity>,
     cache: EntityCache,
     getInputPeerFunction: any = getInputPeer
 ): [Entity?, Api.TypeInputPeer?] {
@@ -219,7 +220,12 @@ export function getInnerText(text: string, entities: Api.TypeMessageEntity[]) {
  * @returns {InputChannel|*}
  */
 export function getInputChannel(entity: EntityLike) {
-    if (typeof entity === "string" || typeof entity == "number") {
+    if (
+        typeof entity === "string" ||
+        typeof entity == "number" ||
+        typeof entity == "bigint" ||
+        bigInt.isInstance(entity)
+    ) {
         _raiseCastFail(entity, "InputChannel");
     }
     if (entity.SUBCLASS_OF_ID === undefined) {
@@ -261,7 +267,12 @@ export function getInputChannel(entity: EntityLike) {
  * @param entity
  */
 export function getInputUser(entity: EntityLike): Api.TypeInputUser {
-    if (typeof entity === "string" || typeof entity == "number") {
+    if (
+        typeof entity === "string" ||
+        typeof entity == "number" ||
+        typeof entity == "bigint" ||
+        bigInt.isInstance(entity)
+    ) {
         _raiseCastFail(entity, "InputUser");
     }
 
@@ -292,9 +303,8 @@ export function getInputUser(entity: EntityLike): Api.TypeInputUser {
     ) {
         return new Api.InputUserEmpty();
     }
-
     if (entity instanceof Api.UserFull) {
-        return getInputUser(entity.user);
+        return getInputUser(entity);
     }
 
     if (entity instanceof Api.InputPeerUser) {
@@ -978,7 +988,7 @@ export function getPeer(peer: EntityLike | any) {
         _raiseCastFail(peer, "peer");
     }
     try {
-        if (typeof peer === "number") {
+        if (bigInt.isInstance(peer)) {
             const res = resolveId(peer);
             if (res[1] === Api.PeerChannel) {
                 return new Api.PeerChannel({ channelId: res[0] });
@@ -1059,10 +1069,13 @@ export function sanitizeParseMode(
  * @param peer
  * @param addMark
  */
-export function getPeerId(peer: EntityLike, addMark = true): number {
+export function getPeerId(peer: EntityLike, addMark = true): string {
+    if (typeof peer == "string" && parseID(peer)) {
+        peer = returnBigInt(peer);
+    }
     // First we assert it's a Peer TLObject, or early return for integers
-    if (typeof peer == "number") {
-        return addMark ? peer : resolveId(peer)[0];
+    if (bigInt.isInstance(peer)) {
+        return addMark ? peer.toString() : resolveId(peer)[0].toString();
     }
     // Tell the user to use their client to resolve InputPeerSelf if we got one
     if (peer instanceof Api.InputPeerSelf) {
@@ -1075,26 +1088,23 @@ export function getPeerId(peer: EntityLike, addMark = true): number {
         _raiseCastFail(peer, "int");
     }
     if (peer instanceof Api.PeerUser) {
-        return peer.userId;
+        return peer.userId.toString();
     } else if (peer instanceof Api.PeerChat) {
         // Check in case the user mixed things up to avoid blowing up
-        if (!(0 < peer.chatId && peer.chatId <= 0x7fffffff)) {
-            peer.chatId = resolveId(peer.chatId)[0];
-        }
-
-        return addMark ? -peer.chatId : peer.chatId;
+        peer.chatId = resolveId(returnBigInt(peer.chatId))[0];
+        return addMark
+            ? peer.chatId.negate().toString()
+            : peer.chatId.toString();
     } else if (typeof peer == "object" && "channelId" in peer) {
         // if (peer instanceof Api.PeerChannel)
         // Check in case the user mixed things up to avoid blowing up
-        if (!(0 < peer.channelId && peer.channelId <= 0x7fffffff)) {
-            peer.channelId = resolveId(peer.channelId)[0];
-        }
+        peer.channelId = resolveId(returnBigInt(peer.channelId))[0];
         if (!addMark) {
-            return peer.channelId;
+            return peer.channelId.toString();
         }
         // Concat -100 through math tricks, .to_supergroup() on
         // Madeline IDs will be strictly positive -> log works.
-        return -(1000000000000 + peer.channelId);
+        return "-100" + peer.channelId.toString();
     }
     _raiseCastFail(peer, "int");
 }
@@ -1104,12 +1114,12 @@ export function getPeerId(peer: EntityLike, addMark = true): number {
  * @param markedId
  */
 export function resolveId(
-    markedId: number
+    markedId: bigInt.BigInteger
 ): [
-    number,
+    bigInt.BigInteger,
     typeof Api.PeerUser | typeof Api.PeerChannel | typeof Api.PeerChat
 ] {
-    if (markedId >= 0) {
+    if (markedId.greaterOrEquals(bigInt.zero)) {
         return [markedId, Api.PeerUser];
     }
 
@@ -1119,9 +1129,9 @@ export function resolveId(
     // two zeroes.
     const m = markedId.toString().match(/-100([^0]\d*)/);
     if (m) {
-        return [parseInt(m[1]), Api.PeerChannel];
+        return [bigInt(m[1]), Api.PeerChannel];
     }
-    return [-markedId, Api.PeerChat];
+    return [markedId.negate(), Api.PeerChat];
 }
 
 /**
@@ -1178,6 +1188,16 @@ export function parsePhone(phone: string | number) {
     return !isNaN(parseInt(phone)) ? phone : undefined;
 }
 
+/**
+ * Parses a string ID into a big int
+ * @param id
+ */
+export function parseID(id: string) {
+    const isValid = /^([0-9][0-9]*)$/.test(id);
+
+    return isValid ? bigInt(id) : undefined;
+}
+
 export function resolveInviteLink(link: string): [number, number, number] {
     throw new Error("not implemented");
 }

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.11.1";
+export const version = "2.0.0";

+ 1 - 1
gramjs/client/chats.ts

@@ -192,7 +192,7 @@ export class _ParticipantsIter extends RequestIter {
                         }),
                     offset: 0,
                     limit: _MAX_PARTICIPANTS_CHUNK_SIZE,
-                    hash: 0,
+                    hash: bigInt.zero,
                 })
             );
         } else if (ty == helpers._EntityType.CHAT) {

+ 3 - 2
gramjs/client/dialogs.ts

@@ -4,6 +4,7 @@ import { TelegramClient, utils } from "../index";
 import { Dialog } from "../tl/custom/dialog";
 import { DateLike, EntityLike } from "../define";
 import { TotalList } from "../Helpers";
+import bigInt from "big-integer";
 
 const _MAX_CHUNK_SIZE = 100;
 
@@ -56,7 +57,7 @@ export class _DialogsIter extends RequestIter {
             offsetId,
             offsetPeer,
             limit: 1,
-            hash: 0,
+            hash: bigInt.zero,
             excludePinned: ignorePinned,
             folderId: folder,
         });
@@ -91,7 +92,7 @@ export class _DialogsIter extends RequestIter {
         } else {
             this.total = r.dialogs.length;
         }
-        const entities = new Map<number, Api.TypeUser | Api.TypeChat>();
+        const entities = new Map<string, Api.TypeUser | Api.TypeChat>();
         const messages = new Map<string, Api.Message>();
 
         for (const entity of [...r.users, ...r.chats]) {

+ 15 - 11
gramjs/client/messages.ts

@@ -15,11 +15,12 @@ import {
     isArrayLike,
     groupBy,
 } from "../Helpers";
-import { getMessageId, getPeerId } from "../Utils";
+import { getMessageId, getPeerId, parseID } from "../Utils";
 import type { TelegramClient } from "../";
 import { utils } from "../";
 import { _parseMessageText } from "./messageParse";
 import { _getPeer } from "./users";
+import bigInt from "big-integer";
 
 const _MAX_CHUNK_SIZE = 100;
 
@@ -43,7 +44,7 @@ export class _MessagesIter extends RequestIter {
         | Api.messages.GetReplies
         | Api.messages.GetHistory
         | Api.messages.Search;
-    fromId?: number;
+    fromId?: string | bigInt.BigInteger;
     addOffset?: number;
     maxId?: number;
     minId?: number;
@@ -129,7 +130,7 @@ export class _MessagesIter extends RequestIter {
                 limit: 0,
                 maxId: 0,
                 minId: 0,
-                hash: 0,
+                hash: bigInt.zero,
             });
         } else if (
             search !== undefined ||
@@ -153,7 +154,7 @@ export class _MessagesIter extends RequestIter {
                 limit: 0,
                 maxId: 0,
                 minId: 0,
-                hash: 0,
+                hash: bigInt.zero,
                 fromId: fromUser,
             });
             if (
@@ -178,7 +179,7 @@ export class _MessagesIter extends RequestIter {
                 minId: 0,
                 maxId: 0,
                 addOffset: addOffset,
-                hash: 0,
+                hash: bigInt.zero,
             });
         }
         if (this.limit <= 0) {
@@ -238,7 +239,7 @@ export class _MessagesIter extends RequestIter {
             ? (r.messages.reverse() as unknown as Api.Message[])
             : (r.messages as unknown as Api.Message[]);
         for (const message of messages) {
-            if (this.fromId && message.senderId != this.fromId) {
+            if (this.fromId && message.senderId?.notEquals(this.fromId)) {
                 continue;
             }
             if (!this._messageInRange(message)) {
@@ -796,19 +797,22 @@ export async function forwardMessages(
         messages = [messages];
     }
     entity = await client.getInputEntity(entity);
-    let fromPeerId: number | undefined;
+    let fromPeerId: string | undefined;
     if (fromPeer) {
         fromPeer = await client.getInputEntity(fromPeer);
         fromPeerId = await client.getPeerId(fromPeer);
     }
-    const getKey = (m: number | Api.Message) => {
-        if (typeof m == "number") {
+    const getKey = (m: string | Api.Message) => {
+        if (m instanceof Api.Message) {
+            return m.chatId;
+        }
+        let msgId = parseID(m);
+
+        if (msgId) {
             if (fromPeerId !== undefined) {
                 return fromPeerId;
             }
             throw new Error("fromPeer must be given if integer IDs are used");
-        } else if (m instanceof Api.Message) {
-            return m.chatId;
         } else {
             throw new Error(`Cannot forward ${m}`);
         }

+ 50 - 39
gramjs/client/users.ts

@@ -1,7 +1,13 @@
 import { Api } from "../tl";
 import type { Entity, EntityLike } from "../define";
-import { getPeerId as peerUtils } from "../Utils";
-import { _entityType, _EntityType, sleep, isArrayLike } from "../Helpers";
+import { getPeerId as peerUtils, parseID } from "../Utils";
+import {
+    _entityType,
+    _EntityType,
+    sleep,
+    isArrayLike,
+    returnBigInt,
+} from "../Helpers";
 import { errors, utils } from "../";
 import type { TelegramClient } from "../";
 import bigInt from "big-integer";
@@ -173,7 +179,7 @@ export async function getEntity(
             await client.invoke(new Api.channels.GetChannels({ id: channels }))
         ).chats;
     }
-    const idEntity = new Map<number, any>();
+    const idEntity = new Map<string, any>();
 
     for (const user of users) {
         idEntity.set(peerUtils(user), user);
@@ -218,10 +224,30 @@ export async function getInputEntity(
     } catch (e) {}
     // Next in priority is having a peer (or its ID) cached in-memory
     try {
+        if (typeof peer == "string") {
+            const valid = parseID(peer);
+            if (valid) {
+                const res = client._entityCache.get(peer);
+                if (res) {
+                    return res;
+                }
+            }
+        }
+        if (
+            typeof peer === "number" ||
+            typeof peer === "bigint" ||
+            bigInt.isInstance(peer)
+        ) {
+            const res = client._entityCache.get(peer);
+            if (res) {
+                return res;
+            }
+        }
         // 0x2d45687 == crc32(b'Peer')
         if (
-            typeof peer !== "string" &&
-            (typeof peer === "number" || peer.SUBCLASS_OF_ID === 0x2d45687)
+            typeof peer == "object" &&
+            !bigInt.isInstance(peer) &&
+            peer.SUBCLASS_OF_ID === 0x2d45687
         ) {
             const res = client._entityCache.get(peer);
             if (res) {
@@ -244,10 +270,6 @@ export async function getInputEntity(
         }
         // eslint-disable-next-line no-empty
     } catch (e) {}
-    // Only network left to try
-    if (typeof peer === "string") {
-        return utils.getInputPeer(await _getEntityFromString(client, peer));
-    }
     // If we're a bot and the user has messaged us privately users.getUsers
     // will work with accessHash = 0. Similar for channels.getChannels.
     // If we're not a bot but the user is in our contacts, it seems to work
@@ -311,30 +333,9 @@ export async function _getEntityFromString(
     client: TelegramClient,
     string: string
 ) {
-    const phone = utils.parsePhone(string);
-    if (phone) {
-        try {
-            const result = await client.invoke(
-                new Api.contacts.GetContacts({
-                    hash: 0,
-                })
-            );
-            if (!(result instanceof Api.contacts.ContactsNotModified)) {
-                for (const user of result.users) {
-                    if (!(user instanceof Api.User) || user.phone === phone) {
-                        return user;
-                    }
-                }
-            }
-        } catch (e: any) {
-            if (e.errorMessage === "BOT_METHOD_INVALID") {
-                throw new Error(
-                    "Cannot get entity by phone number as a " +
-                        "bot (try using integer IDs, not strings)"
-                );
-            }
-            throw e;
-        }
+    const id = utils.parseID(string);
+    if (id != undefined) {
+        return getInputEntity(client, id);
     } else if (["me", "this"].includes(string.toLowerCase())) {
         return client.getMe();
     } else {
@@ -389,13 +390,21 @@ export async function getPeerId(
     peer: EntityLike,
     addMark = true
 ) {
-    if (typeof peer == "number") {
-        return utils.getPeerId(peer, addMark);
-    }
     if (typeof peer == "string") {
-        peer = await client.getInputEntity(peer);
+        const valid = parseID(peer);
+        if (valid) {
+            return utils.getPeerId(peer, addMark);
+        } else {
+            peer = await client.getInputEntity(peer);
+        }
+    }
+    if (
+        typeof peer == "number" ||
+        typeof peer == "bigint" ||
+        bigInt.isInstance(peer)
+    ) {
+        return utils.getPeerId(peer, addMark);
     }
-
     if (peer.SUBCLASS_OF_ID == 0x2d45687 || peer.SUBCLASS_OF_ID == 0xc91c90b6) {
         peer = await client.getInputEntity(peer);
     }
@@ -410,7 +419,9 @@ export async function _getPeer(client: TelegramClient, peer: EntityLike) {
     if (!peer) {
         return undefined;
     }
-    const [i, cls] = utils.resolveId(await client.getPeerId(peer));
+    const [i, cls] = utils.resolveId(
+        returnBigInt(await client.getPeerId(peer))
+    );
     return new cls({
         userId: i,
         channelId: i,

+ 2 - 0
gramjs/define.d.ts

@@ -5,6 +5,7 @@ import TypeUser = Api.TypeUser;
 import TypeChat = Api.TypeChat;
 import TypeInputUser = Api.TypeInputUser;
 import TypeInputChannel = Api.TypeInputChannel;
+import bigInt from "big-integer";
 
 type ValueOf<T> = T[keyof T];
 type Phone = string;
@@ -18,6 +19,7 @@ type FullEntity =
     | Api.ChannelFull;
 type PeerLike = Api.TypePeer | Api.TypeInputPeer | Entity | FullEntity;
 type EntityLike =
+    | bigInt.BigInteger
     | Phone
     | Username
     | PeerID

+ 8 - 9
gramjs/entityCache.ts

@@ -5,7 +5,7 @@ import { isArrayLike } from "./Helpers";
 import { Api } from "./tl";
 
 export class EntityCache {
-    private cacheMap: Map<number, any>;
+    private cacheMap: Map<string, any>;
 
     constructor() {
         this.cacheMap = new Map();
@@ -36,8 +36,8 @@ export class EntityCache {
         for (const entity of entities) {
             try {
                 const pid = getPeerId(entity);
-                if (!this.cacheMap.has(pid)) {
-                    this.cacheMap.set(pid, getInputPeer(entity));
+                if (!this.cacheMap.has(pid.toString())) {
+                    this.cacheMap.set(pid.toString(), getInputPeer(entity));
                 }
             } catch (e) {}
         }
@@ -47,7 +47,7 @@ export class EntityCache {
         if (!(typeof item === "number") || item < 0) {
             let res;
             try {
-                res = this.cacheMap.get(getPeerId(item));
+                res = this.cacheMap.get(getPeerId(item).toString());
                 if (res) {
                     return res;
                 }
@@ -56,15 +56,14 @@ export class EntityCache {
             }
         }
         for (const cls of [Api.PeerUser, Api.PeerChat, Api.PeerChannel]) {
-            // TODO remove these "as"
             const result = this.cacheMap.get(
                 getPeerId(
                     new cls({
-                        userId: item as number,
-                        chatId: item as number,
-                        channelId: item as number,
+                        userId: item,
+                        chatId: item,
+                        channelId: item,
                     })
-                )
+                ).toString()
             );
             if (result) {
                 return result;

+ 1 - 1
gramjs/events/Album.ts

@@ -85,7 +85,7 @@ export class Album extends EventBuilder {
 
 export class AlbumEvent extends EventCommon {
     messages: Api.Message[];
-    originalUpdates: (Api.TypeUpdate & { _entities?: Map<number, Entity> })[];
+    originalUpdates: (Api.TypeUpdate & { _entities?: Map<string, Entity> })[];
 
     constructor(messages: Api.Message[], originalUpdates: Api.TypeUpdate[]) {
         super({

+ 8 - 9
gramjs/events/CallbackQuery.ts

@@ -1,7 +1,7 @@
 import { EntityLike } from "../define";
-import { EventBuilder, EventCommonSender } from "./common";
+import { EventBuilder, EventCommon, EventCommonSender } from "./common";
 import { Api } from "../tl";
-import { toSignedLittleBuffer } from "../Helpers";
+import { returnBigInt, toSignedLittleBuffer } from "../Helpers";
 import { TelegramClient } from "..";
 import { _getEntityPair, getInputPeer } from "../Utils";
 import { EditMessageParams, SendMessageParams } from "../client/messages";
@@ -53,7 +53,6 @@ export class CallbackQuery extends EventBuilder {
 
     build(update: Api.TypeUpdate | Api.TypeUpdates, others: any = null) {
         if (update instanceof Api.UpdateBotCallbackQuery) {
-            console.log("returning her!");
             return new CallbackQueryEvent(update, update.peer, update.msgId);
         } else if (update instanceof Api.UpdateInlineBotCallbackQuery) {
             const b = toSignedLittleBuffer(update.msgId.id, 8);
@@ -61,8 +60,8 @@ export class CallbackQuery extends EventBuilder {
             const peerId = b.readInt32LE(4);
             const peer =
                 peerId < 0
-                    ? new Api.PeerChannel({ channelId: -peerId })
-                    : new Api.PeerUser({ userId: peerId });
+                    ? new Api.PeerChannel({ channelId: returnBigInt(-peerId) })
+                    : new Api.PeerUser({ userId: returnBigInt(peerId) });
             return new CallbackQueryEvent(update, peer, msgId);
         }
     }
@@ -135,7 +134,7 @@ export class CallbackQueryEvent extends EventCommonSender {
         });
         this.query = query;
         this.patternMatch = undefined;
-        this._senderId = query.userId;
+        this._senderId = returnBigInt(query.userId);
         this._message = undefined;
         this._answered = false;
     }
@@ -143,7 +142,7 @@ export class CallbackQueryEvent extends EventCommonSender {
     _setClient(client: TelegramClient) {
         super._setClient(client);
         const [sender, inputSender] = _getEntityPair(
-            this._senderId!,
+            this._senderId!.toString(),
             this._entities,
             client._entityCache
         );
@@ -184,8 +183,8 @@ export class CallbackQueryEvent extends EventCommonSender {
     }
 
     async _refetchSender() {
-        if (this._entities.has(this._senderId!)) {
-            this._sender = this._entities.get(this._senderId!);
+        if (this._entities.has(this._senderId!.toString())) {
+            this._sender = this._entities.get(this._senderId!.toString());
         }
 
         if (!this._sender) return;

+ 1 - 1
gramjs/events/NewMessage.ts

@@ -176,7 +176,7 @@ export class NewMessage extends EventBuilder {
         }
     }
 
-    filter(event: NewMessageEvent): EventCommon | undefined {
+    filter(event: NewMessageEvent) {
         if (this._noCheck) {
             return event;
         }

+ 18 - 9
gramjs/events/common.ts

@@ -3,26 +3,33 @@ import type { Entity, EntityLike } from "../define";
 import { ChatGetter } from "../tl/custom";
 import type { TelegramClient } from "..";
 
-import { isArrayLike } from "../Helpers";
+import { isArrayLike, returnBigInt } from "../Helpers";
 import { utils } from "../";
 import { SenderGetter } from "../tl/custom/senderGetter";
+import bigInt from "big-integer";
 
 /** @hidden */
 export async function _intoIdSet(
     client: TelegramClient,
     chats: EntityLike[] | EntityLike | undefined
-): Promise<number[] | undefined> {
+): Promise<string[] | undefined> {
     if (chats == undefined) {
         return undefined;
     }
     if (!isArrayLike(chats)) {
         chats = [chats];
     }
-    const result: Set<number> = new Set<number>();
+    const result: Set<string> = new Set<string>();
     for (let chat of chats) {
-        if (typeof chat == "number") {
-            if (chat < 0) {
-                result.add(chat);
+        if (
+            typeof chat == "number" ||
+            typeof chat == "bigint" ||
+            typeof chat == "string" ||
+            bigInt.isInstance(chat)
+        ) {
+            chat = returnBigInt(chat);
+            if (chat.lesser(0)) {
+                result.add(chat.toString());
             } else {
                 result.add(
                     utils.getPeerId(
@@ -121,7 +128,9 @@ export class EventBuilder {
         this.chats = await _intoIdSet(client, this.chats);
     }
 
-    filter(event: EventCommon): undefined | EventCommon {
+    filter(
+        event: EventCommon | EventCommonSender
+    ): undefined | EventCommon | EventCommonSender {
         if (!this.resolved) {
             return;
         }
@@ -151,7 +160,7 @@ interface EventCommonInterface {
 
 export class EventCommon extends ChatGetter {
     _eventName = "Event";
-    _entities: Map<number, Entity>;
+    _entities: Map<string, Entity>;
     _messageId?: number;
 
     constructor({
@@ -176,7 +185,7 @@ export class EventCommon extends ChatGetter {
 }
 export class EventCommonSender extends SenderGetter {
     _eventName = "Event";
-    _entities: Map<number, Entity>;
+    _entities: Map<string, Entity>;
     _messageId?: number;
 
     constructor({

+ 0 - 3
gramjs/network/MTProtoState.ts

@@ -236,9 +236,6 @@ export class MTProtoState {
         if (this.msgIds.has(remoteMsgId.toString())) {
             throw new SecurityError("Duplicate msgIds");
         }
-        if (remoteMsgId.lesser(this._lastMsgId)) {
-            throw new SecurityError("Received old message from server");
-        }
         this.msgIds.add(remoteMsgId.toString());
         const remoteSequence = reader.readInt();
         reader.readInt(); // msgLen for the inner object, padding ignored

+ 24 - 22
gramjs/sessions/Memory.ts

@@ -4,7 +4,7 @@ import { Api } from "../tl";
 import bigInt from "big-integer";
 
 import { getDisplayName, getInputPeer, getPeerId } from "../Utils";
-import { isArrayLike } from "../Helpers";
+import { isArrayLike, returnBigInt } from "../Helpers";
 import { utils } from "../";
 import type { EntityLike } from "../define";
 
@@ -90,8 +90,8 @@ export class MemorySession extends Session {
     delete() {}
 
     _entityValuesToRow(
-        id: number,
-        hash: bigInt.BigInteger,
+        id: bigInt.BigInteger | string,
+        hash: bigInt.BigInteger | string,
         username: string,
         phone: string,
         name: string
@@ -203,7 +203,7 @@ export class MemorySession extends Session {
         }
     }
 
-    getEntityRowsById(id: number, exact = true) {
+    getEntityRowsById(id: string | bigInt.BigInteger, exact = true) {
         if (exact) {
             for (const e of this._entities) {
                 // id, hash, username, phone, name
@@ -213,9 +213,11 @@ export class MemorySession extends Session {
             }
         } else {
             const ids = [
-                utils.getPeerId(new Api.PeerUser({ userId: id })),
-                utils.getPeerId(new Api.PeerChat({ chatId: id })),
-                utils.getPeerId(new Api.PeerChannel({ channelId: id })),
+                utils.getPeerId(new Api.PeerUser({ userId: returnBigInt(id) })),
+                utils.getPeerId(new Api.PeerChat({ chatId: returnBigInt(id) })),
+                utils.getPeerId(
+                    new Api.PeerChannel({ channelId: returnBigInt(id) })
+                ),
             ];
             for (const e of this._entities) {
                 // id, hash, username, phone, name
@@ -228,7 +230,11 @@ export class MemorySession extends Session {
 
     getInputEntity(key: EntityLike): Api.TypeInputPeer {
         let exact;
-        if (typeof key === "object" && key.SUBCLASS_OF_ID) {
+        if (
+            typeof key === "object" &&
+            !bigInt.isInstance(key) &&
+            key.SUBCLASS_OF_ID
+        ) {
             if (key.SUBCLASS_OF_ID == 0xc91c90b6) {
                 return key;
             }
@@ -268,31 +274,27 @@ export class MemorySession extends Session {
                 key = utils.getPeerId(key);
                 exact = true;
             } else {
-                exact = !(typeof key == "number") || key < 0;
+                exact = false;
             }
         }
 
         let result = undefined;
+        if (typeof key == "number") {
+            key = key.toString();
+        }
         if (typeof key === "string") {
-            const phone = utils.parsePhone(key);
-            if (phone) {
-                result = this.getEntityRowsByPhone(phone);
+            const id = utils.parseID(key);
+            if (id) {
+                result = this.getEntityRowsById(id, exact);
             } else {
                 const { username, isInvite } = utils.parseUsername(key);
                 if (username && !isInvite) {
                     result = this.getEntityRowsByUsername(username);
-                } else {
-                    const tup = utils.resolveInviteLink(key)[1];
-                    if (tup) {
-                        result = this.getEntityRowsById(tup, false);
-                    }
                 }
             }
-        } else if (typeof key === "number") {
-            result = this.getEntityRowsById(key, exact);
-        }
-        if (!result && typeof key === "string") {
-            result = this.getEntityRowsByName(key);
+            if (!result) {
+                result = this.getEntityRowsByName(key);
+            }
         }
 
         if (result) {

+ 7 - 3
gramjs/sessions/StoreSession.ts

@@ -1,6 +1,7 @@
 import { MemorySession } from "./Memory";
 import store from "store2";
 import { AuthKey } from "../crypto/AuthKey";
+import bigInt from "big-integer";
 
 export class StoreSession extends MemorySession {
     private readonly sessionName: string;
@@ -66,12 +67,15 @@ export class StoreSession extends MemorySession {
             return;
         }
         for (const row of rows) {
-            row.push(new Date().getTime());
+            row.push(new Date().getTime().toString());
             this.store.set(this.sessionName + row[0], row);
         }
     }
 
-    getEntityRowsById(id: number, exact: boolean = true): any {
-        return this.store.get(this.sessionName + id);
+    getEntityRowsById(
+        id: string | bigInt.BigInteger,
+        exact: boolean = true
+    ): any {
+        return this.store.get(this.sessionName + id.toString());
     }
 }

+ 1 - 1
gramjs/tl/AllTLObjects.ts

@@ -1,6 +1,6 @@
 import { Api } from "./";
 
-export const LAYER = 131;
+export const LAYER = 135;
 const tlobjects: any = {};
 
 for (const tl of Object.values(Api)) {

文件差異過大導致無法顯示
+ 207 - 158
gramjs/tl/api.d.ts


+ 2 - 0
gramjs/tl/api.js

@@ -242,6 +242,8 @@ function compareType(value, type) {
             correct =
                 bigInt.isInstance(value) ||
                 typeof value === "bigint" ||
+                typeof value === "number" ||
+                typeof value === "string" ||
                 value === undefined;
             break;
         case "true":

+ 5 - 2
gramjs/tl/custom/chatGetter.ts

@@ -3,7 +3,8 @@ import type { TelegramClient } from "../../client/TelegramClient";
 import { utils } from "../../";
 import { Api } from "../api";
 import { inspect } from "util";
-import { betterConsoleLog } from "../../Helpers";
+import { betterConsoleLog, returnBigInt } from "../../Helpers";
+import bigInt from "big-integer";
 
 export interface ChatGetterConstructorParams {
     chatPeer?: EntityLike;
@@ -85,7 +86,9 @@ export class ChatGetter {
     }
 
     get chatId() {
-        return this._chatPeer ? utils.getPeerId(this._chatPeer) : undefined;
+        return this._chatPeer
+            ? returnBigInt(utils.getPeerId(this._chatPeer))
+            : undefined;
     }
 
     get isPrivate() {

+ 5 - 4
gramjs/tl/custom/dialog.ts

@@ -4,7 +4,8 @@ import type { Entity } from "../../define";
 import { getDisplayName, getInputPeer, getPeerId } from "../../Utils";
 import { Draft } from "./draft";
 import { inspect } from "util";
-import { betterConsoleLog } from "../../Helpers";
+import { betterConsoleLog, returnBigInt } from "../../Helpers";
+import bigInt from "big-integer";
 
 export class Dialog {
     _client: TelegramClient;
@@ -16,7 +17,7 @@ export class Dialog {
     date: number;
     entity?: Entity;
     inputEntity: Api.TypeInputPeer;
-    id?: number;
+    id?: bigInt.BigInteger;
     name?: string;
     title?: string;
     unreadCount: number;
@@ -32,7 +33,7 @@ export class Dialog {
     constructor(
         client: TelegramClient,
         dialog: Api.Dialog,
-        entities: Map<number, Entity>,
+        entities: Map<string, Entity>,
         message?: Api.Message
     ) {
         this._client = client;
@@ -46,7 +47,7 @@ export class Dialog {
         this.entity = entities.get(getPeerId(dialog.peer));
         this.inputEntity = getInputPeer(this.entity);
         if (this.entity) {
-            this.id = getPeerId(this.entity); // ^ May be InputPeerSelf();
+            this.id = returnBigInt(getPeerId(this.entity)); // ^ May be InputPeerSelf();
             this.name = this.title = getDisplayName(this.entity);
         }
 

+ 9 - 3
gramjs/tl/custom/forward.ts

@@ -3,12 +3,18 @@ import { SenderGetter } from "./senderGetter";
 import { Api } from "../api";
 import type { TelegramClient } from "../../client/TelegramClient";
 import type { Entity } from "../../define";
-import { _EntityType, _entityType, betterConsoleLog } from "../../Helpers";
+import {
+    _EntityType,
+    _entityType,
+    betterConsoleLog,
+    returnBigInt,
+} from "../../Helpers";
 import { _getEntityPair, getPeerId } from "../../Utils";
 import { inspect } from "util";
 
 export class Forward extends SenderGetter {
     private originalFwd: Api.MessageFwdHeader;
+
     [inspect.custom]() {
         return betterConsoleLog(this);
     }
@@ -16,7 +22,7 @@ export class Forward extends SenderGetter {
     constructor(
         client: TelegramClient,
         original: Api.MessageFwdHeader,
-        entities: Map<number, Entity>
+        entities: Map<string, Entity>
     ) {
         super();
         // contains info for the original header sent by telegram.
@@ -51,7 +57,7 @@ export class Forward extends SenderGetter {
             inputChat: inputChat,
         });
         SenderGetter.initSenderClass(this, {
-            senderId: senderId,
+            senderId: senderId ? returnBigInt(senderId) : undefined,
             sender: sender,
             inputSender: inputSender,
         });

+ 19 - 13
gramjs/tl/custom/message.ts

@@ -9,9 +9,9 @@ import type { File } from "./file";
 import { EditMessageParams, SendMessageParams } from "../../client/messages";
 import { DownloadMediaInterface } from "../../client/downloads";
 import { inspect } from "util";
-import { betterConsoleLog } from "../../Helpers";
+import { betterConsoleLog, returnBigInt } from "../../Helpers";
 import { _selfId } from "../../client/users";
-import { BigInteger } from "big-integer";
+import bigInt, { BigInteger } from "big-integer";
 
 interface MessageBaseInterface {
     id: any;
@@ -43,7 +43,7 @@ interface MessageBaseInterface {
     ttlPeriod?: number;
     replies?: any;
     action?: any;
-    _entities?: Map<number, Entity>;
+    _entities?: Map<string, Entity>;
 }
 
 /**
@@ -132,7 +132,7 @@ export class CustomMessage extends SenderGetter {
      * The ID of the bot used to send this message
      * through its inline mode (e.g. "via @like").
      */
-    viaBotId?: number;
+    viaBotId?: bigInt.BigInteger;
     /**
      * The original reply header if this message is replying to another.
      */
@@ -235,10 +235,12 @@ export class CustomMessage extends SenderGetter {
     /** @hidden */
     _sender?: any;
     /** @hidden */
-    _entities?: Map<number, Entity>;
+    _entities?: Map<string, Entity>;
     /** @hidden */
+
     /* @ts-ignore */
     getBytes(): Buffer;
+
     originalArgs: any;
 
     patternMatch?: RegExpMatchArray;
@@ -281,7 +283,7 @@ export class CustomMessage extends SenderGetter {
 
         action = undefined,
         ttlPeriod = undefined,
-        _entities = new Map<number, Entity>(),
+        _entities = new Map<string, Entity>(),
     }: MessageBaseInterface) {
         if (!id) throw new Error("id is a required attribute for Message");
         let senderId = undefined;
@@ -338,7 +340,9 @@ export class CustomMessage extends SenderGetter {
 
         // Note: these calls would reset the client
         ChatGetter.initChatClass(this, { chatPeer: peerId, broadcast: post });
-        SenderGetter.initSenderClass(this, { senderId: senderId });
+        SenderGetter.initSenderClass(this, {
+            senderId: senderId ? returnBigInt(senderId) : undefined,
+        });
 
         this._forward = undefined;
     }
@@ -350,21 +354,21 @@ export class CustomMessage extends SenderGetter {
 
     _finishInit(
         client: TelegramClient,
-        entities: Map<number, Entity>,
+        entities: Map<string, Entity>,
         inputChat?: EntityLike
     ) {
         this._client = client;
         const cache = client._entityCache;
         if (this.senderId) {
             [this._sender, this._inputSender] = utils._getEntityPair(
-                this.senderId,
+                this.senderId.toString(),
                 entities,
                 cache
             );
         }
         if (this.chatId) {
             [this._chat, this._inputChat] = utils._getEntityPair(
-                this.chatId,
+                this.chatId.toString(),
                 entities,
                 cache
             );
@@ -377,7 +381,7 @@ export class CustomMessage extends SenderGetter {
 
         if (this.viaBotId) {
             [this._viaBot, this._viaInputBot] = utils._getEntityPair(
-                this.viaBotId,
+                this.viaBotId.toString(),
                 entities,
                 cache
             );
@@ -393,10 +397,12 @@ export class CustomMessage extends SenderGetter {
                 this.action instanceof Api.MessageActionChatCreate
             ) {
                 this._actionEntities = this.action.users.map((i) =>
-                    entities.get(i)
+                    entities.get(i.toString())
                 );
             } else if (this.action instanceof Api.MessageActionChatDeleteUser) {
-                this._actionEntities = [entities.get(this.action.userId)];
+                this._actionEntities = [
+                    entities.get(this.action.userId.toString()),
+                ];
             } else if (
                 this.action instanceof Api.MessageActionChatJoinedByLink
             ) {

+ 3 - 2
gramjs/tl/custom/senderGetter.ts

@@ -4,15 +4,16 @@ import { Api } from "../api";
 import { inspect } from "util";
 import { betterConsoleLog } from "../../Helpers";
 import { ChatGetter } from "./chatGetter";
+import bigInt from "big-integer";
 
 interface SenderGetterConstructorInterface {
-    senderId?: number;
+    senderId?: bigInt.BigInteger;
     sender?: Entity;
     inputSender?: Api.TypeInputPeer;
 }
 
 export class SenderGetter extends ChatGetter {
-    _senderId?: number;
+    _senderId?: bigInt.BigInteger;
     _sender?: Entity;
     _inputSender?: Api.TypeInputPeer;
     public _client?: TelegramClient;

文件差異過大導致無法顯示
+ 230 - 192
gramjs/tl/static/api.tl


+ 2 - 2
package-lock.json

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

+ 1 - 1
package.json

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

部分文件因文件數量過多而無法顯示