Explorar o código

Update docs
Default logging to Info instead of debug.

painor %!s(int64=3) %!d(string=hai) anos
pai
achega
9cd0423068

+ 2 - 2
gramjs/Utils.ts

@@ -974,8 +974,8 @@ export function getAppropriatedPartSize(fileSize: number) {
         // 750MB
         return 256;
     }
-    if (fileSize <= 1572864000) {
-        // 1500MB
+    if (fileSize <= 2097152000) {
+        // 2000MB
         return 512;
     }
 

+ 1 - 1
gramjs/Version.ts

@@ -1 +1 @@
-export const version = "1.8.3";
+export const version = "1.8.4";

+ 41 - 13
gramjs/client/TelegramClient.ts

@@ -435,10 +435,10 @@ export class TelegramClient extends TelegramBaseClient {
      * @example
      * // sets the mode to HTML
      * client.setParseMode("html");
-     * await client.sendMessage("me","<u>This is an underline text</u>");
+     * await client.sendMessage("me",{message:"<u>This is an underline text</u>"});
      * // disable formatting
      * client.setParseMode(undefined);
-     * await client.sendMessage("me","<u> this will be sent as it is</u> ** with no formatting **);
+     * await client.sendMessage("me",{message:"<u> this will be sent as it is</u> ** with no formatting **});
      */
     setParseMode(
         mode:
@@ -557,28 +557,28 @@ export class TelegramClient extends TelegramBaseClient {
      * @example
      * ```ts
      * // Markdown is the default.
-     * await client.sendMessage("me","Hello **world!**);
+     * await client.sendMessage("me",{message:"Hello **world!**});
      *
      * // Defaults to another parse mode.
      * client.setParseMode("HTML");
      *
-     * await client.sendMessage('me', 'Some <b>bold</b> and <i>italic</i> text')
-     * await client.sendMessage('me', 'An <a href="https://example.com">URL</a>')
-     * await client.sendMessage('me', '<a href="tg://user?id=me">Mentions</a>')
+     * await client.sendMessage('me', {message:'Some <b>bold</b> and <i>italic</i> text'})
+     * await client.sendMessage('me', {message:'An <a href="https://example.com">URL</a>'})
+     * await client.sendMessage('me', {message:'<a href="tg://user?id=me">Mentions</a>'})
      *
      * // Explicit parse mode.
      * //  No parse mode by default
      * client.setParseMode(undefined);
      * //...but here I want markdown
-     * await client.sendMessage('me', 'Hello, **world**!', {parseMode:"md"})
+     * await client.sendMessage('me', {message:'Hello, **world**!', {parseMode:"md"}})
      *
      * // ...and here I need HTML
-     * await client.sendMessage('me', 'Hello, <i>world</i>!', {parseMode='html'})
+     * await client.sendMessage('me', {message:'Hello, <i>world</i>!', {parseMode='html'}})
      *
      *
      * // Scheduling a message to be sent after 5 minutes
      *
-     * await client.sendMessage(chat, 'Hi, future!', {schedule:(60 * 5)+ new Date()}
+     * await client.sendMessage(chat, {message:'Hi, future!', schedule:(60 * 5)+ new Date()})
      *
      * ```
      */
@@ -646,7 +646,7 @@ export class TelegramClient extends TelegramBaseClient {
      *  For example, when trying to edit messages with a reply markup (or clear markup) this error will be raised.
      *  @example
      *  ```ts
-     *  const message = await client.sendMessage(chat,"Hi!");
+     *  const message = await client.sendMessage(chat,{message:"Hi!"});
      *
      *  await client.editMessage(chat,{message:message,text:"Hello!"}
      *  // or
@@ -999,10 +999,35 @@ export class TelegramClient extends TelegramBaseClient {
         return userMethods.isUserAuthorized(this);
     }
 
-    /** @hidden */
+    /**
+     * Turns the given entity into a valid Telegram {@link Api.User}, {@link Api.Chat} or {@link Api.Channel}.<br/>
+     * You can also pass a list or iterable of entities, and they will be efficiently fetched from the network.
+     * @param entity - If a username is given, the username will be resolved making an API call every time.<br/>
+     * Resolving usernames is an expensive operation and will start hitting flood waits around 50 usernames in a short period of time.<br/>
+     * <br/>
+     * Similar limits apply to invite links, and you should use their ID instead.<br/>
+     * Using phone numbers (from people in your contact list), exact names, integer IDs or Peer rely on a getInputEntity first,<br/>
+     * which in turn needs the entity to be in cache, unless a InputPeer was passed.<br/>
+     * <br/>
+     * If the entity can't be found, ValueError will be raised.
+     * @return
+     * {@link Api.Chat},{@link Api.Chat} or {@link Api.Channel} corresponding to the input entity. A list will be returned if more than one was given.
+     * @example
+     * ```ts
+     * const me = await client.getEntity("me");
+     * console.log("My name is",utils.getDisplayName(me));
+     *
+     * const chat = await client.getInputEntity("username");
+     * for await (const message of client.iterMessages(chat){
+     *     console.log("Message text is",message.text);
+     * }
+     *
+     * // Note that you could have used the username directly, but it's
+     * // good to use getInputEntity if you will reuse it a lot.
+     * ```
+     */
+
     getEntity(entity: EntityLike): Promise<Entity>;
-    /** @hidden */
-    getEntity(entity: EntityLike[]): Promise<Entity[]>;
     /**
      * Turns the given entity into a valid Telegram {@link Api.User}, {@link Api.Chat} or {@link Api.Channel}.<br/>
      * You can also pass a list or iterable of entities, and they will be efficiently fetched from the network.
@@ -1030,6 +1055,9 @@ export class TelegramClient extends TelegramBaseClient {
      * // good to use getInputEntity if you will reuse it a lot.
      * ```
      */
+
+    getEntity(entity: EntityLike[]): Promise<Entity[]>;
+
     getEntity(entity: any) {
         return userMethods.getEntity(this, entity);
     }

+ 20 - 12
gramjs/client/downloads.ts

@@ -17,6 +17,7 @@ export interface progressCallback {
         /** other args to be passed if needed */
         ...args: any[]
     ): void;
+
     /** When this value is set to true the download will stop */
     isCanceled?: boolean;
     /** Does nothing for now. */
@@ -151,12 +152,12 @@ export async function downloadFile(
                                 location: inputLocation,
                                 offset,
                                 limit,
-                                precise: isPrecise || undefined,
+                                precise: isPrecise || undefined
                             })
                         ),
                         sleep(REQUEST_TIMEOUT).then(() =>
                             Promise.reject(new Error("REQUEST_TIMEOUT"))
-                        ),
+                        )
                     ]);
 
                     if (progressCallback) {
@@ -199,7 +200,8 @@ class Foreman {
     private deferred: Deferred | undefined;
     private activeWorkers = 0;
 
-    constructor(private maxWorkers: number) {}
+    constructor(private maxWorkers: number) {
+    }
 
     requestWorker() {
         this.activeWorkers++;
@@ -229,7 +231,7 @@ function createDeferred(): Deferred {
 
     return {
         promise,
-        resolve: resolve!,
+        resolve: resolve!
     };
 }
 
@@ -247,6 +249,7 @@ export interface DownloadMediaInterface {
     /** number of workers to use while downloading. more means faster but anything above 16 may cause issues. */
     workers?: number;
 }
+
 /** @hidden */
 export async function downloadMedia(
     client: TelegramClient,
@@ -288,6 +291,7 @@ export async function downloadMedia(
     }
 }
 
+/** @hidden */
 export async function _downloadDocument(
     client: TelegramClient,
     doc: Api.MessageMediaDocument | Api.Document,
@@ -324,24 +328,25 @@ export async function _downloadDocument(
             id: doc.id,
             accessHash: doc.accessHash,
             fileReference: doc.fileReference,
-            thumbSize: size ? size.type : "",
+            thumbSize: size ? size.type : ""
         }),
         {
             fileSize:
                 size && !(size instanceof Api.PhotoSizeEmpty)
                     ? size instanceof Api.PhotoSizeProgressive
-                        ? Math.max(...size.sizes)
-                        : size.size
+                    ? Math.max(...size.sizes)
+                    : size.size
                     : doc.size,
             progressCallback: args.progressCallback,
             start: args.start,
             end: args.end,
             dcId: doc.dcId,
-            workers: args.workers,
+            workers: args.workers
         }
     );
 }
 
+/** @hidden */
 export async function _downloadContact(
     client: TelegramClient,
     media: Api.MessageMediaContact,
@@ -350,6 +355,7 @@ export async function _downloadContact(
     throw new Error("not implemented");
 }
 
+/** @hidden */
 export async function _downloadWebDocument(
     client: TelegramClient,
     media: Api.WebDocument | Api.WebDocumentNoProxy,
@@ -373,6 +379,7 @@ function pickFileSize(sizes: Api.TypePhotoSize[], sizeType: string) {
     return undefined;
 }
 
+/** @hidden */
 export function _downloadCachedPhotoSize(
     size: Api.PhotoCachedSize | Api.PhotoStrippedSize
 ) {
@@ -386,6 +393,7 @@ export function _downloadCachedPhotoSize(
     return data;
 }
 
+/** @hidden */
 export async function _downloadPhoto(
     client: TelegramClient,
     photo: Api.MessageMediaPhoto | Api.Photo,
@@ -416,7 +424,7 @@ export async function _downloadPhoto(
             id: photo.id,
             accessHash: photo.accessHash,
             fileReference: photo.fileReference,
-            thumbSize: size.type,
+            thumbSize: size.type
         }),
         {
             dcId: photo.dcId,
@@ -424,7 +432,7 @@ export async function _downloadPhoto(
                 size instanceof Api.PhotoSizeProgressive
                     ? Math.max(...size.sizes)
                     : size.size,
-            progressCallback: args.progressCallback,
+            progressCallback: args.progressCallback
         }
     );
 }
@@ -455,7 +463,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);
@@ -463,6 +471,6 @@ export async function downloadProfilePhoto(
     return client.downloadFile(loc, {
         dcId,
         fileSize: 2 * 1024 * 1024,
-        workers: 1,
+        workers: 1
     });
 }

+ 3 - 4
gramjs/client/messageParse.ts

@@ -23,13 +23,12 @@ export const DEFAULT_DELIMITERS: {
     "```": Api.MessageEntityPre,
 };
 
-// export class MessageParseMethods {
 
 export interface ParseInterface {
     parse: (message: string) => [string, Api.TypeMessageEntity[]];
     unparse: (text: string, entities: Api.TypeMessageEntity[]) => string;
 }
-
+/** @hidden */
 export async function _replaceWithMention(
     client: TelegramClient,
     entities: Api.TypeMessageEntity[],
@@ -47,7 +46,7 @@ export async function _replaceWithMention(
         return false;
     }
 }
-
+/** @hidden */
 export function _parseMessageText(
     client: TelegramClient,
     message: string,
@@ -66,7 +65,7 @@ export function _parseMessageText(
     }
     return parseMode.parse(message);
 }
-
+/** @hidden */
 export function _getResponseMessage(
     client: TelegramClient,
     request: any,

+ 1 - 1
gramjs/client/messages.ts

@@ -547,7 +547,7 @@ export interface EditMessageParams {
     schedule?: DateLike;
 }
 
-//  MessageMethods
+/** @hidden */
 export function iterMessages(
     client: TelegramClient,
     entity: EntityLike | undefined,

+ 15 - 6
gramjs/client/updates.ts

@@ -7,7 +7,7 @@ import { UpdateConnectionState } from "../network";
 import type { Raw } from "../events";
 import { utils } from "../index";
 
-// export class UpdateMethods
+/** @hidden */
 export function on(client: TelegramClient, event?: EventBuilder) {
     return (f: { (event: any): void }) => {
         client.addEventHandler(f, event);
@@ -15,6 +15,7 @@ export function on(client: TelegramClient, event?: EventBuilder) {
     };
 }
 
+/** @hidden */
 export function addEventHandler(
     client: TelegramClient,
     callback: CallableFunction,
@@ -29,24 +30,28 @@ export function addEventHandler(
     client._eventBuilders.push([event, callback]);
 }
 
+/** @hidden */
 export function removeEventHandler(
     client: TelegramClient,
     callback: CallableFunction,
     event: EventBuilder
 ) {
-    client._eventBuilders = client._eventBuilders.filter(function (item) {
+    client._eventBuilders = client._eventBuilders.filter(function(item) {
         return item !== [event, callback];
     });
 }
 
+/** @hidden */
 export function listEventHandlers(client: TelegramClient) {
     return client._eventBuilders;
 }
 
+/** @hidden */
 export function catchUp() {
     // TODO
 }
 
+/** @hidden */
 export function _handleUpdate(
     client: TelegramClient,
     update: Api.TypeUpdate | number
@@ -54,7 +59,7 @@ export function _handleUpdate(
     if (typeof update === "number") {
         if ([-1, 0, 1].includes(update)) {
             _dispatchUpdate(client, {
-                update: new UpdateConnectionState(update),
+                update: new UpdateConnectionState(update)
             });
             return;
         }
@@ -83,6 +88,7 @@ export function _handleUpdate(
     }
 }
 
+/** @hidden */
 export function _processUpdate(
     client: TelegramClient,
     update: any,
@@ -92,12 +98,13 @@ export function _processUpdate(
     update._entities = entities || new Map();
     const args = {
         update: update,
-        others: others,
+        others: others
     };
 
     _dispatchUpdate(client, args);
 }
 
+/** @hidden */
 export async function _dispatchUpdate(
     client: TelegramClient,
     args: { update: UpdateConnectionState | any }
@@ -136,6 +143,7 @@ export async function _dispatchUpdate(
     }
 }
 
+/** @hidden */
 export async function _updateLoop(client: TelegramClient): Promise<void> {
     while (client.connected) {
         const rnd = helpers.getRandomInt(
@@ -148,7 +156,7 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
         try {
             client._sender!.send(
                 new Api.Ping({
-                    pingId: bigInt(rnd),
+                    pingId: bigInt(rnd)
                 })
             );
         } catch (e) {
@@ -166,7 +174,8 @@ export async function _updateLoop(client: TelegramClient): Promise<void> {
         ) {
             try {
                 await client.invoke(new Api.updates.GetState());
-            } catch (e) {}
+            } catch (e) {
+            }
         }
     }
 }

+ 2 - 2
gramjs/client/uploads.ts

@@ -233,7 +233,7 @@ interface FileToMediaInterface {
     asImage?: boolean;
     workers?: number;
 }
-
+/** @hidden */
 async function _fileToMedia(
     client: TelegramClient,
     {
@@ -410,7 +410,7 @@ async function _fileToMedia(
         image: asImage,
     };
 }
-
+/** @hidden */
 export async function sendFile(
     client: TelegramClient,
     entity: EntityLike,

+ 43 - 31
gramjs/client/users.ts

@@ -9,12 +9,7 @@ import bigInt from "big-integer";
 // UserMethods {
 // region Invoking Telegram request
 
-/**
- * Invokes a MTProtoRequest (sends and receives it) and returns its result
- * @param client
- * @param request
- * @returns {Promise}
- */
+/** @hidden */
 export async function invoke<R extends Api.AnyRequest>(
     client: TelegramClient,
     request: R
@@ -80,6 +75,7 @@ export async function invoke<R extends Api.AnyRequest>(
     throw new Error(`Request was unsuccessful ${attempt} time(s)`);
 }
 
+/** @hidden */
 export async function getMe(
     client: TelegramClient,
     inputPeer = false
@@ -110,6 +106,7 @@ export async function getMe(
     }
 }
 
+/** @hidden */
 export async function isBot(client: TelegramClient) {
     if (client._bot === undefined) {
         const me = await client.getMe();
@@ -120,6 +117,7 @@ export async function isBot(client: TelegramClient) {
     return client._bot;
 }
 
+/** @hidden */
 export async function isUserAuthorized(client: TelegramClient) {
     try {
         await client.invoke(new Api.updates.GetState());
@@ -129,6 +127,7 @@ export async function isUserAuthorized(client: TelegramClient) {
     }
 }
 
+/** @hidden */
 export async function getEntity(
     client: TelegramClient,
     entity: EntityLike | EntityLike[]
@@ -152,12 +151,13 @@ 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 +166,7 @@ export async function getEntity(
     if (users.length) {
         users = await client.invoke(
             new Api.users.GetUsers({
-                id: users,
+                id: users
             })
         );
     }
@@ -213,6 +213,7 @@ export async function getEntity(
     return single ? result[0] : result;
 }
 
+/** @hidden */
 export async function getInputEntity(
     client: TelegramClient,
     peer: EntityLike
@@ -222,7 +223,8 @@ 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')
@@ -236,7 +238,8 @@ 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)) {
@@ -250,7 +253,8 @@ 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));
@@ -266,9 +270,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)) {
@@ -283,7 +287,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 {
@@ -292,9 +296,9 @@ export async function getInputEntity(
                     id: [
                         new Api.InputChannel({
                             channelId: peer.channelId,
-                            accessHash: bigInt.zero,
-                        }),
-                    ],
+                            accessHash: bigInt.zero
+                        })
+                    ]
                 })
             );
 
@@ -308,11 +312,12 @@ export async function getInputEntity(
     throw new Error(
         `Could not find the input entity for ${JSON.stringify(peer)}.
          Please read https://` +
-            "docs.telethon.dev/en/latest/concepts/entities.html to" +
-            " find out more details."
+        "docs.telethon.dev/en/latest/concepts/entities.html to" +
+        " find out more details."
     );
 }
 
+/** @hidden */
 export async function _getEntityFromString(
     client: TelegramClient,
     string: string
@@ -322,7 +327,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)) {
@@ -336,7 +341,7 @@ export async function _getEntityFromString(
             if (e.errorMessage === "BOT_METHOD_INVALID") {
                 throw new Error(
                     "Cannot get entity by phone number as a " +
-                        "bot (try using integer IDs, not strings)"
+                    "bot (try using integer IDs, not strings)"
                 );
             }
             throw e;
@@ -348,13 +353,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;
@@ -389,6 +394,7 @@ export async function _getEntityFromString(
     throw new Error(`Cannot find any entity corresponding to "${string}"`);
 }
 
+/** @hidden */
 export async function getPeerId(
     client: TelegramClient,
     peer: EntityLike,
@@ -410,6 +416,7 @@ export async function getPeerId(
     return utils.getPeerId(peer, addMark);
 }
 
+/** @hidden */
 export async function _getPeer(client: TelegramClient, peer: EntityLike) {
     if (!peer) {
         return undefined;
@@ -418,10 +425,11 @@ export async function _getPeer(client: TelegramClient, peer: EntityLike) {
     return new cls({
         userId: i,
         channelId: i,
-        chatId: i,
+        chatId: i
     });
 }
 
+/** @hidden */
 export async function _getInputDialog(client: TelegramClient, dialog: any) {
     try {
         if (dialog.SUBCLASS_OF_ID == 0xa21c9795) {
@@ -431,15 +439,17 @@ 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
     });
 }
 
+/** @hidden */
 export async function _getInputNotify(client: TelegramClient, notify: any) {
     try {
         if (notify.SUBCLASS_OF_ID == 0x58981615) {
@@ -448,12 +458,14 @@ 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)
     });
 }
 
+/** @hidden */
 export function _selfId(client: TelegramClient) {
     return client._selfInputPeer ? client._selfInputPeer.userId : undefined;
 }

+ 1 - 1
gramjs/extensions/Logger.ts

@@ -17,7 +17,7 @@ export class Logger {
 
     constructor(level?: string) {
         if (!_level) {
-            _level = level || "debug";
+            _level = level || "info"; // defaults to info
         }
         this.isBrowser = !IS_NODE;
         if (!this.isBrowser) {

+ 1 - 1
package.json

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

+ 2 - 1
type_doc.js

@@ -5,7 +5,8 @@ module.exports = {
     "**/network/**/*",
     "**/example/**/*",
     "**/extensions/**/*",
-    "**/*+(Password|Version|RequestIter|entityCache).ts",
+    "**/tl/custom/**/*",
+    "**/*+(Password|Utils|Version|RequestIter|entityCache).ts",
     "**/*.js",
   ],
   sort: ["source-order"],