فهرست منبع

Fix scheduled messages
update docs for scheduled messages

painor 3 سال پیش
والد
کامیت
7abb54854b

+ 2 - 2
gramjs/Password.ts

@@ -206,7 +206,7 @@ async function computeDigest(
 ) {
     try {
         checkPrimeAndGood(algo.p, algo.g);
-    } catch (e:any) {
+    } catch (e: any) {
         throw new Error("bad p/g in password");
     }
 
@@ -244,7 +244,7 @@ async function computeCheck(request: Api.account.Password, password: string) {
     const B = readBigIntFromBuffer(srp_B, false);
     try {
         checkPrimeAndGood(algo.p, g);
-    } catch (e:any) {
+    } catch (e: any) {
         throw new Error("bad /g in password");
     }
     if (!isGoodLarge(B, p)) {

+ 1 - 1
gramjs/Utils.ts

@@ -188,7 +188,7 @@ export function _getEntityPair(
     let inputEntity;
     try {
         inputEntity = cache.get(entityId);
-    } catch (e:any) {
+    } catch (e: any) {
         try {
             inputEntity = getInputPeerFunction(inputEntity);
         } catch (e) {}

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.9.2";
+export const version = "1.9.3";

+ 1 - 1
gramjs/client/TelegramClient.ts

@@ -661,7 +661,7 @@ export class TelegramClient extends TelegramBaseClient {
      *
      * // Scheduling a message to be sent after 5 minutes
      *
-     * await client.sendMessage(chat, {message:'Hi, future!', schedule:(60 * 5)+ new Date()})
+     * await client.sendMessage(chat, {message:'Hi, future!', schedule:(60 * 5) + (Date.now() / 1000)})
      *
      * ```
      */

+ 21 - 21
gramjs/client/auth.ts

@@ -93,7 +93,7 @@ export async function start(
 
     const apiCredentials = {
         apiId: client.apiId,
-        apiHash: client.apiHash
+        apiHash: client.apiHash,
     };
 
     await _authFlow(client, apiCredentials, authParams);
@@ -150,7 +150,7 @@ export async function signInUser(
             }
 
             break;
-        } catch (err:any) {
+        } catch (err: any) {
             if (typeof authParams.phoneNumber !== "function") {
                 throw err;
             }
@@ -170,7 +170,7 @@ export async function signInUser(
         try {
             try {
                 phoneCode = await authParams.phoneCode(isCodeViaApp);
-            } catch (err:any) {
+            } catch (err: any) {
                 // This is the support for changing phone number from the phone code screen.
                 if (err.errorMessage === "RESTART_AUTH") {
                     return client.signInUser(apiCredentials, authParams);
@@ -187,7 +187,7 @@ export async function signInUser(
                 new Api.auth.SignIn({
                     phoneNumber,
                     phoneCodeHash,
-                    phoneCode
+                    phoneCode,
                 })
             );
 
@@ -198,7 +198,7 @@ export async function signInUser(
             }
 
             return result.user;
-        } catch (err:any) {
+        } catch (err: any) {
             if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
                 return client.signInWithPassword(apiCredentials, authParams);
             } else {
@@ -229,7 +229,7 @@ export async function signInUser(
                         phoneNumber,
                         phoneCodeHash,
                         firstName,
-                        lastName
+                        lastName,
                     })
                 )) as Api.auth.Authorization;
 
@@ -237,13 +237,13 @@ export async function signInUser(
                     // This is a violation of Telegram rules: the user should be presented with and accept TOS.
                     await client.invoke(
                         new Api.help.AcceptTermsOfService({
-                            id: termsOfService.id
+                            id: termsOfService.id,
                         })
                     );
                 }
 
                 return user;
-            } catch (err:any) {
+            } catch (err: any) {
                 const shouldWeStop = await authParams.onError(err);
                 if (shouldWeStop) {
                     throw new Error("AUTH_USER_CANCEL");
@@ -268,7 +268,7 @@ export async function signInUserWithQrCode(
                 new Api.auth.ExportLoginToken({
                     apiId: Number(apiCredentials.apiId),
                     apiHash: apiCredentials.apiHash,
-                    exceptIds: []
+                    exceptIds: [],
                 })
             );
 
@@ -280,7 +280,7 @@ export async function signInUserWithQrCode(
             if (authParams.qrCode) {
                 await Promise.race([
                     authParams.qrCode({ token, expires }),
-                    sleep(QR_CODE_TIMEOUT)
+                    sleep(QR_CODE_TIMEOUT),
                 ]);
             }
             await sleep(QR_CODE_TIMEOUT);
@@ -306,7 +306,7 @@ export async function signInUserWithQrCode(
             new Api.auth.ExportLoginToken({
                 apiId: Number(apiCredentials.apiId),
                 apiHash: apiCredentials.apiHash,
-                exceptIds: []
+                exceptIds: [],
             })
         );
         if (
@@ -318,7 +318,7 @@ export async function signInUserWithQrCode(
             await client._switchDC(result2.dcId);
             const migratedResult = await client.invoke(
                 new Api.auth.ImportLoginToken({
-                    token: result2.token
+                    token: result2.token,
                 })
             );
 
@@ -329,7 +329,7 @@ export async function signInUserWithQrCode(
                 return migratedResult.authorization.user;
             }
         }
-    } catch (err:any) {
+    } catch (err: any) {
         if (err.errorMessage === "SESSION_PASSWORD_NEEDED") {
             return client.signInWithPassword(apiCredentials, authParams);
         }
@@ -356,7 +356,7 @@ export async function sendCode(
                 phoneNumber,
                 apiId,
                 apiHash,
-                settings: new Api.CodeSettings({})
+                settings: new Api.CodeSettings({}),
             })
         );
 
@@ -365,22 +365,22 @@ export async function sendCode(
             return {
                 phoneCodeHash: sendResult.phoneCodeHash,
                 isCodeViaApp:
-                    sendResult.type instanceof Api.auth.SentCodeTypeApp
+                    sendResult.type instanceof Api.auth.SentCodeTypeApp,
             };
         }
 
         const resendResult = await client.invoke(
             new Api.auth.ResendCode({
                 phoneNumber,
-                phoneCodeHash: sendResult.phoneCodeHash
+                phoneCodeHash: sendResult.phoneCodeHash,
             })
         );
 
         return {
             phoneCodeHash: resendResult.phoneCodeHash,
-            isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp
+            isCodeViaApp: resendResult.type instanceof Api.auth.SentCodeTypeApp,
         };
-    } catch (err:any) {
+    } catch (err: any) {
         if (err.errorMessage === "AUTH_RESTART") {
             return client.sendCode(apiCredentials, phoneNumber, forceSMS);
         } else {
@@ -417,12 +417,12 @@ export async function signInWithPassword(
             );
             const { user } = (await client.invoke(
                 new Api.auth.CheckPassword({
-                    password: passwordSrpCheck
+                    password: passwordSrpCheck,
                 })
             )) as Api.auth.Authorization;
 
             return user;
-        } catch (err:any) {
+        } catch (err: any) {
             const shouldWeStop = await authParams.onError(err);
             if (shouldWeStop) {
                 throw new Error("AUTH_USER_CANCEL");
@@ -461,7 +461,7 @@ export async function signInBot(
         new Api.auth.ImportBotAuthorization({
             apiId,
             apiHash,
-            botAuthToken
+            botAuthToken,
         })
     )) as Api.auth.Authorization;
     return user;

+ 50 - 6
gramjs/client/messageParse.ts

@@ -165,6 +165,7 @@ export function _getResponseMessage(
                 return update.message;
             }
         } else if (update instanceof Api.UpdateNewScheduledMessage) {
+            console.log("here!");
             (update.message as unknown as Message)._finishInit(
                 client,
                 entities,
@@ -194,12 +195,22 @@ export function _getResponseMessage(
     if (request == undefined) {
         return idToMessage;
     }
+    let mapping: Map<number, Message>;
+    let opposite = new Map<number, Message>();
+    if ("scheduleDate" in request && request.scheduleDate != undefined) {
+        mapping = schedToMessage;
+        opposite = idToMessage;
+    } else {
+        mapping = idToMessage;
+    }
+    console.log("request is", request);
     let randomId =
         isArrayLike(request) ||
         typeof request == "number" ||
         bigInt.isInstance(request)
             ? request
             : request.randomId.toString();
+    console.log("random id", randomToId);
     if (!randomId) {
         client._log.warn(
             `No randomId in ${request} to map to. returning undefined for ${result}`
@@ -208,27 +219,60 @@ export function _getResponseMessage(
     }
 
     if (!isArrayLike(randomId)) {
-        const msg = idToMessage.get(randomToId.get(randomId)!);
+        let msg = mapping.get(randomToId.get(randomId)!);
+        if (!msg) {
+            msg = opposite.get(randomToId.get(randomId)!);
+        }
         if (!msg) {
             client._log.warn(
-                `Request ${request} had missing message mapping ${result}`
+                `Request ${request.className} had missing message mapping ${result.className}`
             );
         }
         return msg;
     } else {
-        const mapping = [];
+        const mappingToReturn = [];
+        let warned = false;
+        for (let i = 0; i < randomId.length; i++) {
+            const rnd = randomId[i] + "";
+            const msg = mapping.get(randomToId.get(rnd)!);
+            if (!msg) {
+                warned = true;
+                break;
+            } else {
+                mappingToReturn.push(msg);
+            }
+        }
+        if (!warned) {
+            return mappingToReturn;
+        }
+        const oppositeToReturn = [];
+        warned = false;
         for (let i = 0; i < randomId.length; i++) {
             const rnd = randomId[i] + "";
-            const msg = idToMessage.get(randomToId.get(rnd)!);
+            const msg = opposite.get(randomToId.get(rnd)!);
             if (!msg) {
                 client._log.warn(
                     `Request ${request} had missing message mapping ${result}`
                 );
+                warned = true;
                 break;
             } else {
-                mapping.push(msg);
+                oppositeToReturn.push(msg);
             }
         }
-        return mapping;
+        if (!warned) {
+            return mappingToReturn;
+        }
+    }
+    const finalToReturn = [];
+    for (let i = 0; i < randomId.length; i++) {
+        const rnd = randomId[i] + "";
+        if (randomToId.has(rnd)) {
+            finalToReturn.push(
+                mapping.get(randomToId.get(rnd)!) ||
+                    opposite.get(randomToId.get(rnd)!)
+            );
+        }
     }
+    return finalToReturn;
 }

+ 1 - 1
gramjs/client/messages.ts

@@ -357,7 +357,7 @@ export class _IDsIter extends RequestIter {
                         id: ids,
                     })
                 );
-            } catch (e:any) {
+            } catch (e: any) {
                 if (e.errorMessage == "MESSAGE_IDS_EMPTY") {
                     r = new Api.messages.MessagesNotModified({
                         count: ids.length,

+ 1 - 1
gramjs/client/telegramBaseClient.ts

@@ -412,7 +412,7 @@ export abstract class TelegramBaseClient {
                 sender.userDisconnected = false;
 
                 return sender;
-            } catch (err:any) {
+            } catch (err: any) {
                 if (err.errorMessage === "DC_ID_INVALID") {
                     sender._authenticated = true;
                     sender.userDisconnected = false;

+ 1 - 1
gramjs/client/updates.ts

@@ -182,7 +182,7 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
                 PING_FAIL_ATTEMPTS,
                 PING_FAIL_INTERVAL
             );
-        } catch (err:any) {
+        } catch (err: any) {
             // eslint-disable-next-line no-console
             client._log.error(err);
             if (client._reconnecting) {

+ 3 - 3
gramjs/client/users.ts

@@ -32,7 +32,7 @@ export async function invoke<R extends Api.AnyRequest>(
             client.session.processEntities(result);
             client._entityCache.add(result);
             return result;
-        } catch (e:any) {
+        } catch (e: any) {
             if (
                 e instanceof errors.ServerError ||
                 e.errorMessage === "RPC_CALL_FAIL" ||
@@ -326,7 +326,7 @@ export async function _getEntityFromString(
                     }
                 }
             }
-        } catch (e:any) {
+        } catch (e: any) {
             if (e.errorMessage === "BOT_METHOD_INVALID") {
                 throw new Error(
                     "Cannot get entity by phone number as a " +
@@ -372,7 +372,7 @@ export async function _getEntityFromString(
                         }
                     }
                 }
-            } catch (e:any) {
+            } catch (e: any) {
                 if (e.errorMessage === "USERNAME_NOT_OCCUPIED") {
                     throw new Error(`No user has "${username}" as username`);
                 }

+ 6 - 6
gramjs/events/NewMessage.ts

@@ -2,7 +2,7 @@ import {
     _intoIdSet,
     DefaultEventInterface,
     EventBuilder,
-    EventCommon
+    EventCommon,
 } from "./common";
 import type { Entity, EntityLike } from "../define";
 import type { TelegramClient } from "..";
@@ -89,7 +89,7 @@ export class NewMessage extends EventBuilder {
             fromUsers,
             forwards,
             pattern,
-            blacklistChats = false
+            blacklistChats = false,
         } = newMessageParams;
         if (incoming && outgoing) {
             incoming = outgoing = undefined;
@@ -115,7 +115,7 @@ export class NewMessage extends EventBuilder {
             pattern,
             fromUsers,
             forwards,
-            func
+            func,
         ].every((v) => v == undefined);
     }
 
@@ -156,7 +156,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
@@ -176,7 +176,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
@@ -229,7 +229,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;

+ 5 - 5
gramjs/network/MTProtoSender.ts

@@ -431,7 +431,7 @@ export class MTProtoSender {
 
             try {
                 await this._connection!.send(data);
-            } catch (e:any) {
+            } catch (e: any) {
                 this._log.error(e);
                 this._log.info("Connection closed while sending data");
                 return;
@@ -462,7 +462,7 @@ export class MTProtoSender {
             this._log.debug("Receiving items from the network...");
             try {
                 body = await this._connection!.recv();
-            } catch (e:any) {
+            } catch (e: any) {
                 /** when the server disconnects us we want to reconnect */
                 this._log.warn("Connection closed while receiving data");
                 if (!this.userDisconnected) {
@@ -474,7 +474,7 @@ export class MTProtoSender {
             }
             try {
                 message = await this._state.decryptMessageData(body);
-            } catch (e:any) {
+            } catch (e: any) {
                 if (e instanceof TypeNotFoundError) {
                     // Received object which we don't know how to deserialize
                     this._log.info(
@@ -527,7 +527,7 @@ export class MTProtoSender {
             }
             try {
                 await this._processMessage(message);
-            } catch (e:any) {
+            } catch (e: any) {
                 this._log.error("Unhandled error while receiving data");
                 this._log.error(e);
             }
@@ -624,7 +624,7 @@ export class MTProtoSender {
                 if (!(reader.tgReadObject() instanceof Api.upload.File)) {
                     throw new Error("Not an upload.File");
                 }
-            } catch (e:any) {
+            } catch (e: any) {
                 this._log.error(e);
                 if (e instanceof TypeNotFoundError) {
                     this._log.info(

+ 2 - 2
gramjs/network/connection/Connection.ts

@@ -117,7 +117,7 @@ class Connection {
                 }
                 await this._send(data);
             }
-        } catch (e:any) {
+        } catch (e: any) {
             this._log.info("The server closed the connection while sending");
         }
     }
@@ -130,7 +130,7 @@ class Connection {
                 if (!data) {
                     throw new Error("no data received");
                 }
-            } catch (e:any) {
+            } catch (e: any) {
                 this._log.info("connection closed");
                 //await this._recvArray.push()
 

+ 2 - 2
gramjs/tl/custom/messageButton.ts

@@ -69,7 +69,7 @@ export class MessageButton {
             });
             try {
                 return await this._client.invoke(request);
-            } catch (e:any) {
+            } catch (e: any) {
                 if (e.errorMessage == "BOT_RESPONSE_TIMEOUT") {
                     return null;
                 }
@@ -93,7 +93,7 @@ export class MessageButton {
             });
             try {
                 return await this._client.invoke(request);
-            } catch (e:any) {
+            } catch (e: any) {
                 if (e.errorMessage == "BOT_RESPONSE_TIMEOUT") {
                     return null;
                 }

+ 6 - 6
gramjs/tl/generationHelpers.ts

@@ -15,7 +15,7 @@ const CORE_TYPES = new Set([
     0x997275b5, // boolTrue#997275b5 = Bool;
     0x3fedd339, // true#3fedd339 = True;
     0xc4b9f9bb, // error#c4b9f9bb code:int text:string = Error;
-    0x56730bcc // null#56730bcc = Null;
+    0x56730bcc, // null#56730bcc = Null;
 ]);
 const AUTH_KEY_TYPES = new Set([
     0x05162463, // resPQ,
@@ -28,7 +28,7 @@ const AUTH_KEY_TYPES = new Set([
     0x6643b654, // client_DH_inner_data
     0xd712e4be, // req_DH_params
     0xf5045f1f, // set_client_DH_params
-    0x3072cfa1 // gzip_packed
+    0x3072cfa1, // gzip_packed
 ]);
 
 const fromLine = (line: string, isFunction: boolean) => {
@@ -48,7 +48,7 @@ const fromLine = (line: string, isFunction: boolean) => {
         subclassOfId: crc32(match[3]),
         result: match[3],
         isFunction: isFunction,
-        namespace: undefined
+        namespace: undefined,
     };
     if (!currentConfig.constructorId) {
         const hexId = "";
@@ -112,7 +112,7 @@ function buildArgConfig(name: string, argType: string) {
         flagIndex: -1,
         flagIndicator: true,
         type: null,
-        useVectorId: null
+        useVectorId: null,
     };
 
     // Special case: some types can be inferred, which makes it
@@ -301,7 +301,7 @@ export function serializeBytes(data: Buffer | string | any) {
                 254,
                 data.length % 256,
                 (data.length >> 8) % 256,
-                (data.length >> 16) % 256
+                (data.length >> 16) % 256,
             ])
         );
         r.push(data);
@@ -333,5 +333,5 @@ export {
     fromLine,
     CORE_TYPES,
     snakeToCamelCase,
-    variableSnakeToCamelCase
+    variableSnakeToCamelCase,
 };

+ 2 - 2
package-lock.json

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

+ 1 - 1
package.json

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