Hierarchy (view full)

Implements

Constructors

Properties

Methods

[captureRejectionSymbol]? _normalizeInputFile _normalizeInputMedia _normalizePrivacyRules addChatMembers addContact addListener addStickerToSet answerCallbackQuery answerInlineQuery answerMedia answerMediaGroup answerPreCheckoutQuery answerText applyBoost archiveChats banChatMember blockUser call canApplyBoost canSendStory cancelPasswordEmail changeCloudPassword changePrimaryDc checkPassword close closeChat closePoll commentMedia commentMediaGroup commentText computeNewPasswordHash computeSrpParams connect createBusinessChatLink createChannel createFolder createForumTopic createGroup createInviteLink createStickerSet createSupergroup deleteBusinessChatLink deleteChannel deleteChatPhoto deleteContacts deleteFolder deleteForumTopicHistory deleteGroup deleteHistory deleteMessages deleteMessagesById deleteMyCommands deleteProfilePhotos deleteScheduledMessages deleteStickerFromSet deleteStories deleteSupergroup deleteUserHistory downloadAsBuffer downloadAsIterable downloadAsNodeStream downloadAsStream downloadToFile editAdminRights editBusinessChatLink editCloseFriends editCloseFriendsRaw editFolder editForumTopic editInlineMessage editInviteLink editMessage editStory emit emitError enableCloudPassword eventNames exportInviteLink exportSession findDialogs findFolder forwardMessages forwardMessagesById getAllScheduledMessages getAllStories getApiCrenetials getAvailableMessageEffects getBoostStats getBoosts getBotInfo getBotMenuButton getBusinessChatLinks getBusinessConnection getCallbackAnswer getCallbackQueryMessage getChat getChatEventLog getChatMember getChatMembers getChatPreview getChatlistPreview getCollectibleInfo getCommonChats getContacts getCustomEmojis getCustomEmojisFromMessages getDiscussionMessage getFactCheck getFolders getForumTopics getForumTopicsById getFullChat getGameHighScores getGlobalTtl getHistory getInlineGameHighScores getInstalledStickers getInviteLink getInviteLinkMembers getInviteLinks getMaxListeners getMe getMessageByLink getMessageGroup getMessageReactions getMessageReactionsById getMessages getMessagesUnsafe getMtprotoMessageId getMyBoostSlots getMyCommands getMyStickerSets getMyUsername getNearbyChats getPasswordHint getPeerDialogs getPeerStories getPoolSize getPrimaryDcId getPrimaryInviteLink getProfilePhoto getProfilePhotos getProfileStories getReactionUsers getReplyTo getScheduledMessages getServerUpdateHandler getSimilarChannels getStarsTransactions getStickerSet getStoriesById getStoriesInteractions getStoryLink getStoryViewers getUsers handleClientUpdate hideAllJoinRequests hideJoinRequest hideMyStoriesViews importContacts importSession incrementStoriesViews initTakeoutSession isPeerAvailable isSelfPeer iterAllStories iterBoosters iterChatEventLog iterChatMembers iterDialogs iterForumTopics iterHistory iterInviteLinkMembers iterInviteLinks iterProfilePhotos iterProfileStories iterReactionUsers iterSearchGlobal iterSearchHashtag iterSearchMessages iterStarsTransactions iterStoryViewers joinChat joinChatlist kickChatMember leaveChat listenerCount listeners logOut markChatUnread moveStickerInSet notifyChannelClosed notifyChannelOpened notifyLoggedIn notifyLoggedOut off on onConnectionState onError onServerUpdate onUpdate once openChat pinMessage prepare prependListener prependOnceListener quoteWithMedia quoteWithMediaGroup quoteWithText rawListeners readHistory readReactions readStories recoverPassword removeAllListeners removeCloudPassword removeListener reorderPinnedForumTopics reorderUsernames replaceStickerInSet replyMedia replyMediaGroup replyText reportStory resendCode resendPasswordEmail resolveChannel resolvePeer resolvePeerMany resolveUser restrictChatMember revokeInviteLink run saveDraft searchGlobal searchHashtag searchMessages sendCode sendCopy sendCopyGroup sendMedia sendMediaGroup sendPaidReaction sendReaction sendRecoveryCode sendScheduled sendStory sendStoryReaction sendText sendTyping sendVote setBotInfo setBotMenuButton setBusinessIntro setBusinessWorkHours setChatColor setChatDefaultPermissions setChatDescription setChatPhoto setChatStickerSet setChatTitle setChatTtl setChatUsername setFoldersOrder setGameScore setGlobalTtl setInlineGameScore setMaxListeners setMyBirthday setMyCommands setMyDefaultRights setMyEmojiStatus setMyProfilePhoto setMyUsername setOffline setSlowMode setStickerSetThumb signIn signInBot signInQr start startTest startUpdatesLoop stopUpdatesLoop toggleContentProtection toggleForum toggleForumTopicClosed toggleForumTopicPinned toggleFragmentUsername toggleGeneralTopicHidden toggleJoinRequests toggleJoinToSend togglePeerStoriesArchived toggleStoriesPinned translateMessage translateText unarchiveChats unbanChatMember unblockUser unpinAllMessages unpinMessage unrestrictChatMember updateProfile uploadFile uploadMedia verifyPasswordEmail withParams addAbortListener getEventListeners getMaxListeners listenerCount on once setMaxListeners

Constructors

Properties

appConfig: PublicPart<AppConfigManager>
log: Logger
stopSignal: AbortSignal
captureRejectionSymbol: typeof captureRejectionSymbol

Value: Symbol.for('nodejs.rejection')

See how to write a custom rejection handler.

v13.4.0, v12.16.0

captureRejections: boolean

Value: boolean

Change the default captureRejections option on all new EventEmitter objects.

v13.4.0, v12.16.0

defaultMaxListeners: number

By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual EventEmitter instances using the emitter.setMaxListeners(n) method. To change the default for allEventEmitter instances, the events.defaultMaxListenersproperty can be used. If this value is not a positive number, a RangeErroris thrown.

Take caution when setting the events.defaultMaxListeners because the change affects allEventEmitter instances, including those created before the change is made. However, calling emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners.

This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a "possible EventEmitter memory leak" has been detected. For any singleEventEmitter, the emitter.getMaxListeners() and emitter.setMaxListeners()methods can be used to temporarily avoid this warning:

import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});

The --trace-warnings command-line flag can be used to display the stack trace for such warnings.

The emitted warning can be inspected with process.on('warning') and will have the additional emitter, type, and count properties, referring to the event emitter instance, the event's name and the number of attached listeners, respectively. Its name property is set to 'MaxListenersExceededWarning'.

v0.11.2

errorMonitor: typeof errorMonitor

This symbol shall be used to install a listener for only monitoring 'error'events. Listeners installed using this symbol are called before the regular'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an'error' event is emitted. Therefore, the process will still crash if no regular 'error' listener is installed.

v13.6.0, v12.17.0

