Hierarchy (view full)

Implements

Constructors

Properties

Methods

[captureRejectionSymbol]? _normalizeInputFile _normalizeInputMedia _normalizePrivacyRules acceptStarGift 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 getStarGiftOptions getStarGifts 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 iterStarGifts 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 resendCode resendPasswordEmail resolveChannel resolvePeer resolvePeerMany resolveUser restrictChatMember revokeInviteLink run saveDraft searchGlobal searchHashtag searchMessages sendCode sendCopy sendCopyGroup sendMedia sendMediaGroup sendPaidReaction sendReaction sendRecoveryCode sendScheduled sendStarGift 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>

  • Accept, hide or convert a star gift.

    Available: 👤 users only

    Parameters

    • params: InputMessageId & {
          action: "save" | "hide" | "convert";
      }

    Returns Promise<boolean>

    Whether the action was successful

  • 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;
          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).

      • 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 gifts sent to a given user.

    Wrapper over getStarGifts

    Available: 👤 users only

    Parameters

    • peerId: InputPeerLike

      Peer ID

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

      Additional parameters

    Returns AsyncIterableIterator<UserStarGift>

  • 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[]>

  • 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>