Methods

  • Parameters

    • error: Error
    • event: string
    • Rest...args: any[]

    Returns void

  • Normalize a InputFileLike to InputFile, uploading it if needed. Available: ✅ both users and bots

    Parameters

    • input: InputFileLike
    • params: {
          fileMime?: string;
          fileName?: string;
          fileSize?: number;
          progressCallback?: ((uploaded: number, total: number) => void);
      }
      • OptionalfileMime?: string
      • OptionalfileName?: string
      • OptionalfileSize?: number
      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)
          • (uploaded, total): void
          • Parameters

            • uploaded: number
            • total: number

            Returns void

    Returns Promise<TypeInputFile>

  • Normalize an InputMediaLike to InputMedia, uploading the file if needed. Available: ✅ both users and bots

    Parameters

    • media: InputMediaLike
    • Optionalparams: {
          businessConnectionId?: string;
          progressCallback?: ((uploaded: number, total: number) => void);
          uploadPeer?: TypeInputPeer;
      }
      • OptionalbusinessConnectionId?: string
      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)
          • (uploaded, total): void
          • Parameters

            • uploaded: number
            • total: number

            Returns void

      • OptionaluploadPeer?: TypeInputPeer
    • OptionaluploadMedia: boolean

    Returns Promise<TypeInputMedia>

  • Add one or more new members to a group, supergroup or channel.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      ID of the chat or its username

    • users: MaybeArray<InputPeerLike>

      ID(s) of the user(s) to add

    • params: {
          forwardCount?: number;
      }
      • OptionalforwardCount?: number

        Number of old messages to be forwarded (0-100). Only applicable to legacy groups, ignored for supergroups and channels

        100
        

    Returns Promise<RawMissingInvitee[]>

    List of users that were failed to be invited (may be empty)

  • Add an existing Telegram user as a contact Available: 👤 users only

    Parameters

    • params: {
          firstName: string;
          lastName?: string;
          phone?: string;
          sharePhone?: boolean;
          userId: InputPeerLike;
      }
      • firstName: string

        First name of the contact

      • OptionallastName?: string

        Last name of the contact

      • Optionalphone?: string

        Phone number of the contact, if available

      • OptionalsharePhone?: boolean

        Whether to share your own phone number with the newly created contact

        false
        
      • userId: InputPeerLike

        User ID, username or phone number

    Returns Promise<User>

  • Alias for emitter.on(eventName, listener).

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.26

  • Add a sticker to a sticker set.

    For bots the sticker set must have been created by this bot.

    Available: ✅ both users and bots

    Parameters

    • setId: InputStickerSet

      Sticker set short name or TL object with input sticker set

    • sticker: InputStickerSetItem

      Sticker to be added

    • Optionalparams: {
          progressCallback?: ((uploaded: number, total: number) => void);
      }
      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)

        Upload progress callback

          • (uploaded, total): void
          • Parameters

            • uploaded: number

              Number of bytes uploaded

            • total: number

              Total file size

            Returns void

    Returns Promise<StickerSet>

    Modfiied sticker set

  • Send an answer to a callback query.

    Available: 🤖 bots only

    Parameters

    • queryId: Long | CallbackQuery

      ID of the callback query, or the query itself

    • Optionalparams: {
          alert?: boolean;
          cacheTime?: number;
          text?: string;
          url?: string;
      }

      Parameters of the answer

      • Optionalalert?: boolean

        Whether to show an alert in the middle of the screen instead of a notification at the top of the screen.

        false
        
      • OptionalcacheTime?: number

        Maximum amount of time in seconds for which this result can be cached by the client (not server!).

        0
        
      • Optionaltext?: string

        Text of the notification (0-200 chars).

        If not set, nothing will be displayed

      • Optionalurl?: string

        URL that the client should open.

        If this was a button containing a game, you can provide arbitrary link to your game. Otherwise, you can only use links in the format t.me/your_bot?start=... that open your bot with a deep-link parameter.

    Returns Promise<void>

  • Answer an inline query.

    Available: 🤖 bots only

    Parameters

    • queryId: Long | InlineQuery

      Inline query ID

    • results: InputInlineResult[]

      Results of the query

    • Optionalparams: {
          cacheTime?: number;
          gallery?: boolean;
          nextOffset?: string;
          private?: boolean;
          switchPm?: {
              parameter: string;
              text: string;
          };
          switchWebview?: {
              text: string;
              url: string;
          };
      }

      Additional parameters

      • OptionalcacheTime?: number

        Maximum number of time in seconds that the results of the query may be cached on the server for.

        300
        
      • Optionalgallery?: boolean

        Whether the results should be displayed as a gallery instead of a vertical list. Only applicable to some media types.

        In some cases changing this may lead to the results not being displayed by the client.

        Default is derived automatically based on result types

      • OptionalnextOffset?: string

        Next pagination offset (up to 64 bytes).

        When user has reached the end of the current results, the client will re-send the inline query with the same text, but with offset set to this value.

        If omitted or empty string is provided, it is assumed that there are no more results.

      • Optionalprivate?: boolean

        Whether the results should only be cached on the server for the user who sent the query.

        false
        
      • OptionalswitchPm?: {
            parameter: string;
            text: string;
        }

        If passed, clients will display a button before any other results, that when clicked switches the user to a private chat with the bot and sends the bot /start ${parameter}.

        An example from the Bot API docs:

        An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a "Connect your YouTube account" button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities

        • parameter: string

          Parameter for /start command

        • text: string

          Text of the button

      • OptionalswitchWebview?: {
            text: string;
            url: string;
        }

        If passed, clients will display a button on top of the remaining inline result list with the specified text, that switches the user to the specified bot web app.

        • text: string

          Text of the button

        • url: string

          URL to open

    Returns Promise<void>

  • Send a media to the same chat (and topic, if applicable) as a given message

    Parameters

    • message: Message
    • Rest...params: [media: string | InputMediaLike, params?: CommonSendParams & {
          caption?: InputText;
          invert?: boolean;
          progressCallback?: ((uploaded: number, total: number) => void);
          replyMarkup?: ReplyMarkup;
      }]

    Returns Promise<Message>

  • Send a media group to the same chat (and topic, if applicable) as a given message

    Parameters

    • message: Message
    • Rest...params: [medias: (string | InputMediaLike)[], params?: CommonSendParams & {
          invertMedia?: boolean;
          progressCallback?: ((index: number, uploaded: number, total: number) => void);
      }]

    Returns Promise<Message[]>

  • Answer a pre-checkout query.

    Available: 🤖 bots only

    Parameters

    • queryId: Long | PreCheckoutQuery

      Pre-checkout query ID

    • Optionalparams: {
          error?: string;
      }
      • Optionalerror?: string

        If pre-checkout is rejected, error message to show to the user

    Returns Promise<void>

  • Send a text to the same chat (and topic, if applicable) as a given message

    Parameters

    • message: Message
    • Rest...params: [text: InputText, params?: CommonSendParams & {
          disableWebPreview?: boolean;
          invertMedia?: boolean;
          replyMarkup?: ReplyMarkup;
      }]

    Returns Promise<Message>

  • Ban a user/channel from a legacy group, a supergroup or a channel. They will not be able to re-join the group on their own, manual administrator's action will be required.

    When banning a channel, the user won't be able to use any of their channels to post until the ban is lifted.

    Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          participantId: InputPeerLike;
          shouldDispatch?: true;
          untilDate?: number | Date;
      }
      • chatId: InputPeerLike

        Chat ID

      • participantId: InputPeerLike

        ID of the user/channel to ban

      • OptionalshouldDispatch?: true

        Whether to dispatch the returned service message (if any) to the client's update handler.

      • OptionaluntilDate?: number | Date

    Returns Promise<null | Message>

    Service message about removed user, if one was generated.

  • Check if the current user can apply boost to some channel

    Available: ✅ both users and bots

    Returns Promise<CanApplyBoostResult>

    • { can: true } if the user can apply boost
      • .replace - Chats that can be replaced with the current one. If the user can apply boost without replacing any chats, this field will be undefined.
      • { can: false } if the user can't apply boost
        • .reason == "no_slots" if the user has no available slots
        • .reason == "need_premium" if the user needs Premium to boost
      • In all cases, slots will contain all the current user's boost slots
  • Cancel the code that was sent to verify an email to use as 2FA recovery method Available: 👤 users only

    Returns Promise<void>

  • Change your 2FA password Available: 👤 users only

    Parameters

    • params: {
          currentPassword: string;
          hint?: string;
          newPassword: string;
      }
      • currentPassword: string

        Current password as plaintext

      • Optionalhint?: string

        Hint for the new password

      • newPassword: string

        New password as plaintext

    Returns Promise<void>

  • Check your Two-Step verification password and log in

    Available: 👤 users only

    Parameters

    • password: string

      Your Two-Step verification password

    Returns Promise<User>

    The authorized user

    BadRequestError In case the password is invalid

  • Inform the library that the user has closed a chat. Un-does the effect of openChat.

    Some library logic depends on this, for example, the library will periodically ping the server to keep the updates flowing.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Close a poll sent by you.

    Once closed, poll can't be re-opened, and nobody will be able to vote in it Available: ✅ both users and bots

    Parameters

    Returns Promise<Poll>

  • Send a text comment to a given message.

    If this is a normal message (not a channel post), a simple reply will be sent.

    Available: ✅ both users and bots

    Parameters

    • message: Message
    • Rest...params: [media: string | InputMediaLike, params?: CommonSendParams & {
          caption?: InputText;
          invert?: boolean;
          progressCallback?: ((uploaded: number, total: number) => void);
          replyMarkup?: ReplyMarkup;
      }]

    Returns Promise<Message>

    MtArgumentError If this is a channel post which does not have comments section. To check if a post has comments, use Message#replies.hasComments

  • Send a text comment to a given message.

    If this is a normal message (not a channel post), a simple reply will be sent.

    Available: ✅ both users and bots

    Parameters

    • message: Message
    • Rest...params: [medias: (string | InputMediaLike)[], params?: CommonSendParams & {
          invertMedia?: boolean;
          progressCallback?: ((index: number, uploaded: number, total: number) => void);
      }]

    Returns Promise<Message[]>

    MtArgumentError If this is a channel post which does not have comments section. To check if a post has comments, use Message#replies.hasComments

  • Send a text comment to a given message.

    If this is a normal message (not a channel post), a simple reply will be sent.

    Available: ✅ both users and bots

    Parameters

    • message: Message
    • Rest...params: [text: InputText, params?: CommonSendParams & {
          disableWebPreview?: boolean;
          invertMedia?: boolean;
          replyMarkup?: ReplyMarkup;
      }]

    Returns Promise<Message>

    MtArgumentError If this is a channel post which does not have comments section. To check if a post has comments, use Message#replies.hasComments

  • Create a new broadcast channel

    Available: 👤 users only

    Parameters

    • params: {
          description?: string;
          title: string;
      }
      • Optionaldescription?: string

        Channel description

      • title: string

        Channel title

    Returns Promise<Chat>

    Newly created channel

  • Create a topic in a forum

    Only admins with manageTopics permission can do this.

    Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          icon?: number | Long;
          sendAs?: InputPeerLike;
          shouldDispatch?: true;
          title: string;
      }
      • chatId: InputPeerLike

        Chat ID or username

      • Optionalicon?: number | Long

        Icon of the topic.

        Can be a number (color in RGB, see ForumTopic static members for allowed values) or a custom emoji ID.

        Icon color can't be changed after the topic is created.

      • OptionalsendAs?: InputPeerLike

        Send as a specific channel

      • OptionalshouldDispatch?: true

        Whether to dispatch the returned service message (if any) to the client's update handler.

      • title: string

        Topic title

    Returns Promise<Message>

    Service message for the created topic

  • Create a legacy group chat

    If you want to create a supergroup, use createSupergroup instead. Available: 👤 users only

    Parameters

    • params: {
          title: string;
          ttlPeriod?: number;
          users: MaybeArray<InputPeerLike>;
      }
      • title: string

        Group title

      • OptionalttlPeriod?: number

        TTL period (in seconds) for the newly created chat

        0 (i.e. messages don't expire)
        
      • users: MaybeArray<InputPeerLike>

        User(s) to be invited in the group (ID(s), username(s) or phone number(s)). Due to Telegram limitations, you can't create a legacy group with just yourself.

    Returns Promise<CreateGroupResult>

  • Create an additional invite link for the chat.

    You must be an administrator and have appropriate rights.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalparams: {
          expires?: number | Date;
          usageLimit?: number;
          withApproval?: boolean;
      }
      • Optionalexpires?: number | Date

        Date when this link will expire. If number is passed, UNIX time in ms is expected.

      • OptionalusageLimit?: number

        Maximum number of users that can be members of this chat at the same time after joining using this link.

        Integer in range [1, 99999] or Infinity

        Infinity

      • OptionalwithApproval?: boolean

        Whether users to be joined via this link need to be approved by an admin

    Returns Promise<ChatInviteLink>

  • Create a new sticker set.

    Available: ✅ both users and bots

    Parameters

    • params: {
          adaptive?: boolean;
          owner: InputPeerLike;
          progressCallback?: ((idx: number, uploaded: number, total: number) => void);
          shortName: string;
          sourceType?: StickerSourceType;
          stickers: InputStickerSetItem[];
          thumb?: InputFileLike;
          title: string;
          type?: StickerType;
      }
      • Optionaladaptive?: boolean

        Whether to create "adaptive" emoji set.

        Color of the emoji will be changed depending on the text color. Only works for TGS-based emoji stickers

      • owner: InputPeerLike

        Owner of the sticker set (must be user).

        If this pack is created from a user account, can only be "self"

      • OptionalprogressCallback?: ((idx: number, uploaded: number, total: number) => void)

        Upload progress callback.

          • (idx, uploaded, total): void
          • Parameters

            • idx: number

              Index of the sticker

            • uploaded: number

              Number of bytes uploaded

            • total: number

              Total file size

            Returns void

      • shortName: string

        Short name of the sticker set. Can only contain English letters, digits and underscores (i.e. must match /^[a-zA-Z0-9_]+$/), and (for bots) must end with by (` is case-insensitive).

      • OptionalsourceType?: StickerSourceType

        File source type for the stickers in this set.

        static, i.e. regular WEBP stickers.

      • stickers: InputStickerSetItem[]

        List of stickers to be immediately added into the pack. There must be at least one sticker in this list.

      • Optionalthumb?: InputFileLike

        Thumbnail for the set.

        The file must be either a .png file up to 128kb, having size of exactly 100x100 px, or a .tgs file up to 32kb.

        If not set, Telegram will use the first sticker in the sticker set as the thumbnail

      • title: string

        Title of the sticker set (1-64 chars)

      • Optionaltype?: StickerType

        Type of the stickers in this set.

        sticker, i.e. regular stickers.

    Returns Promise<StickerSet>

    Newly created sticker set

  • Create a new supergroup

    Available: 👤 users only

    Parameters

    • params: {
          description?: string;
          forum?: boolean;
          title: string;
          ttlPeriod?: number;
      }
      • Optionaldescription?: string

        Supergroup description

      • Optionalforum?: boolean

        Whether to create a forum

      • title: string

        Supergroup title

      • OptionalttlPeriod?: number

        TTL period (in seconds) for the newly created supergroup

        0 (i.e. messages don't expire)
        

    Returns Promise<Chat>

    Newly created supergroup

  • Delete a chat photo

    You must be an administrator and have the appropriate permissions.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Delete one or more contacts from your Telegram contacts list

    Returns deleted contact's profiles. Does not return profiles of users that were not in your contacts list

    Available: 👤 users only

    Parameters

    Returns Promise<User[]>

  • Delete a forum topic and all its history

    Available: ✅ both users and bots

    Parameters

    • chat: InputPeerLike

      Chat or user ID, username, phone number, "me" or "self"

    • topicId: number | ForumTopic

      ID of the topic (i.e. its top message ID)

    • Optionalparams: {
          shouldDispatch?: true;
      }
      • OptionalshouldDispatch?: true

        Whether to dispatch updates that will be generated by this call. Doesn't follow disableNoDispatch

    Returns Promise<void>

  • Delete communication history (for private chats and legacy groups) Available: 👤 users only

    Parameters

    • chat: InputPeerLike
    • Optionalparams: {
          maxId?: number;
          mode: "delete" | "revoke" | "clear";
      }
      • OptionalmaxId?: number

        Maximum ID of message to delete.

        0, i.e. remove all messages
        
      • mode: "delete" | "revoke" | "clear"

        Deletion mode. Can be:

        • delete: delete messages (only for yourself) AND the dialog itself
        • clear: delete messages (only for yourself), but keep the dialog in the list
        • revoke: delete messages for all users
        'delete'
        

    Returns Promise<void>

  • Delete scheduled messages by their IDs.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat's marked ID, its username, phone or "me" or "self".

    • ids: number[]

      Message(s) ID(s) to delete.

    Returns Promise<void>

  • Delete all messages of a user (or channel) in a supergroup Available: 👤 users only

    Parameters

    • params: {
          chatId: InputPeerLike;
          participantId: InputPeerLike;
          shouldDispatch?: true;
      }
      • chatId: InputPeerLike

        Chat ID

      • participantId: InputPeerLike

        User/channel ID whose messages to delete

      • OptionalshouldDispatch?: true

        Whether to dispatch the updates that will be generated by this call. Doesn't follow disableNoDispatch

    Returns Promise<void>

  • Download a file and return its contents as a Buffer.

    Note: This method will download the entire file into memory at once. This might cause an issue, so use wisely!

    Available: ✅ both users and bots

    Parameters

    Returns Promise<Uint8Array>

  • Download a file and return it as an iterable, which yields file contents in chunks of a given size. Order of the chunks is guaranteed to be consecutive.

    Available: 👤 users only

    Parameters

    Returns AsyncIterableIterator<Uint8Array>

  • Download a remote file to a local file (only for Node.js). Promise will resolve once the download is complete.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Edit "close friends" list directly using user IDs

    Available: 👤 users only

    Parameters

    • ids: number[]

      User IDs

    Returns Promise<void>

  • Edit a folder with given modification

    Available: 👤 users only

    Parameters

    • params: {
          folder: string | number | RawDialogFilter;
          modification: Partial<Omit<RawDialogFilter, "_" | "id">>;
      }
      • folder: string | number | RawDialogFilter

        Folder, folder ID or name. Note that passing an ID or name will require re-fetching all folders, and passing name might affect not the right folder if you have multiple with the same name.

      • modification: Partial<Omit<RawDialogFilter, "_" | "id">>

        Modification to be applied to this folder

    Returns Promise<RawDialogFilter>

    Modified folder

  • Modify a topic in a forum

    Only admins with manageTopics permission can do this.

    Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          icon?: null | Long;
          shouldDispatch?: true;
          title?: string;
          topicId: number | ForumTopic;
      }
      • chatId: InputPeerLike

        Chat ID or username

      • Optionalicon?: null | Long

        New icon of the topic.

        Can be a custom emoji ID, or null to remove the icon and use static color instead

      • OptionalshouldDispatch?: true

        Whether to dispatch the returned service message (if any) to the client's update handler.

      • Optionaltitle?: string

        New topic title

      • topicId: number | ForumTopic

        ID of the topic (i.e. its top message ID)

    Returns Promise<Message>

    Service message about the modification

  • Edit sent inline message text, media and reply markup.

    Available: ✅ both users and bots

    Parameters

    • params: {
          disableWebPreview?: boolean;
          invertMedia?: boolean;
          media?: InputMediaLike;
          messageId: string | TypeInputBotInlineMessageID;
          progressCallback?: ((uploaded: number, total: number) => void);
          replyMarkup?: ReplyMarkup;
          text?: InputText;
      }
      • OptionaldisableWebPreview?: boolean

        Whether to disable links preview in this message

      • OptionalinvertMedia?: boolean

        Whether to invert media position.

        Currently only supported for web previews and makes the client render the preview above the caption and not below.

      • Optionalmedia?: InputMediaLike

        New message media

      • messageId: string | TypeInputBotInlineMessageID

        Inline message ID, either as a TL object, or as a TDLib and Bot API compatible string

      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)

        For media, upload progress callback.

          • (uploaded, total): void
          • Parameters

            • uploaded: number

              Number of bytes uploaded

            • total: number

              Total file size in bytes

            Returns void

      • OptionalreplyMarkup?: ReplyMarkup

        For bots: new reply markup. If omitted, existing markup will be removed.

      • Optionaltext?: InputText

        New message text

        When media is passed, media.caption is used instead

    Returns Promise<void>

  • Edit an invite link. You can only edit non-primary invite links.

    Only pass the fields that you want to modify.

    Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          expires?: number | Date;
          link: string | ChatInviteLink;
          usageLimit?: number;
          withApproval?: boolean;
      }
      • chatId: InputPeerLike

        Chat ID

      • Optionalexpires?: number | Date

        Date when this link will expire. If number is passed, UNIX time in ms is expected.

      • link: string | ChatInviteLink

        Invite link to edit

      • OptionalusageLimit?: number

        Maximum number of users that can be members of this chat at the same time after joining using this link.

        Integer in range [1, 99999] or Infinity,

      • OptionalwithApproval?: boolean

        Whether users to be joined via this link need to be approved by an admin

    Returns Promise<ChatInviteLink>

    Modified invite link

  • Edit message text, media, reply markup and schedule date.

    Available: ✅ both users and bots

    Parameters

    • params: InputMessageId & {
          businessConnectionId?: string;
          disableWebPreview?: boolean;
          invertMedia?: boolean;
          media?: InputMediaLike | undefined;
          progressCallback?: ((uploaded: number, total: number) => void);
          replyMarkup?: ReplyMarkup | undefined;
          scheduleDate?: number | Date;
          shouldDispatch?: true;
          text?: InputText | undefined;
      }

    Returns Promise<Message>

  • Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments to each.

    Returns true if the event had listeners, false otherwise.

    import { EventEmitter } from 'node:events';
    const myEmitter = new EventEmitter();

    // First listener
    myEmitter.on('event', function firstListener() {
    console.log('Helloooo! first listener');
    });
    // Second listener
    myEmitter.on('event', function secondListener(arg1, arg2) {
    console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
    });
    // Third listener
    myEmitter.on('event', function thirdListener(...args) {
    const parameters = args.join(', ');
    console.log(`event with parameters ${parameters} in third listener`);
    });

    console.log(myEmitter.listeners('event'));

    myEmitter.emit('event', 1, 2, 3, 4, 5);

    // Prints:
    // [
    // [Function: firstListener],
    // [Function: secondListener],
    // [Function: thirdListener]
    // ]
    // Helloooo! first listener
    // event with parameters 1, 2 in second listener
    // event with parameters 1, 2, 3, 4, 5 in third listener

    Parameters

    • eventName: string | symbol
    • Rest...args: any[]

    Returns boolean

    v0.1.26

  • Enable 2FA password on your account

    Note that if you pass email, EmailUnconfirmedError may be thrown, and you should use verifyPasswordEmail, resendPasswordEmail or cancelPasswordEmail, and the call this method again Available: 👤 users only

    Parameters

    • params: {
          email?: string;
          hint?: string;
          password: string;
      }
      • Optionalemail?: string

        Recovery email

      • Optionalhint?: string

        Hint for the new password

      • password: string

        2FA password as plaintext

    Returns Promise<void>

  • Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbols.

    import { EventEmitter } from 'node:events';

    const myEE = new EventEmitter();
    myEE.on('foo', () => {});
    myEE.on('bar', () => {});

    const sym = Symbol('symbol');
    myEE.on(sym, () => {});

    console.log(myEE.eventNames());
    // Prints: [ 'foo', 'bar', Symbol(symbol) ]

    Returns (string | symbol)[]

    v6.0.0

  • Try to find a dialog (dialogs) with a given peer (peers) by their ID, username or phone number.

    This might be an expensive call, as it will potentially iterate over all dialogs to find the one with the given peer

    Available: 👤 users only

    Parameters

    Returns Promise<Dialog[]>

    If a dialog with any of the given peers was not found

  • Find a folder by its parameter.

    Note: Searching by title and/or emoji might not be accurate since you can set the same title and/or emoji to multiple folders.

    Available: ✅ both users and bots

    Parameters

    • params: {
          emoji?: string;
          id?: number;
          title?: string;
      }

      Search parameters. At least one must be set.

      • Optionalemoji?: string

        Folder emoji

      • Optionalid?: number

        Folder ID

      • Optionaltitle?: string

        Folder title

    Returns Promise<null | RawDialogFilter>

  • Forward one or more messages by their IDs. You can forward no more than 100 messages at once.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<Message[]>

    Newly sent, forwarded messages in the destination chat.

  • Get all stories (e.g. to load the top bar) Available: 👤 users only

    Parameters

    • Optionalparams: {
          archived?: boolean;
          offset?: string;
      }
      • Optionalarchived?: boolean

        Whether to fetch stories from "archived" (or "hidden") peers

      • Optionaloffset?: string

        Offset from which to fetch stories

    Returns Promise<AllStories>

  • Gets information about a bot the current uzer owns (or the current bot) Available: ✅ both users and bots

    Parameters

    • params: {
          bot?: InputPeerLike;
          langCode?: string;
      }
      • Optionalbot?: InputPeerLike

        When called by a user, a bot the user owns must be specified. When called by a bot, must be empty

      • OptionallangCode?: string

        If passed, will retrieve the bot's description in the given language. If left empty, will retrieve the fallback description.

    Returns Promise<RawBotInfo>

  • Request a callback answer from a bot, i.e. click an inline button that contains data.

    Available: 👤 users only

    Parameters

    • params: InputMessageId & {
          data: string | Uint8Array;
          fireAndForget?: boolean;
          game?: boolean;
          password?: string;
          timeout?: number;
      }

    Returns Promise<RawBotCallbackAnswer>

  • Get chat event log ("Recent actions" in official clients).

    Only available for supergroups and channels, and requires (any) administrator rights.

    Results are returned in reverse chronological order (i.e. newest first) and event IDs are in direct chronological order (i.e. newer events have bigger event ID)

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike
    • Optionalparams: {
          filters?: InputChatEventFilters;
          limit?: number;
          maxId?: Long;
          minId?: Long;
          query?: string;
          users?: InputPeerLike[];
      }
      • Optionalfilters?: InputChatEventFilters

        Event filters. Can be a TL object, or one or more action types.

        Note that some filters are grouped in TL (i.e. info=true will return title_changed, username_changed and many more), and when passing one or more action types, they will be filtered locally.

      • Optionallimit?: number

        Limit the number of events returned.

        Note: when using filters, there will likely be less events returned than specified here. This limit is only used to limit the number of events to fetch from the server.

        If you need to limit the number of events returned, use iterChatEventLog instead.

        100
        
      • OptionalmaxId?: Long

        Maximum event ID to return, can be used as a base offset

      • OptionalminId?: Long

        Minimum event ID to return

      • Optionalquery?: string

        Search query

      • Optionalusers?: InputPeerLike[]

        List of users whose actions to return

    Returns Promise<ChatEvent[]>

  • Get a chunk of members of some chat.

    You can retrieve up to 200 members at once

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalparams: {
          limit?: number;
          offset?: number;
          query?: string;
          type?:
              | "mention"
              | "restricted"
              | "contacts"
              | "bots"
              | "banned"
              | "admins"
              | "all"
              | "recent";
      }

      Additional parameters

      • Optionallimit?: number

        Maximum number of members to be retrieved.

        Note: Telegram currently only allows you to ever retrieve at most 200 members, regardless of offset/limit. I.e. when passing offset=201 nothing will ever be returned.

        200
        
      • Optionaloffset?: number

        Sequential number of the first member to be returned.

      • Optionalquery?: string

        Search query to filter members by their display names and usernames

        Note: Only used for these values of filter: all, banned, restricted, mention, contacts

        '' (empty string)

      • Optionaltype?:
            | "mention"
            | "restricted"
            | "contacts"
            | "bots"
            | "banned"
            | "admins"
            | "all"
            | "recent"

        Type of the query. Can be:

        • all: get all members
        • banned: get only banned members
        • restricted: get only restricted members
        • bots: get only bots
        • recent: get recent members
        • admins: get only administrators (and creator)
        • contacts: get only contacts
        • mention: get users that can be mentioned (see tl.RawChannelParticipantsMentions)

        Only used for channels and supergroups.

        recent

    Returns Promise<ArrayWithTotal<ChatMember>>

  • Get preview information about a private chat.

    Available: 👤 users only

    Parameters

    • inviteLink: string

      Invite link

    Returns Promise<ChatPreview>

    MtArgumentError In case invite link has invalid format

    MtPeerNotFoundError In case you are trying to get info about private chat that you have already joined. Use getChat or getFullChat instead.

  • Get discussion message for some channel post.

    Returns null if the post does not have a discussion message.

    This method might throw FLOOD_WAIT_X error in case the discussion message was not yet created. Error is usually handled by the client, but if you disabled that, you'll need to handle it manually.

    Available: 👤 users only

    Parameters

    Returns Promise<null | Message>

  • Gets the current default value of the Time-To-Live setting, applied to all new chats. Available: 👤 users only

    Returns Promise<number>

  • Get chat history.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat's marked ID, its username, phone or "me" or "self".

    • Optionalparams: {
          addOffset?: number;
          limit?: number;
          maxId?: number;
          minId?: number;
          offset?: GetHistoryOffset;
          reverse?: boolean;
      }

      Additional fetch parameters

      • OptionaladdOffset?: number

        Additional offset from offset, in resulting messages.

        This can be used for advanced use cases, like:

        • Loading 20 messages newer than message with ID MSGID: offset = MSGID, addOffset = -20, limit = 20
        • Loading 20 messages around message with ID MSGID: offset = MSGID, addOffset = -10, limit = 20

        0 (disabled)

      • Optionallimit?: number

        Limits the number of messages to be retrieved.

        100
        
      • OptionalmaxId?: number

        Maximum message ID to return.

        Unless addOffset is used, this will work the same as offset.

        0 (disabled).

      • OptionalminId?: number

        Minimum message ID to return

        0 (disabled).

      • Optionaloffset?: GetHistoryOffset

        Offset for pagination

      • Optionalreverse?: boolean

        Whether to retrieve messages in reversed order (from older to recent), starting from offset (inclusive).

        Note: Using reverse=true requires you to pass offset from which to start fetching the messages "downwards". If you call getHistory with reverse=true and without any offset, it will return an empty array.

        false
        

    Returns Promise<ArrayPaginated<Message, GetHistoryOffset>>

  • Get a list of all installed sticker packs

    Note: This method returns brief meta information about the packs, that does not include the stickers themselves. Use getStickerSet to get a stickerset that will include the stickers Available: 👤 users only

    Returns Promise<StickerSet[]>

  • Iterate over users who have joined the chat with the given invite link.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalparams: {
          limit?: number;
          link?: string | ChatInviteLink;
          offsetDate?: number | Date;
          offsetUser?: TypeInputUser;
          requested?: boolean;
          requestedSearch?: string;
      }

      Additional params

      • Optionallimit?: number

        Maximum number of users to return

        100
        
      • Optionallink?: string | ChatInviteLink

        Invite link for which to get members

      • OptionaloffsetDate?: number | Date

        Offset request/join date used as an anchor for pagination.

      • OptionaloffsetUser?: TypeInputUser

        Offset user used as an anchor for pagination

      • Optionalrequested?: boolean

        Whether to get users who have requested to join the chat but weren't accepted yet

      • OptionalrequestedSearch?: string

        Search for a user in the pending join requests list (if passed, requested is assumed to be true)

        Doesn't work when link is set (Telegram limitation)

    Returns Promise<ArrayPaginated<ChatInviteLinkMember, {
        date: number;
        user: TypeInputUser;
    }>>

  • Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.

    Returns number

    v1.0.0

  • Get reactions to Messages.

    Note: messages must all be from the same chat.

    Apps should short-poll reactions for visible messages (that weren't sent by the user) once every 15-30 seconds, but only if message.reactions is set

    Available: ✅ both users and bots

    Parameters

    Returns Promise<(null | MessageReactions)[]>

    Reactions to corresponding messages, or null if there are none

  • Get reactions to messages by their IDs.

    Apps should short-poll reactions for visible messages (that weren't sent by the user) once every 15-30 seconds, but only if message.reactions is set

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      ID of the chat with messages

    • messages: number[]

      Message IDs

    Returns Promise<(null | MessageReactions)[]>

    Reactions to corresponding messages, or null if there are none

  • Get messages in chat by their IDs

    Fot messages that were not found, null will be returned at that position.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat's marked ID, its username, phone or "me" or "self"

    • messageIds: MaybeArray<number>

      Messages IDs

    • OptionalfromReply: boolean

      Whether the reply to a given message should be fetched (i.e. getMessages(msg.chat.id, msg.id, true).id === msg.replyToMessageId)

    Returns Promise<(null | Message)[]>

  • Get messages from PM or legacy group by their IDs. For channels, use getMessages.

    Unlike getMessages, this method does not check if the message belongs to some chat.

    Fot messages that were not found, null will be returned at that position.

    Available: ✅ both users and bots

    Parameters

    • messageIds: MaybeArray<number>

      Messages IDs

    • OptionalfromReply: boolean

      Whether the reply to a given message should be fetched (i.e. getMessages(msg.chat.id, msg.id, true).id === msg.replyToMessageId)

    Returns Promise<(null | Message)[]>

  • Get boost slots information of the current user.

    Includes information about the currently boosted channels, as well as the slots that can be used to boost other channels. Available: 👤 users only

    Returns Promise<BoostSlot[]>

  • Get currently authorized user's username.

    This method uses locally available information and does not call any API methods. Available: ✅ both users and bots

    Returns Promise<null | string>

  • Get nearby chats

    Available: 👤 users only

    Parameters

    • latitude: number

      Latitude of the location

    • longitude: number

      Longitude of the location

    Returns Promise<Chat[]>

  • Get your Two-Step Verification password hint.

    Available: 👤 users only

    Returns Promise<null | string>

    The password hint as a string, if any

  • Get a list of profile pictures of a user

    Available: ✅ both users and bots

    Parameters

    • userId: InputPeerLike

      User ID, username, phone number, "me" or "self"

    • Optionalparams: {
          limit?: number;
          offset?: number;
      }
      • Optionallimit?: number

        Maximum number of items to fetch (up to 100)

        100

      • Optionaloffset?: number

        Offset from which to fetch.

        0

    Returns Promise<ArrayPaginated<Photo, number>>

  • Get profile stories Available: 👤 users only

    Parameters

    • peerId: InputPeerLike
    • Optionalparams: {
          kind?: "pinned" | "archived";
          limit?: number;
          offsetId?: number;
      }
      • Optionalkind?: "pinned" | "archived"

        Kind of stories to fetch

        • pinned - stories pinned to the profile and visible to everyone
        • archived - "archived" stories that can later be pinned, only visible to the owner

        pinned

      • Optionallimit?: number

        Maximum number of stories to fetch

        100
        
      • OptionaloffsetId?: number

        Offset ID for pagination

    Returns Promise<ArrayPaginated<Story, number>>

  • For messages containing a reply, fetch the message that is being replied.

    Note that even if a message has replyToMessage, the message itself may have been deleted, in which case this method will also return null. Available: ✅ both users and bots

    Parameters

    Returns Promise<null | Message>

  • Get scheduled messages in chat by their IDs

    Fot messages that were not found, null will be returned at that position.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat's marked ID, its username, phone or "me" or "self"

    • messageIds: MaybeArray<number>

      Scheduled messages IDs

    Returns Promise<(null | Message)[]>

  • Get channels that are similar to a given channel

    Note: This method only returns the channels that the current user is not subscribed to. For non-premium users, this method will only return a few channels (with the total number of similar channels being specified in .total)

    Returns empty array in case there are no similar channels available. Available: 👤 users only

    Parameters

    Returns Promise<ArrayWithTotal<Chat>>

  • Get Telegram Stars transactions for a given peer.

    You can either pass self to get your own transactions, or a chat/bot ID to get transactions of that peer.

    Available: ✅ both users and bots

    Parameters

    • peerId: InputPeerLike

      Peer ID

    • Optionalparams: {
          direction?: "incoming" | "outgoing";
          limit?: number;
          offset?: string;
          sort?: "asc" | "desc";
          subscriptionId?: string;
      }

      Additional parameters

      • Optionaldirection?: "incoming" | "outgoing"

        If passed, only transactions of this direction will be returned

      • Optionallimit?: number

        Pagination limit

        100
        
      • Optionaloffset?: string

        Pagination offset

      • Optionalsort?: "asc" | "desc"

        Direction to sort transactions date by (default: desc)

      • OptionalsubscriptionId?: string

        If passed, will only return transactions related to this subscription ID

    Returns Promise<StarsStatus>

  • Generate a link to a story.

    Basically the link format is t.me/<username>/s/<story_id>, and if the user doesn't have a username, USER_PUBLIC_MISSING is thrown.

    I have no idea why is this an RPC call, but whatever Available: 👤 users only

    Parameters

    Returns Promise<string>

  • Get viewers list of a story Available: 👤 users only

    Parameters

    • peerId: InputPeerLike
    • storyId: number
    • Optionalparams: {
          limit?: number;
          offset?: string;
          onlyContacts?: boolean;
          query?: string;
          sortBy?: "date" | "reaction";
      }
      • Optionallimit?: number

        Maximum number of viewers to fetch

        100
        
      • Optionaloffset?: string

        Offset ID for pagination

      • OptionalonlyContacts?: boolean

        Whether to only fetch viewers from contacts

      • Optionalquery?: string

        Search query

      • OptionalsortBy?: "date" | "reaction"

        How to sort the results?

        • reaction - by reaction (viewers who has reacted are first), then by date (newest first)
        • date - by date, newest first

        reaction

    Returns Promise<StoryViewersList>

  • Get information about multiple users. You can retrieve up to 200 users at once.

    Note that order is not guaranteed.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<(null | User)[]>

  • Approve or decline multiple join requests to a chat. Available: 👤 users only

    Parameters

    • params: {
          action: "approve" | "decline";
          chatId: InputPeerLike;
          link?: string | ChatInviteLink;
      }
      • action: "approve" | "decline"

        Whether to approve or decline the join requests

      • chatId: InputPeerLike

        Chat/channel ID

      • Optionallink?: string | ChatInviteLink

        Invite link to target

    Returns Promise<void>

  • Approve or decline join request to a chat. Available: ✅ both users and bots

    Parameters

    • params: {
          action: "approve" | "decline";
          chatId: InputPeerLike;
          user: InputPeerLike;
      }
      • action: "approve" | "decline"

        Whether to approve or decline the join request

      • chatId: InputPeerLike

        Chat/channel ID

      • user: InputPeerLike

        User ID

    Returns Promise<void>

  • Hide own stories views (activate so called "stealth mode")

    Currently has a cooldown of 1 hour, and throws FLOOD_WAIT error if it is on cooldown. Available: 👤 users only

    Parameters

    • Optionalparams: {
          future?: boolean;
          past?: boolean;
      }
      • Optionalfuture?: boolean

        Whether to hide views for the next 25 minutes

        true
        
      • Optionalpast?: boolean

        Whether to hide views from the last 5 minutes

        true
        

    Returns Promise<StoriesStealthMode>

  • Increment views of one or more stories.

    This should be used for pinned stories, as they can't be marked as read when the user sees them (Story#isActive == false)

    Available: 👤 users only

    Parameters

    • peerId: InputPeerLike

      Peer ID whose stories to mark as read

    • ids: MaybeArray<number>

      ID(s) of the stories to increment views of (max 200)

    Returns Promise<void>

  • Check whether a given peer ID can be used to actually interact with the Telegram API. This method checks the internal peers cache for the given input peer, and returns true if it is available there.

    You can think of this method as a stripped down version of resolvePeer, which only returns true or false.

    Note: This method works offline and never sends any requests. This means that when passing a username or phone number, it will only return true if the user with that username/phone number is cached in the storage, and will not try to resolve the peer by calling the API, which may lead to false negatives.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<boolean>

  • Iterate over all stories (e.g. to load the top bar)

    Wrapper over getAllStories Available: ✅ both users and bots

    Parameters

    • Optionalparams: {
          archived?: boolean;
          offset?: string;
      } & {
          limit?: number;
      }

    Returns AsyncIterableIterator<PeerStories>

  • Iterate over boosters of a channel.

    Wrapper over getBoosters Available: ✅ both users and bots

    Parameters

    • peerId: InputPeerLike
    • Optionalparams: {
          limit?: number;
          offset?: string;
      } & {
          chunkSize?: number;
          limit?: number;
      }

    Returns AsyncIterableIterator<Boost>

  • Iterate through chat members

    This method is a small wrapper over getChatMembers, which also handles duplicate entries (i.e. does not yield the same member twice)

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalparams: {
          limit?: number;
          offset?: number;
          query?: string;
          type?:
              | "mention"
              | "restricted"
              | "contacts"
              | "bots"
              | "banned"
              | "admins"
              | "all"
              | "recent";
      } & {
          chunkSize?: number;
      }

      Additional parameters

    Returns AsyncIterableIterator<ChatMember>

  • Iterate over dialogs.

    Note that due to Telegram API limitations, ordering here can only be anti-chronological (i.e. newest - first), and draft update date is not considered when sorting.

    Available: 👤 users only

    Parameters

    • Optionalparams: {
          archived?: "exclude" | "only" | "keep";
          chunkSize?: number;
          filter?: Partial<Omit<RawDialogFilter, "_" | "id" | "title">>;
          folder?: InputDialogFolder;
          limit?: number;
          offsetDate?: number | Date;
          offsetId?: number;
          offsetPeer?: TypeInputPeer;
          pinned?:
              | "include"
              | "exclude"
              | "only"
              | "keep";
      }

      Fetch parameters

      • Optionalarchived?: "exclude" | "only" | "keep"

        How to handle archived chats?

        Whether to keep them among other dialogs, exclude them from the list, or only return archived dialogs

        Ignored for folders, since folders themselves contain information about archived chats.

        Note: when pinned=only, archived=keep will act as only because of Telegram API limitations.

        exclude

      • OptionalchunkSize?: number

        Chunk size which will be passed to messages.getDialogs. You shouldn't usually care about this.

        100.
        
      • Optionalfilter?: Partial<Omit<RawDialogFilter, "_" | "id" | "title">>

        Additional filtering for the dialogs.

        If folder is not provided, this filter is used instead. If folder is provided, fields from this object are used to override filters inside the folder.

      • Optionalfolder?: InputDialogFolder

        Folder from which the dialogs will be fetched.

        You can pass folder object, id or title

        Note that passing anything except object will cause the list of the folders to be fetched, and passing a title may fetch from a wrong folder if you have multiple with the same title.

        Also note that fetching dialogs in a folder is orders of magnitudes* slower than normal because of Telegram API limitations - we have to fetch all dialogs and filter the ones we need manually. If possible, use Dialog.filterFolder instead.

        When a folder with given ID or title is not found, MtArgumentError is thrown

        <empty> (fetches from "All" folder)
        
      • Optionallimit?: number

        Limits the number of dialogs to be received.

        Infinity, i.e. all dialogs are fetched

      • OptionaloffsetDate?: number | Date

        Offset message date used as an anchor for pagination.

      • OptionaloffsetId?: number

        Offset message ID used as an anchor for pagination

      • OptionaloffsetPeer?: TypeInputPeer

        Offset peer used as an anchor for pagination

      • Optionalpinned?:
            | "include"
            | "exclude"
            | "only"
            | "keep"

        How to handle pinned dialogs?

        Whether to include them at the start of the list, exclude them at all, or only return pinned dialogs.

        Additionally, for folders you can specify keep, which will return pinned dialogs ordered by date among other non-pinned dialogs.

        Note: When using include mode with folders, pinned dialogs will only be fetched if all offset parameters are unset.

        include.

    Returns AsyncIterableIterator<Dialog>

  • Iterate over chat history. Wrapper over getHistory

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat's marked ID, its username, phone or "me" or "self".

    • Optionalparams: {
          addOffset?: number;
          limit?: number;
          maxId?: number;
          minId?: number;
          offset?: GetHistoryOffset;
          reverse?: boolean;
      } & {
          chunkSize?: number;
          limit?: number;
      }

      Additional fetch parameters

    Returns AsyncIterableIterator<Message>

  • Iterate over users who have joined the chat with the given invite link.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalparams: {
          limit?: number;
          link?: string | ChatInviteLink;
          offsetDate?: number | Date;
          offsetUser?: TypeInputUser;
          requested?: boolean;
          requestedSearch?: string;
      } & {
          chunkSize?: number;
          limit?: number;
      }

      Additional params

    Returns AsyncIterableIterator<ChatInviteLinkMember>

  • Iterate over invite links created by some administrator in the chat.

    As an administrator you can only get your own links (i.e. adminId = "self"), as a creator you can get any other admin's links.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalparams: {
          admin?: InputPeerLike;
          limit?: number;
          offset?: GetInviteLinksOffset;
          revoked?: boolean;
      } & {
          chunkSize?: number;
          limit?: number;
      }

    Returns AsyncIterableIterator<ChatInviteLink>

  • Iterate over profile photos

    Available: ✅ both users and bots

    Parameters

    • userId: InputPeerLike

      User ID, username, phone number, "me" or "self"

    • Optionalparams: {
          limit?: number;
          offset?: number;
      } & {
          chunkSize?: number;
          limit?: number;
      }

    Returns AsyncIterableIterator<Photo>

  • Iterate over profile stories. Wrapper over getProfileStories Available: ✅ both users and bots

    Parameters

    • peerId: InputPeerLike
    • Optionalparams: {
          kind?: "pinned" | "archived";
          limit?: number;
          offsetId?: number;
      } & {
          chunkSize?: number;
          limit?: number;
      }

    Returns AsyncIterableIterator<Story>

  • Iterate over users who have reacted to the message.

    Wrapper over getReactionUsers.

    Available: ✅ both users and bots

    Parameters

    • params: (InputMessageId & { emoji?: InputReaction | undefined; limit?: number | undefined; offset?: string | undefined; }) & {
          chunkSize?: number;
          limit?: number;
      }

    Returns AsyncIterableIterator<PeerReaction>

  • Search for messages globally from all of your chats.

    Iterable version of searchGlobal

    Note: Due to Telegram limitations, you can only get up to ~10000 messages

    Available: ✅ both users and bots

    Parameters

    • Optionalparams: {
          filter?: TypeMessagesFilter;
          limit?: number;
          maxDate?: number | Date;
          minDate?: number | Date;
          offset?: SearchGlobalOffset;
          onlyChannels?: boolean;
          query?: string;
      } & {
          chunkSize?: number;
          limit?: number;
      }

      Search parameters

    Returns AsyncIterableIterator<Message>

  • Perform a global hashtag search, across the entire Telegram

    Iterable version of searchHashtag

    Available: ✅ both users and bots

    Parameters

    • hashtag: string

      Hashtag to search for

    • Optionalparams: {
          limit?: number;
          offset?: SearchHashtagOffset;
      } & {
          chunkSize?: number;
          limit?: number;
      }

      Additional parameters

    Returns AsyncIterableIterator<Message>

  • Search for messages inside a specific chat

    Iterable version of searchMessages

    Available: ✅ both users and bots

    Parameters

    • Optionalparams: {
          addOffset?: number;
          chatId?: InputPeerLike;
          filter?: TypeMessagesFilter;
          fromUser?: InputPeerLike;
          limit?: number;
          maxDate?: number | Date;
          maxId?: number;
          minDate?: number | Date;
          minId?: number;
          offset?: number;
          query?: string;
          threadId?: number;
      } & {
          chunkSize?: number;
          limit?: number;
      }

      Additional search parameters

    Returns AsyncIterableIterator<Message>

  • Iterate over Telegram Stars transactions for a given peer.

    You can either pass self to get your own transactions, or a chat/bot ID to get transactions of that peer.

    Wrapper over getStarsTransactions

    Available: ✅ both users and bots

    Parameters

    • peerId: InputPeerLike

      Peer ID

    • Optionalparams: {
          direction?: "incoming" | "outgoing";
          limit?: number;
          offset?: string;
          sort?: "asc" | "desc";
          subscriptionId?: string;
      } & {
          chunkSize?: number;
          limit?: number;
      }

      Additional parameters

    Returns AsyncIterableIterator<StarsTransaction>

  • Iterate over viewers list of a story. Wrapper over getStoryViewers Available: ✅ both users and bots

    Parameters

    • peerId: InputPeerLike
    • storyId: number
    • Optionalparams: {
          limit?: number;
          offset?: string;
          onlyContacts?: boolean;
          query?: string;
          sortBy?: "date" | "reaction";
      } & {
          chunkSize?: number;
          limit?: number;
      }

    Returns AsyncIterableIterator<StoryViewer>

  • Join a channel or supergroup

    When using with invite links, this method may throw RPC error INVITE_REQUEST_SENT, which means that you need to wait for admin approval. You will get into the chat once they do so.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat identifier. Either an invite link (t.me/joinchat/*), a username (@username) or ID of the linked supergroup or channel.

    Returns Promise<Chat>

  • Leave a group chat, supergroup or channel

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalparams: {
          clear?: boolean;
      }
      • Optionalclear?: boolean

        Whether to clear history after leaving (only for legacy group chats)

    Returns Promise<void>

  • Returns the number of listeners listening for the event named eventName. If listener is provided, it will return how many times the listener is found in the list of the listeners of the event.

    Parameters

    • eventName: string | symbol

      The name of the event being listened for

    • Optionallistener: Function

      The event handler function

    Returns number

    v3.2.0

  • Returns a copy of the array of listeners for the event named eventName.

    server.on('connection', (stream) => {
    console.log('someone connected!');
    });
    console.log(util.inspect(server.listeners('connection')));
    // Prints: [ [Function] ]

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v0.1.26

  • Move a sticker in a sticker set to another position

    For bots the sticker set must have been created by this bot.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<StickerSet>

    Modified sticker set

  • Alias for emitter.removeListener().

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v10.0.0

  • Adds a one-timelistener function for the event named eventName. The next time eventName is triggered, this listener is removed and then invoked.

    server.once('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

    import { EventEmitter } from 'node:events';
    const myEE = new EventEmitter();
    myEE.once('foo', () => console.log('a'));
    myEE.prependOnceListener('foo', () => console.log('b'));
    myEE.emit('foo');
    // Prints:
    // b
    // a

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.3.0

  • Inform the library that the user has opened a chat.

    Some library logic depends on this, for example, the library will periodically ping the server to keep the updates flowing.

    Warning: Opening a chat with openChat method will make the library make additional requests every so often. Which means that you should avoid opening more than 5-10 chats at once, as it will probably trigger server-side limits and you might start getting transport errors or even get banned.

    Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Pin a message in a group, supergroup, channel or PM.

    For supergroups/channels, you must have appropriate permissions, either as an admin, or as default permissions

    Available: ✅ both users and bots

    Parameters

    • params: InputMessageId & {
          bothSides?: boolean;
          notify?: boolean;
          shouldDispatch?: true;
      }

    Returns Promise<null | Message>

    Service message about pinned message, if one was generated.

  • Adds the listener function to the beginning of the listeners array for the event named eventName. No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple times.

    server.prependListener('connection', (stream) => {
    console.log('someone connected!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v6.0.0

  • Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

    server.prependOnceListener('connection', (stream) => {
    console.log('Ah, we have our first user!');
    });

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • eventName: string | symbol

      The name of the event.

    • listener: ((...args: any[]) => void)

      The callback function

        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v6.0.0

  • Send a media in reply to a given quote

    Parameters

    • message: Message
    • params: Omit<CommonSendParams & {
          caption?: InputText;
          invert?: boolean;
          progressCallback?: ((uploaded: number, total: number) => void);
          replyMarkup?: ReplyMarkup;
      }, "quoteText" | "quoteEntities"> & {
          end: number;
          start: number;
          toChatId?: InputPeerLike;
      } & {
          media: string | InputMediaLike;
      }

    Returns Promise<Message>

  • Send a media group in reply to a given quote

    Parameters

    • message: Message
    • params: Omit<CommonSendParams & {
          invertMedia?: boolean;
          progressCallback?: ((index: number, uploaded: number, total: number) => void);
      }, "quoteText" | "quoteEntities"> & {
          end: number;
          start: number;
          toChatId?: InputPeerLike;
      } & {
          medias: (string | InputMediaLike)[];
      }

    Returns Promise<Message[]>

  • Send a text in reply to a given quote

    Parameters

    • message: Message
    • params: Omit<CommonSendParams & {
          disableWebPreview?: boolean;
          invertMedia?: boolean;
          replyMarkup?: ReplyMarkup;
      }, "quoteText" | "quoteEntities"> & {
          end: number;
          start: number;
          toChatId?: InputPeerLike;
      } & {
          text: InputText;
      }

    Returns Promise<Message>

  • Returns a copy of the array of listeners for the event named eventName, including any wrappers (such as those created by .once()).

    import { EventEmitter } from 'node:events';
    const emitter = new EventEmitter();
    emitter.once('log', () => console.log('log once'));

    // Returns a new Array with a function `onceWrapper` which has a property
    // `listener` which contains the original listener bound above
    const listeners = emitter.rawListeners('log');
    const logFnWrapper = listeners[0];

    // Logs "log once" to the console and does not unbind the `once` event
    logFnWrapper.listener();

    // Logs "log once" to the console and removes the listener
    logFnWrapper();

    emitter.on('log', () => console.log('log persistently'));
    // Will return a new Array with a single function bound by `.on()` above
    const newListeners = emitter.rawListeners('log');

    // Logs "log persistently" twice
    newListeners[0]();
    emitter.emit('log');

    Parameters

    • eventName: string | symbol

    Returns Function[]

    v9.4.0

  • Mark chat history as read.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalparams: {
          clearMentions?: boolean;
          maxId?: number;
          shouldDispatch?: true;
      }
      • OptionalclearMentions?: boolean

        Whether to also clear all mentions in the chat

      • OptionalmaxId?: number

        Message up until which to read history

        0, i.e. read everything
        
      • OptionalshouldDispatch?: true

        Whether to dispatch updates that will be generated by this call. Doesn't follow disableNoDispatch

    Returns Promise<void>

  • Mark all reactions in chat as read.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalparams: {
          shouldDispatch?: true;
      }
      • OptionalshouldDispatch?: true

        Whether to dispatch updates that will be generated by this call. Doesn't follow disableNoDispatch

    Returns Promise<void>

  • Mark all stories up to a given ID as read

    This should only be used for "active" stories (Story#isActive == false)

    Available: 👤 users only

    Parameters

    • peerId: InputPeerLike

      Peer ID whose stories to mark as read

    • maxId: number

    Returns Promise<number[]>

    IDs of the stores that were marked as read

  • Recover your password with a recovery code and log in.

    Available: 👤 users only

    Parameters

    • params: {
          recoveryCode: string;
      }
      • recoveryCode: string

        The recovery code sent via email

    Returns Promise<User>

    The authorized user

    BadRequestError In case the code is invalid

  • Removes all listeners, or those of the specified eventName.

    It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • Optionalevent: string | symbol

    Returns this

    v0.1.26

  • Remove 2FA password from your account

    Available: 👤 users only

    Parameters

    • password: string

      2FA password as plaintext

    Returns Promise<void>

  • Removes the specified listener from the listener array for the event namedeventName.

    const callback = (stream) => {
    console.log('someone connected!');
    };
    server.on('connection', callback);
    // ...
    server.removeListener('connection', callback);

    removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName, then removeListener() must be called multiple times to remove each instance.

    Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them fromemit() in progress. Subsequent events behave as expected.

    import { EventEmitter } from 'node:events';
    class MyEmitter extends EventEmitter {}
    const myEmitter = new MyEmitter();

    const callbackA = () => {
    console.log('A');
    myEmitter.removeListener('event', callbackB);
    };

    const callbackB = () => {
    console.log('B');
    };

    myEmitter.on('event', callbackA);

    myEmitter.on('event', callbackB);

    // callbackA removes listener callbackB but it will still be called.
    // Internal listener array at time of emit [callbackA, callbackB]
    myEmitter.emit('event');
    // Prints:
    // A
    // B

    // callbackB is now removed.
    // Internal listener array [callbackA]
    myEmitter.emit('event');
    // Prints:
    // A

    Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

    When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once('ping')listener is removed:

    import { EventEmitter } from 'node:events';
    const ee = new EventEmitter();

    function pong() {
    console.log('pong');
    }

    ee.on('ping', pong);
    ee.once('ping', pong);
    ee.removeListener('ping', pong);

    ee.emit('ping');
    ee.emit('ping');

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • eventName: string | symbol
    • listener: ((...args: any[]) => void)
        • (...args): void
        • Parameters

          • Rest...args: any[]

          Returns void

    Returns this

    v0.1.26

  • Reorder pinned forum topics

    Only admins with manageTopics permission can do this. Available: 👤 users only

    Parameters

    • params: {
          chatId: InputPeerLike;
          force?: boolean;
          order: (number | ForumTopic)[];
      }
      • chatId: InputPeerLike

        Chat ID or username

      • Optionalforce?: boolean

        Whether to un-pin topics not present in the order

      • order: (number | ForumTopic)[]

        Order of the pinned topics

    Returns Promise<void>

  • Replace a sticker in a sticker set with another sticker

    For bots the sticker set must have been created by this bot.

    Available: ✅ both users and bots

    Parameters

    • sticker: string | RawFullRemoteFileLocation | TypeInputDocument

      TDLib and Bot API compatible File ID, or a TL object representing a sticker to be removed

    • newSticker: InputStickerSetItem

      New sticker to replace the old one with

    • Optionalparams: {
          progressCallback?: ((uploaded: number, total: number) => void);
      }
      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)

        Upload progress callback

          • (uploaded, total): void
          • Parameters

            • uploaded: number

              Number of bytes uploaded

            • total: number

              Total file size

            Returns void

    Returns Promise<StickerSet>

    Modfiied sticker set

  • Send a media group in reply to a given message

    Parameters

    • message: Message
    • Rest...params: [medias: (string | InputMediaLike)[], params?: CommonSendParams & {
          invertMedia?: boolean;
          progressCallback?: ((index: number, uploaded: number, total: number) => void);
      }]

    Returns Promise<Message[]>

  • Report a story (or multiple stories) to the moderation team Available: 👤 users only

    Parameters

    • peerId: InputPeerLike
    • storyIds: MaybeArray<number>
    • Optionalparams: {
          message?: string;
          reason?: TypeReportReason;
      }
      • Optionalmessage?: string

        Additional comment to the report

      • Optionalreason?: TypeReportReason

        Reason for reporting

        inputReportReasonSpam
        

    Returns Promise<void>

  • Re-send the confirmation code using a different type.

    The type of the code to be re-sent is specified in the nextType attribute of SentCode object returned by sendCode Available: 👤 users only

    Parameters

    • params: {
          abortSignal?: AbortSignal;
          phone: string;
          phoneCodeHash: string;
      }
      • OptionalabortSignal?: AbortSignal

        Abort signal

      • phone: string

        Phone number in international format

      • phoneCodeHash: string

        Confirmation code identifier from SentCode

    Returns Promise<SentCode>

  • Get the InputPeer of a known peer id. Useful when an InputPeer is needed in Raw API.

    Available: ✅ both users and bots

    Parameters

    • peerId: InputPeerLike

      The peer identifier that you want to extract the InputPeer from.

    • Optionalforce: boolean

      Whether to force re-fetch the peer from the server (only for usernames and phone numbers)

    Returns Promise<TypeInputPeer>

  • Restrict a user in a supergroup. Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          restrictions: Omit<RawChatBannedRights, "_" | "untilDate">;
          until?: number | Date;
          userId: InputPeerLike;
      }
      • chatId: InputPeerLike

        Chat ID

      • restrictions: Omit<RawChatBannedRights, "_" | "untilDate">

        Restrictions for the user. Note that unlike Bot API, this object contains the restrictions, and not the permissions, i.e. passing sendMessages=true will disallow the user to send messages, and passing {} (empty object) will lift any restrictions

      • Optionaluntil?: number | Date

        Date when the user will be unrestricted. When number is passed, UNIX time in ms is expected. If this value is less than 30 seconds or more than 366 days in the future, user will be restricted forever.

        0, i.e. forever

      • userId: InputPeerLike

        User ID

    Returns Promise<void>

  • Simple wrapper that calls start and then provided callback function (if any) without the need to introduce a main() function manually.

    Errors that were encountered while calling start and then will be emitted as usual, and can be caught with onError

    Available: ✅ both users and bots

    Parameters

    • params: {
          abortSignal?: AbortSignal;
          botToken?: MaybeDynamic<string>;
          code?: MaybeDynamic<string>;
          codeSentCallback?: ((code: SentCode) => MaybePromise<void>);
          codeSettings?: Omit<RawCodeSettings, "_" | "logoutTokens">;
          forceSms?: boolean;
          futureAuthTokens?: Uint8Array[];
          invalidCodeCallback?: ((type: "code" | "password") => MaybePromise<void>);
          password?: MaybeDynamic<string>;
          phone?: MaybeDynamic<string>;
          qrCodeHandler?: ((url: string, expires: Date) => void);
          session?: string | StringSessionData;
          sessionForce?: boolean;
      }

      Parameters to be passed to start

      • OptionalabortSignal?: AbortSignal

        Abort signal

      • OptionalbotToken?: MaybeDynamic<string>

        Bot token to use. Ignored if phone is supplied.

      • Optionalcode?: MaybeDynamic<string>

        Code sent to the phone (either sms, call, flash call or other). Ignored if botToken is supplied, must be present if phone is supplied.

      • OptionalcodeSentCallback?: ((code: SentCode) => MaybePromise<void>)

        Custom method that is called when a code is sent. Can be used to show a GUI alert of some kind.

        This method is called before start.params.code.

        console.log.

      • OptionalcodeSettings?: Omit<RawCodeSettings, "_" | "logoutTokens">

        Additional code settings to pass to the server

      • OptionalforceSms?: boolean

        Whether to force code delivery through SMS

      • OptionalfutureAuthTokens?: Uint8Array[]

        Saved future auth tokens, if any

      • OptionalinvalidCodeCallback?: ((type: "code" | "password") => MaybePromise<void>)

        If passed, this function will be called if provided code or 2FA password was invalid. New code/password will be requested later.

        If provided code/password is a constant string, providing an invalid one will interrupt authorization flow.

      • Optionalpassword?: MaybeDynamic<string>

        2FA password. Ignored if botToken is supplied

      • Optionalphone?: MaybeDynamic<string>

        Phone number of the account. If account does not exist, it will be created

      • OptionalqrCodeHandler?: ((url: string, expires: Date) => void)

        When passed, QR login flow will be used instead of the regular login flow.

        This function will be called whenever the login URL is changed, and the app is expected to display it as a QR code to the user.

          • (url, expires): void
          • Parameters

            • url: string
            • expires: Date

            Returns void

      • Optionalsession?: string | StringSessionData

        String session exported using TelegramClient.exportSession.

        This simply calls TelegramClient.importSession before anything else.

        Note that passed session will be ignored in case storage already contains authorization.

      • OptionalsessionForce?: boolean

        Whether to overwrite existing session.

    • Optionalthen: ((user: User) => void | Promise<void>)

      Function to be called after start returns

        • (user): void | Promise<void>
        • Parameters

          Returns void | Promise<void>

    Returns void

    This method provides no real value over start, please use it instead

  • Save or delete a draft message associated with some chat

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      ID of the chat, its username, phone or "me" or "self"

    • draft: null | Omit<RawDraftMessage, "_" | "date">

      Draft message, or null to delete.

    Returns Promise<void>

  • Search for messages globally from all of your chats

    Note: Due to Telegram limitations, you can only get up to ~10000 messages

    Available: 👤 users only

    Parameters

    • Optionalparams: {
          filter?: TypeMessagesFilter;
          limit?: number;
          maxDate?: number | Date;
          minDate?: number | Date;
          offset?: SearchGlobalOffset;
          onlyChannels?: boolean;
          query?: string;
      }

      Search parameters

      • Optionalfilter?: TypeMessagesFilter

        Filter the results using some filter. (see SearchFilters)

        SearchFilters.Empty (i.e. will return all messages)

      • Optionallimit?: number

        Limits the number of messages to be retrieved.

        100
        
      • OptionalmaxDate?: number | Date

        Only return messages older than this date

      • OptionalminDate?: number | Date

        Only return messages newer than this date

      • Optionaloffset?: SearchGlobalOffset

        Offset data used for pagination

      • OptionalonlyChannels?: boolean

        Whether to only search across broadcast channels

      • Optionalquery?: string

        Text query string. Use "@" to search for mentions.

        "" (empty string)

    Returns Promise<ArrayPaginated<Message, SearchGlobalOffset>>

  • Search for messages inside a specific chat

    Available: 👤 users only

    Parameters

    • Optionalparams: {
          addOffset?: number;
          chatId?: InputPeerLike;
          filter?: TypeMessagesFilter;
          fromUser?: InputPeerLike;
          limit?: number;
          maxDate?: number | Date;
          maxId?: number;
          minDate?: number | Date;
          minId?: number;
          offset?: number;
          query?: string;
          threadId?: number;
      }

      Additional search parameters

      • OptionaladdOffset?: number

        Additional offset from offset, in resulting messages.

        This can be used for advanced use cases, like:

        • Loading 20 results newer than message with ID MSGID: offset = MSGID, addOffset = -20, limit = 20
        • Loading 20 results around message with ID MSGID: offset = MSGID, addOffset = -10, limit = 20

        When offset is not set, this will be relative to the last message

        0 (disabled)

      • OptionalchatId?: InputPeerLike

        Chat where to search for messages.

        When empty, will search across common message box (i.e. private messages and legacy chats)

      • Optionalfilter?: TypeMessagesFilter

        Filter the results using some filter (see SearchFilters)

        SearchFilters.Empty (i.e. will return all messages)

      • OptionalfromUser?: InputPeerLike

        Search only for messages sent by a specific user.

        You can pass their marked ID, username, phone or "me" or "self"

      • Optionallimit?: number

        Limits the number of messages to be retrieved.

        100
        
      • OptionalmaxDate?: number | Date

        Maximum message date to return

        0 (disabled).

      • OptionalmaxId?: number

        Maximum message ID to return.

        Unless addOffset is used, this will work the same as offset.

        0 (disabled).

      • OptionalminDate?: number | Date

        Minimum message date to return

        0 (disabled).

      • OptionalminId?: number

        Minimum message ID to return

        0 (disabled).

      • Optionaloffset?: number

        Offset ID for the search. Only messages earlier than this ID will be returned.

        0 (starting from the latest message).

      • Optionalquery?: string

        Text query string. Required for text-only messages, optional for media.

        "" (empty string)

      • OptionalthreadId?: number

        Thread ID to return only messages from this thread.

    Returns Promise<ArrayPaginated<Message, number>>

  • Send the confirmation code to the given phone number

    Available: 👤 users only

    Parameters

    • params: {
          abortSignal?: AbortSignal;
          codeSettings?: Omit<RawCodeSettings, "_" | "logoutTokens">;
          futureAuthTokens?: Uint8Array[];
          phone: string;
      }
      • OptionalabortSignal?: AbortSignal

        Abort signal

      • OptionalcodeSettings?: Omit<RawCodeSettings, "_" | "logoutTokens">

        Additional code settings to pass to the server

      • OptionalfutureAuthTokens?: Uint8Array[]

        Saved future auth tokens, if any

      • phone: string

        Phone number in international format

    Returns Promise<SentCode>

    An object containing information about the sent confirmation code

  • Copy a message (i.e. send the same message, but do not forward it).

    Note that if the message contains a webpage, it will be copied simply as a text message, and if the message contains an invoice, it can't be copied. Available: ✅ both users and bots

    Parameters

    Returns Promise<Message>

  • Copy a message group (i.e. send the same message group, but do not forward it).

    Note that all the provided messages must be in the same message group Available: ✅ both users and bots

    Parameters

    Returns Promise<Message[]>

  • Send a single media (a photo or a document-based media)

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      ID of the chat, its username, phone or "me" or "self"

    • media: string | InputMediaLike

      Media contained in the message. You can also pass TDLib and Bot API compatible File ID, which will be wrapped in InputMedia.auto

    • Optionalparams: CommonSendParams & {
          caption?: InputText;
          invert?: boolean;
          progressCallback?: ((uploaded: number, total: number) => void);
          replyMarkup?: ReplyMarkup;
      }

      Additional sending parameters

    Returns Promise<Message>

    InputMedia

  • Send a group of media.

    To add a caption to the group, add caption to the first media in the group and don't add caption for any other.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      ID of the chat, its username, phone or "me" or "self"

    • medias: (string | InputMediaLike)[]

      Medias contained in the message.

    • Optionalparams: CommonSendParams & {
          invertMedia?: boolean;
          progressCallback?: ((index: number, uploaded: number, total: number) => void);
      }

      Additional sending parameters

    Returns Promise<Message[]>

    InputMedia

  • Send a paid reaction using Telegram Stars.

    Available: 👤 users only

    Parameters

    • params: InputMessageId & {
          anonymous?: boolean;
          count?: number;
          shouldDispatch?: true;
      }

    Returns Promise<MessageReactions>

    Message to which the reaction was sent, if available. The message is normally available for users, but may not be available for bots in PMs.

  • Send or remove a reaction.

    Available: 👤 users only

    Parameters

    • params: InputMessageId & {
          big?: boolean;
          emoji?: MaybeArray<InputReaction> | null | undefined;
          shouldDispatch?: true;
      }

    Returns Promise<null | Message>

    Message to which the reaction was sent, if available. The message is normally available for users, but may not be available for bots in PMs.

  • Send a code to email needed to recover your password

    Available: 👤 users only

    Returns Promise<string>

    String containing email pattern to which the recovery code was sent

  • Send previously scheduled message(s)

    Note that if the message belongs to a media group, the entire group will be sent, and all the messages will be returned.

    Available: 👤 users only

    Parameters

    Returns Promise<Message[]>

  • Send a story

    Available: 👤 users only

    Parameters

    • params: {
          caption?: InputText;
          forbidForwards?: boolean;
          interactiveElements?: TypeMediaArea[];
          media: string | InputMediaLike;
          peer?: InputPeerLike;
          period?: number;
          pinned?: boolean;
          privacyRules?: InputPrivacyRule[];
      }
      • Optionalcaption?: InputText

        Override caption for media

      • OptionalforbidForwards?: boolean

        Whether to disallow sharing this story

      • OptionalinteractiveElements?: TypeMediaArea[]

        Interactive elements to add to the story

      • media: string | InputMediaLike

        Media contained in a story. Currently can only be a photo or a video.

        You can also pass TDLib and Bot API compatible File ID, which will be wrapped in InputMedia.auto

      • Optionalpeer?: InputPeerLike

        Peer ID to send story as

        self

      • Optionalperiod?: number

        TTL period of the story, in seconds

        86400
        
      • Optionalpinned?: boolean

        Whether to automatically pin this story to the profile

      • OptionalprivacyRules?: InputPrivacyRule[]

        Privacy rules to apply to the story

        "Everyone"
        

    Returns Promise<Story>

    Created story

  • Send (or remove) a reaction to a story Available: 👤 users only

    Parameters

    • params: {
          addToRecent?: boolean;
          peerId: InputPeerLike;
          reaction: InputReaction;
          storyId: number;
      }
      • OptionaladdToRecent?: boolean

        Whether to add this reaction to recently used

      • peerId: InputPeerLike
      • reaction: InputReaction
      • storyId: number

    Returns Promise<void>

  • Send a text message

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      ID of the chat, its username, phone or "me" or "self"

    • text: InputText

      Text of the message

    • Optionalparams: CommonSendParams & {
          disableWebPreview?: boolean;
          invertMedia?: boolean;
          replyMarkup?: ReplyMarkup;
      }

      Additional sending parameters

    Returns Promise<Message>

  • Sends a current user/bot typing event to a conversation partner or group.

    This status is set for 6 seconds, and is automatically cancelled if you send a message.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • Optionalstatus:
          | "contact"
          | "game"
          | "geo"
          | "sticker"
          | "typing"
          | "cancel"
          | "record_video"
          | "upload_video"
          | "record_voice"
          | "upload_voice"
          | "upload_photo"
          | "upload_document"
          | "record_round"
          | "upload_round"
          | "speak_call"
          | "history_import"
          | TypeSendMessageAction

      Typing status

    • Optionalparams: {
          businessConnectionId?: string;
          progress?: number;
          threadId?: number;
      }
      • OptionalbusinessConnectionId?: string

        Unique identifier of the business connection on behalf of which the action will be sent

      • Optionalprogress?: number

        For upload_* and history import actions, progress of the upload

      • OptionalthreadId?: number

        For comment threads, ID of the thread (i.e. top message)

    Returns Promise<void>

  • Sets information about a bot the current uzer owns (or the current bot) Available: ✅ both users and bots

    Parameters

    • params: {
          bio?: string;
          bot?: InputPeerLike;
          description?: string;
          langCode?: string;
          name?: string;
      }
      • Optionalbio?: string

        New bio text (displayed in the profile)

      • Optionalbot?: InputPeerLike

        When called by a user, a bot the user owns must be specified. When called by a bot, must be empty

      • Optionaldescription?: string

        New description text (displayed when the chat is empty)

      • OptionallangCode?: string

        If passed, will update the bot's description in the given language. If left empty, will change the fallback description.

      • Optionalname?: string

        New bot name

    Returns Promise<void>

  • Set current user's business work hours. Available: 👤 users only

    Parameters

    • params: null | ({ timezone: string; } & ({ hours: readonly BusinessWorkHoursDay[]; } | { intervals: RawBusinessWeeklyOpen[]; }))

    Returns Promise<void>

  • Set peer color and optionally background pattern Available: 👤 users only

    Parameters

    • params: {
          backgroundEmojiId?: Long;
          color: number;
          forProfile?: boolean;
          peer?: InputPeerLike;
      }
      • OptionalbackgroundEmojiId?: Long

        Background pattern emoji ID.

        Must be an adaptive emoji, otherwise the request will fail.

      • color: number

        Color identificator

        Note that this value is not an RGB color representation. Instead, it is a number which should be used to pick a color from a predefined list of colors:

        • 0-6 are the default colors used by Telegram clients: red, orange, purple, green, sea, blue, pink
        • >= 7 are returned by help.getAppConfig.
      • OptionalforProfile?: boolean

        Whether to set this color for the profile header instead of chat name/replies.

        Currently only available for the current user.

      • Optionalpeer?: InputPeerLike

        Peer where to update the color.

        By default will change the color for the current user

    Returns Promise<void>

  • Change default chat permissions for all members.

    You must be an administrator in the chat and have appropriate permissions.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • restrictions: Omit<RawChatBannedRights, "_" | "untilDate">

      Restrictions for the chat. Note that unlike Bot API, this object contains the restrictions, and not the permissions, i.e. passing sendMessages=true will disallow the users to send messages, and passing {} (empty object) will lift any restrictions

    Returns Promise<Chat>

  • Change chat description

    You must be an administrator and have the appropriate permissions.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • description: string

      New chat description, 0-255 characters

    Returns Promise<void>

  • Set a new chat photo or video.

    You must be an administrator and have the appropriate permissions. Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          media: InputFileLike;
          previewSec?: number;
          type: "photo" | "video";
      }
      • chatId: InputPeerLike

        Chat ID or username

      • media: InputFileLike

        Input media file

      • OptionalpreviewSec?: number

        When type = video, timestamp in seconds which will be shown as a static preview.

      • type: "photo" | "video"

        Media type (photo or video)

    Returns Promise<void>

  • Change chat title

    You must be an administrator and have the appropriate permissions.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • title: string

      New chat title, 1-255 characters

    Returns Promise<void>

  • Set maximum Time-To-Live of all newly sent messages in the specified chat

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID

    • period: number

      New TTL period, in seconds (or 0 to disable)

    Returns Promise<void>

  • Change supergroup/channel username

    You must be an administrator and have the appropriate permissions.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID or current username

    • username: null | string

      New username, or null to remove

    Returns Promise<void>

  • Reorder folders

    Available: 👤 users only

    Parameters

    • order: number[]

      New order of folders (folder IDs, where default = 0)

    Returns Promise<void>

  • Changes the current default value of the Time-To-Live setting, applied to all new chats.

    Available: 👤 users only

    Parameters

    • period: number

      New TTL period, in seconds (or 0 to disable)

    Returns Promise<void>

  • Set a score of a user in a game contained in an inline message

    Available: 🤖 bots only

    Parameters

    • params: {
          force?: boolean;
          messageId: string | TypeInputBotInlineMessageID;
          noEdit?: boolean;
          score: number;
          userId: InputPeerLike;
      }
      • Optionalforce?: boolean

        Whether to allow user's score to decrease. This can be useful when fixing mistakes or banning cheaters

      • messageId: string | TypeInputBotInlineMessageID

        ID of the inline message

      • OptionalnoEdit?: boolean

        When true, the game message will not be modified to include the new score

      • score: number

        The new score (must be >0)

      • userId: InputPeerLike

        ID of the user who has scored

    Returns Promise<void>

  • By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.

    Returns a reference to the EventEmitter, so that calls can be chained.

    Parameters

    • n: number

    Returns this

    v0.3.5

  • Set or remove current user's birthday. Available: 👤 users only

    Parameters

    • birthday: null | {
          day: number;
          month: number;
          year?: number;
      }

    Returns Promise<void>

  • Sets the default chat permissions for the bot in the supergroup or channel. Available: 🤖 bots only

    Parameters

    • params: {
          rights: Omit<RawChatAdminRights, "_">;
          target: "channel" | "group";
      }
      • rights: Omit<RawChatAdminRights, "_">

        The default chat permissions.

      • target: "channel" | "group"

        Whether to target groups or channels.

    Returns Promise<void>

  • Set an emoji status for the current user

    Available: 👤 users only

    Parameters

    • emoji: null | Long

      Custom emoji ID or null to remove the emoji

    • Optionalparams: {
          until?: number | Date;
      }
      • Optionaluntil?: number | Date

        Date when the emoji status should expire (only if emoji is not null)

    Returns Promise<void>

  • Set a new profile photo or video for the current user.

    You can also pass a file ID or an InputPhoto to re-use existing photo. Available: ✅ both users and bots

    Parameters

    • params: {
          media: TypeInputPhoto | InputFileLike;
          previewSec?: number;
          type: "photo" | "video";
      }
      • media: TypeInputPhoto | InputFileLike

        Input media file

      • OptionalpreviewSec?: number

        When type = video, timestamp in seconds which will be shown as a static preview.

      • type: "photo" | "video"

        Media type (photo or video)

    Returns Promise<Photo>

  • Change username of the current user.

    Note that bots usernames must be changed through bot support or re-created from scratch.

    Available: 👤 users only

    Parameters

    • username: null | string

      New username (5-32 chars, allowed chars: a-zA-Z0-9_), or null to remove

    Returns Promise<User>

  • Change user status to offline or online

    Available: 👤 users only

    Parameters

    • Optionaloffline: boolean

      Whether the user is currently offline

    Returns Promise<void>

  • Set supergroup's slow mode interval.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalseconds: number

      Slow mode interval in seconds. Users will be able to send a message only once per this interval. Valid values are: 0 (off), 10, 30, 60 (1m), 300 (5m), 900 (15m) or 3600 (1h)

    Returns Promise<void>

  • Set sticker set thumbnail

    Available: ✅ both users and bots

    Parameters

    • id: InputStickerSet

      Sticker set short name or a TL object with input sticker set

    • thumb: TypeInputDocument | InputFileLike

      Sticker set thumbnail

    • Optionalparams: {
          progressCallback?: ((uploaded: number, total: number) => void);
      }
      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)

        Upload progress callback

          • (uploaded, total): void
          • Parameters

            • uploaded: number

              Number of bytes uploaded

            • total: number

              Total file size

            Returns void

    Returns Promise<StickerSet>

    Modified sticker set

  • Authorize a user in Telegram with a valid confirmation code.

    Available: 👤 users only

    Parameters

    • params: {
          abortSignal?: AbortSignal;
          phone: string;
          phoneCode: string;
          phoneCodeHash: string;
      }
      • OptionalabortSignal?: AbortSignal

        Abort signal

      • phone: string

        Phone number in international format

      • phoneCode: string

        The confirmation code that was received

      • phoneCodeHash: string

        Code identifier from sendCode

    Returns Promise<User>

    If the code was valid and authorization succeeded, the User is returned.

    BadRequestError In case the arguments are invalid

    SessionPasswordNeededError In case a password is needed to sign in

  • Authorize a bot using its token issued by @BotFather

    Available: ✅ both users and bots

    Parameters

    • token: string

      Bot token issued by BotFather

    Returns Promise<User>

    Bot's User object

    BadRequestError In case the bot token is invalid

  • Execute the QR login flow.

    This method will resolve once the authorization is complete, returning the authorized user. Available: 👤 users only

    Parameters

    • params: {
          abortSignal?: AbortSignal;
          invalidPasswordCallback?: (() => MaybePromise<void>);
          onQrScanned?: (() => void);
          onUrlUpdated: ((url: string, expires: Date) => void);
          password?: MaybeDynamic<string>;
      }
      • OptionalabortSignal?: AbortSignal

        Abort signal

      • OptionalinvalidPasswordCallback?: (() => MaybePromise<void>)

        Function that will be called after the server has rejected the password.

        Note that in case password is not a function, this callback will never be called, and an error will be thrown instead.

      • OptionalonQrScanned?: (() => void)

        Function that will be called when the user has scanned the QR code (i.e. when updateLoginToken is received), and the library is finalizing the auth

          • (): void
          • Returns void

      • onUrlUpdated: ((url: string, expires: Date) => void)

        Function that will be called whenever the login URL is changed.

        The app is expected to display url as a QR code to the user

          • (url, expires): void
          • Parameters

            • url: string
            • expires: Date

            Returns void

      • Optionalpassword?: MaybeDynamic<string>

        Password for 2FA

    Returns Promise<User>

  • Start the client in an interactive and declarative manner, by providing callbacks for authorization details.

    This method handles both login and sign up, and also handles 2FV

    All parameters are MaybeDynamic<T>, meaning you can either supply T, or a function that returns MaybePromise<T>

    This method is intended for simple and fast use in automated scripts and bots. If you are developing a custom client, you'll probably need to use other auth methods. Available: ✅ both users and bots

    Parameters

    • params: {
          abortSignal?: AbortSignal;
          botToken?: MaybeDynamic<string>;
          code?: MaybeDynamic<string>;
          codeSentCallback?: ((code: SentCode) => MaybePromise<void>);
          codeSettings?: Omit<RawCodeSettings, "_" | "logoutTokens">;
          forceSms?: boolean;
          futureAuthTokens?: Uint8Array[];
          invalidCodeCallback?: ((type: "code" | "password") => MaybePromise<void>);
          password?: MaybeDynamic<string>;
          phone?: MaybeDynamic<string>;
          qrCodeHandler?: ((url: string, expires: Date) => void);
          session?: string | StringSessionData;
          sessionForce?: boolean;
      }
      • OptionalabortSignal?: AbortSignal

        Abort signal

      • OptionalbotToken?: MaybeDynamic<string>

        Bot token to use. Ignored if phone is supplied.

      • Optionalcode?: MaybeDynamic<string>

        Code sent to the phone (either sms, call, flash call or other). Ignored if botToken is supplied, must be present if phone is supplied.

      • OptionalcodeSentCallback?: ((code: SentCode) => MaybePromise<void>)

        Custom method that is called when a code is sent. Can be used to show a GUI alert of some kind.

        This method is called before start.params.code.

        console.log.

      • OptionalcodeSettings?: Omit<RawCodeSettings, "_" | "logoutTokens">

        Additional code settings to pass to the server

      • OptionalforceSms?: boolean

        Whether to force code delivery through SMS

      • OptionalfutureAuthTokens?: Uint8Array[]

        Saved future auth tokens, if any

      • OptionalinvalidCodeCallback?: ((type: "code" | "password") => MaybePromise<void>)

        If passed, this function will be called if provided code or 2FA password was invalid. New code/password will be requested later.

        If provided code/password is a constant string, providing an invalid one will interrupt authorization flow.

      • Optionalpassword?: MaybeDynamic<string>

        2FA password. Ignored if botToken is supplied

      • Optionalphone?: MaybeDynamic<string>

        Phone number of the account. If account does not exist, it will be created

      • OptionalqrCodeHandler?: ((url: string, expires: Date) => void)

        When passed, QR login flow will be used instead of the regular login flow.

        This function will be called whenever the login URL is changed, and the app is expected to display it as a QR code to the user.

          • (url, expires): void
          • Parameters

            • url: string
            • expires: Date

            Returns void

      • Optionalsession?: string | StringSessionData

        String session exported using TelegramClient.exportSession.

        This simply calls TelegramClient.importSession before anything else.

        Note that passed session will be ignored in case storage already contains authorization.

      • OptionalsessionForce?: boolean

        Whether to overwrite existing session.

    Returns Promise<User>

  • Utility function to quickly authorize on test DC using a Test phone number, which is randomly generated by default.

    Note: Using this method assumes that you are using a test DC in primaryDc parameter.

    Available: ✅ both users and bots

    Parameters

    • Optionalparams: {
          dcId?: number;
          logout?: boolean;
          phone?: string;
      }

      Additional parameters

      • OptionaldcId?: number

        Override user's DC. Must be a valid test DC.

      • Optionallogout?: boolean

        Whether to log out if current session is logged in.

        false.
        
      • Optionalphone?: string

        Override phone number. Must be a valid Test phone number.

        By default is randomly generated.

    Returns Promise<User>

  • Set whether a chat has content protection (i.e. forwarding messages is disabled)

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalenabled: boolean

      Whether content protection should be enabled

    Returns Promise<void>

  • Set whether a supergroup is a forum.

    Only owner of the supergroup can change this setting.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalenabled: boolean

      Whether the supergroup should be a forum

    Returns Promise<void>

  • Toggle open/close status of a topic in a forum

    Only admins with manageTopics permission can do this.

    Available: ✅ both users and bots

    Parameters

    • parmas: {
          chatId: InputPeerLike;
          closed: boolean;
          shouldDispatch?: true;
          topicId: number | ForumTopic;
      }
      • chatId: InputPeerLike

        Chat ID or username

      • closed: boolean

        Whether the topic should be closed

      • OptionalshouldDispatch?: true

        Whether to dispatch the returned service message (if any) to the client's update handler.

      • topicId: number | ForumTopic

        ID of the topic (i.e. its top message ID)

    Returns Promise<Message>

    Service message about the modification

  • Toggle whether a topic in a forum is pinned

    Only admins with manageTopics permission can do this. Available: 👤 users only

    Parameters

    • params: {
          chatId: InputPeerLike;
          pinned: boolean;
          topicId: number | ForumTopic;
      }
      • chatId: InputPeerLike

        Chat ID or username

      • pinned: boolean

        Whether the topic should be pinned

      • topicId: number | ForumTopic

        ID of the topic (i.e. its top message ID)

    Returns Promise<void>

  • Toggle a collectible (Fragment) username

    Note: non-collectible usernames must still be changed using setUsername/setChatUsername Available: 👤 users only

    Parameters

    • params: {
          active: boolean;
          peerId: InputPeerLike;
          username: string;
      }
      • active: boolean

        Whether to enable or disable the username

      • peerId: InputPeerLike

        Peer ID whose username to toggle

      • username: string

        Username to toggle

    Returns Promise<void>

  • Toggle whether "General" topic in a forum is hidden or not

    Only admins with manageTopics permission can do this.

    Available: ✅ both users and bots

    Parameters

    • params: {
          chatId: InputPeerLike;
          hidden: boolean;
          shouldDispatch?: true;
      }
      • chatId: InputPeerLike

        Chat ID or username

      • hidden: boolean

        Whether the topic should be hidden

      • OptionalshouldDispatch?: true

        Whether to dispatch the returned service message (if any) to the client's update handler.

    Returns Promise<Message>

    Service message about the modification

  • Set whether a channel/supergroup has join requests enabled.

    Note: this method only affects primary invite links. Additional invite links may exist with the opposite setting.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalenabled: boolean

      Whether join requests should be enabled

    Returns Promise<void>

  • Set whether a channel/supergroup has join-to-send setting enabled.

    This only affects discussion groups where users can send messages without joining the group.

    Available: 👤 users only

    Parameters

    • chatId: InputPeerLike

      Chat ID or username

    • Optionalenabled: boolean

      Whether join-to-send setting should be enabled

    Returns Promise<void>

  • Toggle whether peer's stories are archived (hidden) or not.

    This does not archive the chat with that peer, only stories. Available: 👤 users only

    Parameters

    Returns Promise<void>

  • Toggle one or more stories pinned status

    Available: 👤 users only

    Parameters

    • params: {
          ids: MaybeArray<number>;
          peer?: InputPeerLike;
          pinned: boolean;
      }
      • ids: MaybeArray<number>

        Story ID(s) to toggle

      • Optionalpeer?: InputPeerLike

        Peer ID whose stories to toggle

        self

      • pinned: boolean

        Whether to pin or unpin the story

    Returns Promise<number[]>

    IDs of stories that were toggled

  • Unban a user/channel from a supergroup or a channel, or remove any restrictions that they have. Unbanning does not add the user back to the chat, this just allows the user to join the chat again, if they want.

    This method acts as a no-op in case a legacy group is passed. Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Unpin all pinned messages in a chat.

    Available: ✅ both users and bots

    Parameters

    • chatId: InputPeerLike

      Chat or user ID

    • Optionalparams: {
          shouldDispatch?: true;
          topicId?: number;
      }
      • OptionalshouldDispatch?: true

        Whether to dispatch updates that will be generated by this call. Doesn't follow disableNoDispatch

      • OptionaltopicId?: number

        For forums - unpin only messages from the given topic

    Returns Promise<void>

  • Unpin a message in a group, supergroup, channel or PM.

    For supergroups/channels, you must have appropriate permissions, either as an admin, or as default permissions

    Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Unban a user/channel from a supergroup or a channel, or remove any restrictions that they have. Unbanning does not add the user back to the chat, this just allows the user to join the chat again, if they want.

    This method acts as a no-op in case a legacy group is passed. Available: ✅ both users and bots

    Parameters

    Returns Promise<void>

  • Update your profile details.

    Only pass fields that you want to change.

    Available: 👤 users only

    Parameters

    • params: {
          bio?: string;
          firstName?: string;
          lastName?: string;
      }
      • Optionalbio?: string

        New bio (max 70 chars). Pass '' (empty string) to remove it

      • OptionalfirstName?: string

        New first name

      • OptionallastName?: string

        New last name. Pass '' (empty string) to remove it

    Returns Promise<User>

  • Upload a file to Telegram servers, without actually sending a message anywhere. Useful when an InputFile is required.

    This method is quite low-level, and you should use other methods like sendMedia that handle this under the hood.

    Available: ✅ both users and bots

    Parameters

    • params: {
          estimatedSize?: number;
          file: UploadFileLike;
          fileMime?: string;
          fileName?: string;
          fileSize?: number;
          partSize?: number;
          progressCallback?: ((uploaded: number, total: number) => void);
          requestsPerConnection?: number;
          requireFileSize?: boolean;
      }

      Upload parameters

      • OptionalestimatedSize?: number

        If the file size is unknown, you can provide an estimate, which will be used to determine appropriate part size.

      • file: UploadFileLike

        Upload file source.

      • OptionalfileMime?: string

        File MIME type. By default is automatically inferred from magic number If MIME can't be inferred, it defaults to application/octet-stream

      • OptionalfileName?: string

        File name for the uploaded file. Is usually inferred from path, but should be provided for files sent as Buffer or stream.

        When file name can't be inferred, it falls back to "unnamed"

      • OptionalfileSize?: number

        Total file size. Automatically inferred for Buffer, File and local files.

      • OptionalpartSize?: number

        Upload part size (in KB).

        By default, automatically selected by file size. Must not be bigger than 512 and must not be a fraction.

      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)

        Function that will be called after some part has been uploaded.

          • (uploaded, total): void
          • Parameters

            • uploaded: number

              Number of bytes already uploaded

            • total: number

              Total file size, if known

            Returns void

      • OptionalrequestsPerConnection?: number

        Number of parts to be sent in parallel per connection.

      • OptionalrequireFileSize?: boolean

        When using inputMediaUploadedPhoto (e.g. when sending an uploaded photo) require the file size to be known beforehand.

        In case this is set to true, a stream is passed as file and the file size is unknown, the stream will be buffered in memory and the file size will be inferred from the buffer.

    Returns Promise<UploadedFile>

  • Upload a media to Telegram servers, without actually sending a message anywhere. Useful when File ID is needed.

    The difference with uploadFile is that the returned object will act like a message media and contain fields like File ID.

    Available: ✅ both users and bots

    Parameters

    • media: InputMediaLike

      Media to upload

    • Optionalparams: {
          peer?: InputPeerLike;
          progressCallback?: ((uploaded: number, total: number) => void);
      }

      Upload parameters

      • Optionalpeer?: InputPeerLike
      • OptionalprogressCallback?: ((uploaded: number, total: number) => void)
          • (uploaded, total): void
          • Parameters

            • uploaded: number
            • total: number

            Returns void

    Returns Promise<
        | Photo
        | Document
        | Audio
        | Sticker
        | Video
        | Voice>

  • Verify an email to use as 2FA recovery method

    Available: 👤 users only

    Parameters

    • code: string

      Code which was sent via email

    Returns Promise<void>

  • Experimental

    Listens once to the abort event on the provided signal.

    Listening to the abort event on abort signals is unsafe and may lead to resource leaks since another third party with the signal can call e.stopImmediatePropagation(). Unfortunately Node.js cannot change this since it would violate the web standard. Additionally, the original API makes it easy to forget to remove listeners.

    This API allows safely using AbortSignals in Node.js APIs by solving these two issues by listening to the event such that stopImmediatePropagation does not prevent the listener from running.

    Returns a disposable so that it may be unsubscribed from more easily.

    import { addAbortListener } from 'node:events';

    function example(signal) {
    let disposable;
    try {
    signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
    disposable = addAbortListener(signal, (e) => {
    // Do something when signal is aborted.
    });
    } finally {
    disposable?.[Symbol.dispose]();
    }
    }

    Parameters

    • signal: AbortSignal
    • resource: ((event: Event) => void)
        • (event): void
        • Parameters

          • event: Event

          Returns void

    Returns Disposable

    Disposable that removes the abort listener.

    v20.5.0

  • Returns a copy of the array of listeners for the event named eventName.

    For EventEmitters this behaves exactly the same as calling .listeners on the emitter.

    For EventTargets this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

    import { getEventListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    const listener = () => console.log('Events are fun');
    ee.on('foo', listener);
    console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
    }
    {
    const et = new EventTarget();
    const listener = () => console.log('Events are fun');
    et.addEventListener('foo', listener);
    console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
    }

    Parameters

    • emitter: EventEmitter | _DOMEventTarget
    • name: string | symbol

    Returns Function[]

    v15.2.0, v14.17.0

  • Returns the currently set max amount of listeners.

    For EventEmitters this behaves exactly the same as calling .getMaxListeners on the emitter.

    For EventTargets this is the only way to get the max event listeners for the event target. If the number of event handlers on a single EventTarget exceeds the max set, the EventTarget will print a warning.

    import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';

    {
    const ee = new EventEmitter();
    console.log(getMaxListeners(ee)); // 10
    setMaxListeners(11, ee);
    console.log(getMaxListeners(ee)); // 11
    }
    {
    const et = new EventTarget();
    console.log(getMaxListeners(et)); // 10
    setMaxListeners(11, et);
    console.log(getMaxListeners(et)); // 11
    }

    Parameters

    • emitter: EventEmitter | _DOMEventTarget

    Returns number

    v19.9.0

  • A class method that returns the number of listeners for the given eventNameregistered on the given emitter.

    import { EventEmitter, listenerCount } from 'node:events';

    const myEmitter = new EventEmitter();
    myEmitter.on('event', () => {});
    myEmitter.on('event', () => {});
    console.log(listenerCount(myEmitter, 'event'));
    // Prints: 2

    Parameters

    • emitter: EventEmitter

      The emitter to query

    • eventName: string | symbol

      The event name

    Returns number

    v0.9.12

    Since v3.2.0 - Use listenerCount instead.

  • import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo')) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here

    Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits 'error'. It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

    An AbortSignal can be used to cancel waiting on events:

    import { on, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ac = new AbortController();

    (async () => {
    const ee = new EventEmitter();

    // Emit later on
    process.nextTick(() => {
    ee.emit('foo', 'bar');
    ee.emit('foo', 42);
    });

    for await (const event of on(ee, 'foo', { signal: ac.signal })) {
    // The execution of this inner block is synchronous and it
    // processes one event at a time (even with await). Do not use
    // if concurrent execution is required.
    console.log(event); // prints ['bar'] [42]
    }
    // Unreachable here
    })();

    process.nextTick(() => ac.abort());

    Parameters

    • emitter: EventEmitter
    • eventName: string

      The name of the event being listened for

    • Optionaloptions: StaticEventEmitterOptions

    Returns AsyncIterableIterator<any>

    that iterates eventName events emitted by the emitter

    v13.6.0, v12.16.0

  • Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits 'error' while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event semantics and does not listen to the 'error' event.

    import { once, EventEmitter } from 'node:events';
    import process from 'node:process';

    const ee = new EventEmitter();

    process.nextTick(() => {
    ee.emit('myevent', 42);
    });

    const [value] = await once(ee, 'myevent');
    console.log(value);

    const err = new Error('kaboom');
    process.nextTick(() => {
    ee.emit('error', err);
    });

    try {
    await once(ee, 'myevent');
    } catch (err) {
    console.error('error happened', err);
    }

    The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the 'error' event itself, then it is treated as any other kind of event without special handling:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();

    once(ee, 'error')
    .then(([err]) => console.log('ok', err.message))
    .catch((err) => console.error('error', err.message));

    ee.emit('error', new Error('boom'));

    // Prints: ok boom

    An AbortSignal can be used to cancel waiting for the event:

    import { EventEmitter, once } from 'node:events';

    const ee = new EventEmitter();
    const ac = new AbortController();

    async function foo(emitter, event, signal) {
    try {
    await once(emitter, event, { signal });
    console.log('event emitted!');
    } catch (error) {
    if (error.name === 'AbortError') {
    console.error('Waiting for the event was canceled!');
    } else {
    console.error('There was an error', error.message);
    }
    }
    }

    foo(ee, 'foo', ac.signal);
    ac.abort(); // Abort waiting for the event
    ee.emit('foo'); // Prints: Waiting for the event was canceled!

    Parameters

    • emitter: _NodeEventTarget
    • eventName: string | symbol
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

    v11.13.0, v10.16.0

  • Parameters

    • emitter: _DOMEventTarget
    • eventName: string
    • Optionaloptions: StaticEventEmitterOptions

    Returns Promise<any[]>

  • import { setMaxListeners, EventEmitter } from 'node:events';

    const target = new EventTarget();
    const emitter = new EventEmitter();

    setMaxListeners(5, target, emitter);

    Parameters

    • Optionaln: number

      A non-negative number. The maximum number of listeners per EventTarget event.

    • Rest...eventTargets: (EventEmitter | _DOMEventTarget)[]

    Returns void

    v15.4.0