Readonly
appReadonly
logReadonly
stopReadonly
storageStatic
Readonly
captureStatic
captureValue: boolean
Change the default captureRejections
option on all new EventEmitter
objects.
Static
defaultBy 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.defaultMaxListeners
property can be used. If this value is not a positive number, a RangeError
is 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'
.
Static
Readonly
errorThis 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.
Optional
[captureNormalize a InputFileLike to InputFile
,
uploading it if needed.
Available: ✅ both users and bots
Optional
fileOptional
fileOptional
fileOptional
progressNormalize an InputMediaLike to InputMedia
,
uploading the file if needed.
Available: ✅ both users and bots
Optional
params: { Optional
businessOptional
progressOptional
uploadOptional
uploadMedia: booleanNormalize InputPrivacyRule[] to tl.TypeInputPrivacyRule
,
resolving the peers if needed.
Available: ✅ both users and bots
Accept, hide or convert a star gift.
Available: 👤 users only
Whether the action was successful
Add one or more new members to a group, supergroup or channel.
Available: 👤 users only
ID of the chat or its username
ID(s) of the user(s) to add
Optional
forwardNumber of old messages to be forwarded (0-100). Only applicable to legacy groups, ignored for supergroups and channels
List of users that were failed to be invited (may be empty)
Add an existing Telegram user as a contact Available: 👤 users only
First name of the contact
Optional
lastLast name of the contact
Optional
phone?: stringPhone number of the contact, if available
Optional
shareWhether to share your own phone number with the newly created contact
User ID, username or phone number
Add a sticker to a sticker set.
For bots the sticker set must have been created by this bot.
Available: ✅ both users and bots
Sticker set short name or TL object with input sticker set
Sticker to be added
Optional
params: { Optional
progressUpload progress callback
Number of bytes uploaded
Total file size
Modfiied sticker set
Send an answer to a callback query.
Available: 🤖 bots only
ID of the callback query, or the query itself
Optional
params: { Parameters of the answer
Optional
alert?: booleanWhether to show an alert in the middle of the screen instead of a notification at the top of the screen.
Optional
cacheMaximum amount of time in seconds for which this result can be cached by the client (not server!).
Optional
text?: stringText of the notification (0-200 chars).
If not set, nothing will be displayed
Optional
url?: stringURL 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.
Answer an inline query.
Available: 🤖 bots only
Inline query ID
Results of the query
Optional
params: { Additional parameters
Optional
cacheMaximum number of time in seconds that the results of the query may be cached on the server for.
Optional
gallery?: booleanWhether 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
Optional
nextNext 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.
Optional
private?: booleanWhether the results should only be cached on the server for the user who sent the query.
Optional
switchIf 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 for /start
command
Text of the button
Optional
switchIf 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 of the button
URL to open
Send a media to the same chat (and topic, if applicable) as a given message
Rest
...params: [media: string | InputMediaLike, params?: CommonSendParams & { Send a media group to the same chat (and topic, if applicable) as a given message
Rest
...params: [medias: (string | InputMediaLike)[], params?: CommonSendParams & { Answer a pre-checkout query.
Available: 🤖 bots only
Pre-checkout query ID
Optional
params: { Optional
error?: stringIf pre-checkout is rejected, error message to show to the user
Send a text to the same chat (and topic, if applicable) as a given message
Rest
...params: [text: InputText, params?: CommonSendParams & { Boost a given channel
Available: 👤 users only
Peer ID to boost
Archive one or more chats
Available: 👤 users only
Chat ID(s), username(s), phone number(s), "me"
or "self"
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
Chat ID
ID of the user/channel to ban
Optional
shouldWhether to dispatch the returned service message (if any) to the client's update handler.
Optional
untilService message about removed user, if one was generated.
Block a user
Available: 👤 users only
User ID, username or phone number
Check if the current user can apply boost to some channel
Available: ✅ both users and bots
{ 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 boostslots
will contain all the current user's boost slotsCheck if the current user can post stories as a given peer
Available: 👤 users only
Peer ID whose stories to fetch
true
if the user can post stories
"need_admin"
if the user is not an admin in the chat"need_boosts"
if the channel doesn't have enough boostsChange your 2FA password Available: 👤 users only
Current password as plaintext
Optional
hint?: stringHint for the new password
New password as plaintext
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
Chat to open
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
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
Rest
...params: [media: string | InputMediaLike, params?: CommonSendParams & { 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
Rest
...params: [medias: (string | InputMediaLike)[], params?: CommonSendParams & { 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
Rest
...params: [text: InputText, params?: CommonSendParams & { 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 business chat link
Available: 👤 users only
Text to be inserted into the message input
Optional
params: { Optional
title?: stringCustom title for the link
Create a folder from given parameters
ID for the folder is optional, if not provided it will be derived automatically.
Available: 👤 users only
Parameters for the folder
Newly created folder
Create a topic in a forum
Only admins with manageTopics
permission can do this.
Available: ✅ both users and bots
Chat ID or username
Optional
icon?: number | LongIcon 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.
Optional
sendSend as a specific channel
Optional
shouldWhether to dispatch the returned service message (if any) to the client's update handler.
Topic title
Service message for the created topic
Create a legacy group chat
If you want to create a supergroup, use createSupergroup instead. Available: 👤 users only
Group title
Optional
ttlTTL period (in seconds) for the newly created chat
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.
Create an additional invite link for the chat.
You must be an administrator and have appropriate rights.
Available: ✅ both users and bots
Chat ID
Optional
params: { Optional
expires?: number | DateDate when this link will expire.
If number
is passed, UNIX time in ms is expected.
Optional
usageMaximum 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
Optional
withWhether users to be joined via this link need to be approved by an admin
Create a new sticker set.
Available: ✅ both users and bots
Optional
adaptive?: booleanWhether 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 of the sticker set (must be user).
If this pack is created from a user account,
can only be "self"
Optional
progressUpload progress callback.
Index of the sticker
Number of bytes uploaded
Total file size
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 (
List of stickers to be immediately added into the pack. There must be at least one sticker in this list.
Optional
thumb?: InputFileLikeThumbnail 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 of the sticker set (1-64 chars)
Optional
type?: StickerTypeType of the stickers in this set.
Newly created sticker set
Create a new supergroup
Available: 👤 users only
Optional
description?: stringSupergroup description
Optional
forum?: booleanWhether to create a forum
Supergroup title
Optional
ttlTTL period (in seconds) for the newly created supergroup
Newly created supergroup
Delete a business chat link
Available: 👤 users only
The link to delete
Delete a channel or a supergroup
Available: 👤 users only
Chat ID or username
Delete a chat photo
You must be an administrator and have the appropriate permissions.
Available: ✅ both users and bots
Chat ID or username
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
User IDs, usernames or phone numbers
Delete a folder by its ID
Available: 👤 users only
Folder ID or folder itself
Delete a forum topic and all its history
Available: ✅ both users and bots
Chat or user ID, username, phone number, "me"
or "self"
ID of the topic (i.e. its top message ID)
Optional
params: { Optional
shouldWhether to dispatch updates that will be generated by this call.
Doesn't follow disableNoDispatch
Delete a legacy group chat for all members
Available: 👤 users only
Chat ID
Delete communication history (for private chats and legacy groups) Available: 👤 users only
Optional
params: { Optional
maxMaximum ID of message to delete.
Deletion mode. Can be:
delete
: delete messages (only for yourself) AND the dialog itselfclear
: delete messages (only for yourself), but keep the dialog in the listrevoke
: delete messages for all usersDelete one or more Message
Available: ✅ both users and bots
Message(s) to delete
Optional
params: DeleteMessagesParamsDelete messages by their IDs
Available: ✅ both users and bots
Chat's marked ID, its username, phone or "me"
or "self"
.
Message(s) ID(s) to delete.
Optional
params: DeleteMessagesParamsDelete commands for the current bot and the given scope.
Does the same as passing null
to setMyCommands
Learn more about scopes in the Bot API docs Available: 🤖 bots only
Optional
params: { Optional
langUser language applied to the scope.
Optional
scope?: IntermediateScope | TypeBotCommandScopeScope of the commands.
Delete your own profile photos
Available: 👤 users only
ID(s) of the photos. Can be file IDs or raw TL objects
Delete scheduled messages by their IDs.
Available: 👤 users only
Chat's marked ID, its username, phone or "me"
or "self"
.
Message(s) ID(s) to delete.
Delete a sticker from a sticker set
For bots the sticker set must have been created by this bot.
Available: ✅ both users and bots
TDLib and Bot API compatible File ID, or a TL object representing a sticker to be removed
Modfiied sticker set
Delete a story
Available: 👤 users only
Story IDs to delete
Optional
peer?: InputPeerLikePeer ID whose stories to delete
IDs of stories that were removed
Delete a channel or a supergroup
Available: 👤 users only
Chat ID or username
Delete all messages of a user (or channel) in a supergroup Available: 👤 users only
Chat ID
User/channel ID whose messages to delete
Optional
shouldWhether to dispatch the updates that will be generated by this call.
Doesn't follow disableNoDispatch
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
Optional
params: FileDownloadParametersFile download parameters
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
Optional
params: FileDownloadParametersDownload parameters
Download a remote file as a Node.js Readable stream.
Available: ✅ both users and bots
Optional
params: FileDownloadParametersFile download parameters
Download a file and return it as a readable stream, streaming file contents.
Available: ✅ both users and bots
Optional
params: FileDownloadParametersFile download parameters
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
Local file name to which the remote file will be downloaded
Optional
params: FileDownloadParametersFile download parameters
Edit supergroup/channel admin rights of a user. Available: ✅ both users and bots
Chat ID
Optional
rank?: stringCustom admin rank
New admin rights
User ID
Edit an existing business chat link
Available: 👤 users only
The link to edit
Text to be inserted in the message input
Optional
title?: stringCustom title for the link
Edit "close friends" list using InputPeerLike
s
Available: 👤 users only
User IDs
Edit a folder with given modification
Available: 👤 users only
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 to be applied to this folder
Modified folder
Modify a topic in a forum
Only admins with manageTopics
permission can do this.
Available: ✅ both users and bots
Chat ID or username
Optional
icon?: null | LongNew icon of the topic.
Can be a custom emoji ID, or null
to remove the icon
and use static color instead
Optional
shouldWhether to dispatch the returned service message (if any) to the client's update handler.
Optional
title?: stringNew topic title
ID of the topic (i.e. its top message ID)
Service message about the modification
Edit sent inline message text, media and reply markup.
Available: ✅ both users and bots
Optional
disableWhether to disable links preview in this message
Optional
invertWhether to invert media position.
Currently only supported for web previews and makes the client render the preview above the caption and not below.
Optional
media?: InputMediaLikeNew message media
Inline message ID, either as a TL object, or as a TDLib and Bot API compatible string
Optional
progressFor media, upload progress callback.
Number of bytes uploaded
Total file size in bytes
Optional
replyFor bots: new reply markup. If omitted, existing markup will be removed.
Optional
text?: InputTextNew message text
When media
is passed, media.caption
is used instead
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
Chat ID
Optional
expires?: number | DateDate when this link will expire.
If number
is passed, UNIX time in ms is expected.
Invite link to edit
Optional
usageMaximum 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
,
Optional
withWhether users to be joined via this link need to be approved by an admin
Modified invite link
Edit message text, media, reply markup and schedule date.
Available: ✅ both users and bots
Edit a sent story
Available: 👤 users only
Optional
caption?: InputTextOverride caption for media
Story ID to edit
Optional
interactiveInteractive elements to add to the story
Optional
media?: InputMediaLikeMedia contained in a story. Currently can only be a photo or a video.
Optional
peer?: InputPeerLikePeer ID to whose story to edit
Optional
privacyPrivacy rules to apply to the story
Edited story
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
Rest
...args: any[]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
Optional
email?: stringRecovery email
Optional
hint?: stringHint for the new password
2FA password as plaintext
Returns an array listing the events for which the emitter has registered
listeners. The values in the array are strings or Symbol
s.
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) ]
Generate a new primary invite link for a chat, old primary link is revoked.
Note: each administrator has their own primary invite link, and bots by default don't have one.
Available: ✅ both users and bots
Chat IDs
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
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
Search parameters. At least one must be set.
Optional
emoji?: stringFolder emoji
Optional
id?: numberFolder ID
Optional
title?: stringFolder title
Forward one or more Messages to another chat.
Note: all messages must be from the same chat. Available: ✅ both users and bots
Forward one or more messages by their IDs. You can forward no more than 100 messages at once.
Available: ✅ both users and bots
Additional sending parameters
Newly sent, forwarded messages in the destination chat.
Get all scheduled messages in chat
Available: 👤 users only
Chat's marked ID, its username, phone or "me"
or "self"
Get all stories (e.g. to load the top bar) Available: 👤 users only
Optional
params: { Optional
archived?: booleanWhether to fetch stories from "archived" (or "hidden") peers
Optional
offset?: stringOffset from which to fetch stories
Get a list of available message effects Available: 👤 users only
Get information about boosts in a channel
Available: 👤 users only
IDs of stories that were removed
Get boosts of a channel Available: 👤 users only
Optional
params: { Optional
limit?: numberMaximum number of boosters to fetch
Optional
offset?: stringOffset for pagination
Gets information about a bot the current uzer owns (or the current bot) Available: ✅ both users and bots
Optional
bot?: InputPeerLikeWhen called by a user, a bot the user owns must be specified. When called by a bot, must be empty
Optional
langIf passed, will retrieve the bot's description in the given language. If left empty, will retrieve the fallback description.
Fetches the menu button set for the given user. Available: 🤖 bots only
Get current user's business chat links Available: 👤 users only
Get information about the connection of the bot with a business account
Available: 🤖 bots only
ID of the business connection
Request a callback answer from a bot, i.e. click an inline button that contains data.
Available: 👤 users only
Get the message containing the button being clicked in the given callback query. Available: 🤖 bots only
Get basic information about a chat.
Available: ✅ both users and bots
ID of the chat, its username or invite link
MtArgumentError In case you are trying to get info about private chat that you haven't joined. Use getChatPreview instead.
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
Optional
params: { Optional
filters?: InputChatEventFiltersEvent 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.
Optional
limit?: numberLimit 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.
Optional
maxMaximum event ID to return, can be used as a base offset
Optional
minMinimum event ID to return
Optional
query?: stringSearch query
Optional
users?: InputPeerLike[]List of users whose actions to return
Get information about a single chat member
Available: ✅ both users and bots
Chat ID or username
User ID, username, phone number, "me"
or "self"
Chat member, or null
if user is not a member of the chat
Get a chunk of members of some chat.
You can retrieve up to 200 members at once
Available: ✅ both users and bots
Chat ID or username
Optional
params: { Additional parameters
Optional
limit?: numberMaximum 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.
Optional
offset?: numberSequential number of the first member to be returned.
Optional
query?: stringSearch query to filter members by their display names and usernames
Note: Only used for these values of
filter
:all, banned, restricted, mention, contacts
Optional
type?: Type of the query. Can be:
all
: get all membersbanned
: get only banned membersrestricted
: get only restricted membersbots
: get only botsrecent
: get recent membersadmins
: get only administrators (and creator)contacts
: get only contactsmention
: get users that can be mentioned (see tl.RawChannelParticipantsMentions)Only used for channels and supergroups.
Get preview information about a private chat.
Available: 👤 users only
Invite link
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 a preview of a chatlist by its invite link
Available: 👤 users only
Invite link
Get information about a fragment collectible Available: 👤 users only
Get a list of common chats you have with a given user
Available: 👤 users only
User's ID, username or phone number
Given one or more messages, extract all unique custom emojis from it and fetch them Available: ✅ both users and bots
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
Get fact check information for one or more messages in a chat
Available: 👤 users only
Chat where the messages are located
One or more message IDs
Get list of folders. Available: 👤 users only
Get forum topics
Available: 👤 users only
Chat ID or username
Optional
params: { Optional
limit?: numberMaximum number of topics to return.
Optional
offset?: GetForumTopicsOffsetOffset for pagination
Optional
query?: stringSearch query
Get forum topics by their IDs
Available: 👤 users only
Chat ID or username
Get full information about a chat.
Available: ✅ both users and bots
ID of the chat, its username or invite link
MtArgumentError In case you are trying to get info about private chat that you haven't joined. Use getChatPreview instead.
Get high scores of a game Available: 🤖 bots only
Get chat history.
Available: 👤 users only
Chat's marked ID, its username, phone or "me"
or "self"
.
Optional
params: { Additional fetch parameters
Optional
addAdditional offset from offset, in resulting messages.
This can be used for advanced use cases, like:
MSGID
:
offset = MSGID, addOffset = -20, limit = 20
MSGID
:
offset = MSGID, addOffset = -10, limit = 20
Optional
limit?: numberLimits the number of messages to be retrieved.
Optional
maxMaximum message ID to return.
Unless addOffset is used, this will work the same as offset.
Optional
minMinimum message ID to return
Optional
offset?: GetHistoryOffsetOffset for pagination
Optional
reverse?: booleanWhether 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 callgetHistory
withreverse=true
and without any offset, it will return an empty array.
Get high scores of a game from an inline message
Available: 🤖 bots only
ID of the inline message containing the game
Optional
userId: InputPeerLikeID of the user to find high scores for
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
Get detailed information about an invite link
Available: 👤 users only
Chat ID
The invite link
Iterate over users who have joined the chat with the given invite link.
Available: 👤 users only
Chat ID
Optional
params: { Additional params
Optional
limit?: numberMaximum number of users to return
Optional
link?: string | ChatInviteLinkInvite link for which to get members
Optional
offsetOffset request/join date used as an anchor for pagination.
Optional
offsetOffset user used as an anchor for pagination
Optional
requested?: booleanWhether to get users who have requested to join the chat but weren't accepted yet
Optional
requestedSearch 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)
Get 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: 👤 users only
Chat ID
Optional
params: { Optional
admin?: InputPeerLikeOnly return this admin's links.
Optional
limit?: numberLimit the number of invite links to be fetched.
Optional
offset?: GetInviteLinksOffsetOffset for pagination.
Optional
revoked?: booleanWhether to fetch revoked invite links
Returns the current max listener value for the EventEmitter
which is either
set by emitter.setMaxListeners(n)
or defaults to defaultMaxListeners.
Get all messages inside of a message group
Available: ✅ both users and bots
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
Message IDs
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
ID of the chat with messages
Message IDs
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
Chat's marked ID, its username, phone or "me"
or "self"
Messages IDs
Optional
fromReply: booleanWhether the reply to a given message should be fetched
(i.e. getMessages(msg.chat.id, msg.id, true).id === msg.replyToMessageId
)
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
Messages IDs
Optional
fromReply: booleanWhether the reply to a given message should be fetched
(i.e. getMessages(msg.chat.id, msg.id, true).id === msg.replyToMessageId
)
Get a list of current bot's commands for the given command scope and user language. If they are not set, empty set is returned.
Learn more about scopes in the Bot API docs Available: 🤖 bots only
Optional
params: { Optional
langUser language applied to the scope.
Optional
scope?: IntermediateScope | TypeBotCommandScopeScope of the commands.
Get the list of sticker sets that were created by the current user Available: 👤 users only
Get dialogs with certain peers.
Available: 👤 users only
Peers for which to fetch dialogs.
Get stories of a given peer
Available: 👤 users only
Peer ID whose stories to fetch
Optional
dcId: numberGet primary invite link of a chat
Available: 👤 users only
Chat ID
Get a single profile picture of a user by its ID
Available: ✅ both users and bots
User ID, username, phone number, "me"
or "self"
ID of the photo to fetch
Get a list of profile pictures of a user
Available: ✅ both users and bots
User ID, username, phone number, "me"
or "self"
Optional
params: { Optional
limit?: numberMaximum number of items to fetch (up to 100)
Optional
offset?: numberOffset from which to fetch.
Get profile stories Available: 👤 users only
Optional
params: { Optional
kind?: "pinned" | "archived"Kind of stories to fetch
pinned
- stories pinned to the profile and visible to everyonearchived
- "archived" stories that can later be pinned, only visible to the ownerOptional
limit?: numberMaximum number of stories to fetch
Optional
offsetOffset ID for pagination
Get users who have reacted to the message.
Available: 👤 users only
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
Get scheduled messages in chat by their IDs
Fot messages that were not found, null
will be
returned at that position.
Available: 👤 users only
Chat's marked ID, its username, phone or "me"
or "self"
Scheduled messages IDs
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
Get a list of gifts sent to a user.
Available: 👤 users only
User whose gifts to fetch
Optional
params: { Optional
limit?: numberMaximum number of gifts to fetch.
Optional
offset?: stringOffset for pagination.
Gifts sent to the user
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
Peer ID
Optional
params: { Additional parameters
Optional
direction?: "incoming" | "outgoing"If passed, only transactions of this direction will be returned
Optional
limit?: numberPagination limit
Optional
offset?: stringPagination offset
Optional
sort?: "asc" | "desc"Direction to sort transactions date by (default: desc)
Optional
subscriptionIf passed, will only return transactions related to this subscription ID
Get a sticker set and stickers inside of it.
Available: ✅ both users and bots
Sticker set identifier
Get one or more stories by their IDs
Available: 👤 users only
Peer ID whose stories to fetch
Story IDs
Get brief information about stories interactions.
The result will be in the same order as the input IDs Available: 👤 users only
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
Get viewers list of a story Available: 👤 users only
Optional
params: { Optional
limit?: numberMaximum number of viewers to fetch
Optional
offset?: stringOffset ID for pagination
Optional
onlyWhether to only fetch viewers from contacts
Optional
query?: stringSearch query
Optional
sortHow to sort the results?
reaction
- by reaction (viewers who has reacted are first), then by date (newest first)date
- by date, newest firstGet information about multiple users. You can retrieve up to 200 users at once.
Note that order is not guaranteed.
Available: ✅ both users and bots
Users' identifiers. Can be ID, username, phone number, "me"
, "self"
or TL object
Optional
noDispatch: booleanApprove or decline multiple join requests to a chat. Available: 👤 users only
Whether to approve or decline the join requests
Chat/channel ID
Optional
link?: string | ChatInviteLinkInvite link to target
Approve or decline join request to a chat. Available: ✅ both users and bots
Whether to approve or decline the join request
Chat/channel ID
User ID
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
Optional
params: { Optional
future?: booleanWhether to hide views for the next 25 minutes
Optional
past?: booleanWhether to hide views from the last 5 minutes
Import contacts to your Telegram contacts list.
Available: 👤 users only
List of contacts
Optional
force: booleanIncrement 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
Peer ID whose stories to mark as read
ID(s) of the stories to increment views of (max 200)
Create a new takeout session
Available: 👤 users only
Takeout session parameters
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
Check if the given peer/input peer is referring to the current user Available: ✅ both users and bots
Iterate over all stories (e.g. to load the top bar)
Wrapper over getAllStories Available: ✅ both users and bots
Optional
params: { Iterate over boosters of a channel.
Wrapper over getBoosters Available: ✅ both users and bots
Optional
params: { Chat ID
Optional
params: { 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
Chat ID or username
Optional
params: { Additional parameters
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
Optional
params: { Fetch parameters
Optional
archived?: "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 asonly
because of Telegram API limitations.
Optional
chunkChunk size which will be passed to messages.getDialogs
.
You shouldn't usually care about this.
Optional
filter?: 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.
Optional
folder?: InputDialogFolderFolder 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
Optional
limit?: numberLimits the number of dialogs to be received.
Optional
offsetOffset message date used as an anchor for pagination.
Optional
offsetOffset message ID used as an anchor for pagination
Optional
offsetOffset peer used as an anchor for pagination
Optional
pinned?: 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.
Iterate over forum topics. Wrapper over getForumTopics.
Available: ✅ both users and bots
Chat ID or username
Optional
params: { Iterate over chat history. Wrapper over getHistory
Available: ✅ both users and bots
Chat's marked ID, its username, phone or "me"
or "self"
.
Optional
params: { Additional fetch parameters
Iterate over users who have joined the chat with the given invite link.
Available: ✅ both users and bots
Chat ID
Optional
params: { Additional params
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
Chat ID
Optional
params: { Iterate over profile photos
Available: ✅ both users and bots
User ID, username, phone number, "me"
or "self"
Optional
params: { Iterate over profile stories. Wrapper over getProfileStories Available: ✅ both users and bots
Optional
params: { Iterate over users who have reacted to the message.
Wrapper over getReactionUsers.
Available: ✅ both users and bots
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
Optional
params: { Search parameters
Perform a global hashtag search, across the entire Telegram
Iterable version of searchHashtag
Available: ✅ both users and bots
Hashtag to search for
Optional
params: { Additional parameters
Search for messages inside a specific chat
Iterable version of searchMessages
Available: ✅ both users and bots
Optional
params: { Additional search parameters
Peer ID
Optional
params: { Additional parameters
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
Peer ID
Optional
params: { Additional parameters
Iterate over viewers list of a story. Wrapper over getStoryViewers Available: ✅ both users and bots
Optional
params: { 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
Chat identifier. Either an invite link (t.me/joinchat/*
), a username (@username
)
or ID of the linked supergroup or channel.
Join a chatlist by its link
Available: 👤 users only
Invite link to the chatlist
Optional
params: { Additional parameters
Optional
peers?: MaybeArray<InputPeerLike>Chats to join from the chatlist (all by default)
Folder representing the chatlist
Kick a user from a chat.
This effectively bans a user and immediately unbans them.
Available: ✅ both users and bots
Chat ID
User ID
Service message about removed user, if one was generated.
Leave a group chat, supergroup or channel
Available: ✅ both users and bots
Chat ID or username
Optional
params: { Optional
clear?: booleanWhether to clear history after leaving (only for legacy group chats)
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.
The name of the event being listened for
Optional
listener: FunctionThe event handler function
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] ]
Log out from Telegram account and optionally reset the session storage.
When you log out, you can immediately log back in using the same TelegramClient instance.
Available: ✅ both users and bots
On success, true
is returned
Mark a chat as unread
Available: 👤 users only
Chat ID
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
TDLib and Bot API compatible File ID, or a TL object representing a sticker to be removed
New sticker position (starting from 0)
Modified sticker set
Register a raw update handler
Event name
Raw update handler
Register a parsed update handler
Event name
Raw update handler
Register a new message handler
Register an edit message handler
Register a message group handler
Register a delete message handler
Event name
Delete message handler
Register a chat member update handler
Event name
Chat member update handler
Register an inline query handler
Event name
Inline query handler
Register a chosen inline result handler
Event name
Chosen inline result handler
Register a callback query handler
Event name
Callback query handler
Register an inline callback query handler
Event name
Inline callback query handler
Register a business callback query handler
Event name
Business callback query handler
Register a poll update handler
Event name
Poll update handler
Register a poll vote handler
Event name
Poll vote handler
Register an user status update handler
Event name
User status update handler
Register an user typing handler
Event name
User typing handler
Register a history read handler
Event name
History read handler
Register a bot stopped handler
Event name
Bot stopped handler
Register a bot chat join request handler
Event name
Bot chat join request handler
Register a chat join request handler
Event name
Chat join request handler
Register a pre checkout query handler
Event name
Pre checkout query handler
Register a story update handler
Event name
Story update handler
Register a delete story handler
Event name
Delete story handler
Register a bot reaction update handler
Event name
Bot reaction update handler
Register a bot reaction count update handler
Event name
Bot reaction count update handler
Register a business connection update handler
Event name
Business connection update handler
Register a new business message handler
Event name
New business message handler
Register an edit business message handler
Event name
Edit business message handler
Register a business message group handler
Event name
Business message group handler
Register a delete business message handler
Event name
Delete business message handler
Rest
...args: any[]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
The name of the event.
The callback function
Rest
...args: any[]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
Chat to open
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
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 eventName
and 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.
The name of the event.
The callback function
Rest
...args: any[]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.
The name of the event.
The callback function
Rest
...args: any[]Send a media in reply to a given quote
Send a media group in reply to a given quote
Send a text in reply to a given quote
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');
Mark chat history as read.
Available: 👤 users only
Chat ID
Optional
params: { Optional
clearWhether to also clear all mentions in the chat
Optional
maxMessage up until which to read history
Optional
shouldWhether to dispatch updates that will be generated by this call.
Doesn't follow disableNoDispatch
Mark all reactions in chat as read.
Available: 👤 users only
Chat ID
Optional
params: { Optional
shouldWhether to dispatch updates that will be generated by this call.
Doesn't follow disableNoDispatch
Mark all stories up to a given ID as read
This should only be used for "active" stories (Story#isActive == false)
Available: 👤 users only
Peer ID whose stories to mark as read
IDs of the stores that were marked as read
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.
Optional
event: string | symbolRemoves 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.
Rest
...args: any[]Reorder pinned forum topics
Only admins with manageTopics
permission can do this.
Available: 👤 users only
Chat ID or username
Optional
force?: booleanWhether to un-pin topics not present in the order
Order of the pinned topics
Reorder usernames
Available: 👤 users only
Bot, channel or "me"/"self"
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
TDLib and Bot API compatible File ID, or a TL object representing a sticker to be removed
New sticker to replace the old one with
Optional
params: { Optional
progressUpload progress callback
Number of bytes uploaded
Total file size
Modfiied sticker set
Send a media in reply to a given message
Rest
...params: [media: string | InputMediaLike, params?: CommonSendParams & { Send a media group in reply to a given message
Rest
...params: [medias: (string | InputMediaLike)[], params?: CommonSendParams & { Send a text in reply to a given message
Rest
...params: [text: InputText, params?: CommonSendParams & { 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
Optional
abortAbort signal
Phone number in international format
Confirmation code identifier from SentCode
Shorthand for resolvePeer
that converts the input peer to InputChannel
.
Available: ✅ both users and bots
Optional
force: booleanGet the InputPeer
of a known peer id.
Useful when an InputPeer
is needed in Raw API.
Available: ✅ both users and bots
The peer identifier that you want to extract the InputPeer
from.
Optional
force: booleanWhether to force re-fetch the peer from the server (only for usernames and phone numbers)
Get multiple InputPeer
s at once,
while also normalizing and removing
peers that can't be normalized to that type.
If a peer was not found, it will be skipped.
Uses async pool internally, with a concurrent limit of 8
Peer Ids
Normalization function
Get multiple InputPeer
s at once.
If a peer was not found, null
will be returned instead
Uses async pool internally, with a concurrent limit of 8
Peer Ids
Shorthand for resolvePeer
that converts the input peer to InputUser
.
Available: ✅ both users and bots
Optional
force: booleanRestrict a user in a supergroup. Available: ✅ both users and bots
Chat ID
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
Optional
until?: number | DateDate 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.
User ID
Revoke an invite link.
If link
is a primary invite link, a new invite link will be
generated automatically by Telegram
Available: ✅ both users and bots
Chat ID
Invite link to revoke
If link
is a primary invite, newly generated invite link, otherwise the revoked link
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 to be passed to start
Optional
abortAbort signal
Optional
botBot token to use. Ignored if phone
is supplied.
Optional
code?: 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.
Optional
codeCustom 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.
Optional
codeAdditional code settings to pass to the server
Optional
forceWhether to force code delivery through SMS
Optional
futureSaved future auth tokens, if any
Optional
invalidIf 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.
Optional
password?: MaybeDynamic<string>2FA password. Ignored if botToken
is supplied
Optional
phone?: MaybeDynamic<string>Phone number of the account. If account does not exist, it will be created
Optional
qrWhen 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.
Optional
session?: string | StringSessionDataString 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.
Optional
sessionWhether to overwrite existing session.
Optional
then: ((user: User) => void | Promise<void>)Function to be called after start returns
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
ID of the chat, its username, phone or "me"
or "self"
Draft message, or null
to delete.
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
Optional
params: { Search parameters
Optional
filter?: TypeMessagesFilterFilter the results using some filter. (see SearchFilters)
Optional
limit?: numberLimits the number of messages to be retrieved.
Optional
maxOnly return messages older than this date
Optional
minOnly return messages newer than this date
Optional
offset?: SearchGlobalOffsetOffset data used for pagination
Optional
onlyWhether to only search across broadcast channels
Optional
query?: stringText query string. Use "@"
to search for mentions.
Perform a global hashtag search, across the entire Telegram
Available: 👤 users only
Hashtag to search for
Optional
params: { Additional parameters
Optional
limit?: numberLimit the number of results
Optional
offset?: SearchHashtagOffsetOffset for the search
Search for messages inside a specific chat
Available: 👤 users only
Optional
params: { Additional search parameters
Optional
addAdditional offset from offset, in resulting messages.
This can be used for advanced use cases, like:
MSGID
:
offset = MSGID, addOffset = -20, limit = 20
MSGID
:
offset = MSGID, addOffset = -10, limit = 20
When offset is not set, this will be relative to the last message
Optional
chatChat where to search for messages.
When empty, will search across common message box (i.e. private messages and legacy chats)
Optional
filter?: TypeMessagesFilterFilter the results using some filter (see SearchFilters)
Optional
fromSearch only for messages sent by a specific user.
You can pass their marked ID, username, phone or "me"
or "self"
Optional
limit?: numberLimits the number of messages to be retrieved.
Optional
maxMaximum message date to return
Optional
maxMaximum message ID to return.
Unless addOffset is used, this will work the same as offset.
Optional
minMinimum message date to return
Optional
minMinimum message ID to return
Optional
offset?: numberOffset ID for the search. Only messages earlier than this ID will be returned.
Optional
query?: stringText query string. Required for text-only messages, optional for media.
Optional
threadThread ID to return only messages from this thread.
Send the confirmation code to the given phone number
Available: 👤 users only
Optional
abortAbort signal
Optional
codeAdditional code settings to pass to the server
Optional
futureSaved future auth tokens, if any
Phone number in international format
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
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
Send a single media (a photo or a document-based media)
Available: ✅ both users and bots
ID of the chat, its username, phone or "me"
or "self"
Media contained in the message. You can also pass TDLib and Bot API compatible File ID, which will be wrapped in InputMedia.auto
Optional
params: CommonSendParams & { Additional sending parameters
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
ID of the chat, its username, phone or "me"
or "self"
Medias contained in the message.
Optional
params: CommonSendParams & { Additional sending parameters
Send a paid reaction using Telegram Stars.
Available: 👤 users only
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
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 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
Chat where the messages were scheduled
ID(s) of the messages
Send a star gift to a user.
Note: this method is not indended to be used by full-fledged clients, as this method hides the actual invoice and payment form from the user. For GUI clients, you should refer to the method's source code and present the payment form to the user.
Available: 👤 users only
Optional
anonymous?: booleanWhether to send the gift anonymously (i.e. if the recipient chooses to display the gift on their profile, your name won't be visible)
ID of the gift to send
Optional
message?: InputTextMessage to send along with the gift
Optional
shouldWhether to dispatch the new message event to the client's update handler.
ID of the user to send the gift to
Service message about the sent gift
Send a story
Available: 👤 users only
Optional
caption?: InputTextOverride caption for media
Optional
forbidWhether to disallow sharing this story
Optional
interactiveInteractive elements to add to the story
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
Optional
peer?: InputPeerLikePeer ID to send story as
Optional
period?: numberTTL period of the story, in seconds
Optional
pinned?: booleanWhether to automatically pin this story to the profile
Optional
privacyPrivacy rules to apply to the story
Created story
Send (or remove) a reaction to a story Available: 👤 users only
Optional
addWhether to add this reaction to recently used
Send a text message
Available: ✅ both users and bots
ID of the chat, its username, phone or "me"
or "self"
Text of the message
Optional
params: CommonSendParams & { Additional sending parameters
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
Chat ID
Optional
status: Typing status
Optional
params: { Optional
businessUnique identifier of the business connection on behalf of which the action will be sent
Optional
progress?: numberFor upload_*
and history import actions, progress of the upload
Optional
threadFor comment threads, ID of the thread (i.e. top message)
Send or retract a vote in a poll. Available: 👤 users only
Sets information about a bot the current uzer owns (or the current bot) Available: ✅ both users and bots
Optional
bio?: stringNew bio text (displayed in the profile)
Optional
bot?: InputPeerLikeWhen called by a user, a bot the user owns must be specified. When called by a bot, must be empty
Optional
description?: stringNew description text (displayed when the chat is empty)
Optional
langIf passed, will update the bot's description in the given language. If left empty, will change the fallback description.
Optional
name?: stringNew bot name
Sets a menu button for the given user. Available: 🤖 bots only
Set current user's business introduction.
Available: 👤 users only
Introduction parameters, or null
to remove
Set peer color and optionally background pattern Available: 👤 users only
Optional
backgroundBackground pattern emoji ID.
Must be an adaptive emoji, otherwise the request will fail.
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
.Optional
forWhether to set this color for the profile header instead of chat name/replies.
Currently only available for the current user.
Optional
peer?: InputPeerLikePeer where to update the color.
By default will change the color for the current user
Change default chat permissions for all members.
You must be an administrator in the chat and have appropriate permissions.
Available: ✅ both users and bots
Chat ID or username
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
Change chat description
You must be an administrator and have the appropriate permissions.
Available: ✅ both users and bots
Chat ID or username
New chat description, 0-255 characters
Set a new chat photo or video.
You must be an administrator and have the appropriate permissions. Available: ✅ both users and bots
Chat ID or username
Input media file
Optional
previewWhen type = video
, timestamp in seconds which will be shown
as a static preview.
Media type (photo or video)
Set group sticker set for a supergroup
Available: ✅ both users and bots
Sticker set short name or a TL object with input sticker set
Modified sticker set
Change chat title
You must be an administrator and have the appropriate permissions.
Available: ✅ both users and bots
Chat ID or username
New chat title, 1-255 characters
Set maximum Time-To-Live of all newly sent messages in the specified chat
Available: 👤 users only
Chat ID
New TTL period, in seconds (or 0 to disable)
Change supergroup/channel username
You must be an administrator and have the appropriate permissions.
Available: 👤 users only
Chat ID or current username
New username, or null
to remove
Set a score of a user in a game
Available: 🤖 bots only
The modified message
Set a score of a user in a game contained in an inline message
Available: 🤖 bots only
Optional
force?: booleanWhether to allow user's score to decrease. This can be useful when fixing mistakes or banning cheaters
ID of the inline message
Optional
noWhen true
, the game message will not be modified
to include the new score
The new score (must be >0)
ID of the user who has scored
By default EventEmitter
s 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.
Set or delete commands for the current bot and the given scope
Learn more about scopes in the Bot API docs Available: 🤖 bots only
New list of bot commands for the given scope.
Pass empty array or null
to delete them.
Optional
langUser language applied to the scope.
Optional
scope?: IntermediateScope | TypeBotCommandScopeScope of the commands.
Sets the default chat permissions for the bot in the supergroup or channel. Available: 🤖 bots only
The default chat permissions.
Whether to target groups or channels.
Set an emoji status for the current user
Available: 👤 users only
Custom emoji ID or null
to remove the emoji
Optional
params: { Optional
until?: number | DateDate when the emoji status should expire (only if emoji
is not null
)
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
Input media file
Optional
previewWhen type = video
, timestamp in seconds which will be shown as a static preview.
Media type (photo or video)
Change username of the current user.
Note that bots usernames must be changed through bot support or re-created from scratch.
Available: 👤 users only
New username (5-32 chars, allowed chars: a-zA-Z0-9_
), or null
to remove
Set supergroup's slow mode interval.
Available: 👤 users only
Chat ID or username
Optional
seconds: numberSlow 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)
Set sticker set thumbnail
Available: ✅ both users and bots
Sticker set short name or a TL object with input sticker set
Sticker set thumbnail
Optional
params: { Optional
progressUpload progress callback
Number of bytes uploaded
Total file size
Modified sticker set
Authorize a user in Telegram with a valid confirmation code.
Available: 👤 users only
Optional
abortAbort signal
Phone number in international format
The confirmation code that was received
Code identifier from sendCode
If the code was valid and authorization succeeded, the User is returned.
Authorize a bot using its token issued by @BotFather
Available: ✅ both users and bots
Bot token issued by BotFather
Bot's User object
Execute the QR login flow.
This method will resolve once the authorization is complete, returning the authorized user. Available: 👤 users only
Optional
abortAbort signal
Optional
invalidFunction 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.
Optional
onFunction 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
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
Optional
password?: MaybeDynamic<string>Password for 2FA
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
Optional
abortAbort signal
Optional
botBot token to use. Ignored if phone
is supplied.
Optional
code?: 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.
Optional
codeCustom 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.
Optional
codeAdditional code settings to pass to the server
Optional
forceWhether to force code delivery through SMS
Optional
futureSaved future auth tokens, if any
Optional
invalidIf 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.
Optional
password?: MaybeDynamic<string>2FA password. Ignored if botToken
is supplied
Optional
phone?: MaybeDynamic<string>Phone number of the account. If account does not exist, it will be created
Optional
qrWhen 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.
Optional
session?: string | StringSessionDataString 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.
Optional
sessionWhether to overwrite existing session.
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
Optional
params: { Additional parameters
Optional
dcOverride user's DC. Must be a valid test DC.
Optional
logout?: booleanWhether to log out if current session is logged in.
Optional
phone?: stringOverride phone number. Must be a valid Test phone number.
By default is randomly generated.
Set whether a chat has content protection (i.e. forwarding messages is disabled)
Available: 👤 users only
Chat ID or username
Optional
enabled: booleanWhether content protection should be enabled
Set whether a supergroup is a forum.
Only owner of the supergroup can change this setting.
Available: 👤 users only
Chat ID or username
Optional
enabled: booleanWhether the supergroup should be a forum
Toggle open/close status of a topic in a forum
Only admins with manageTopics
permission can do this.
Available: ✅ both users and bots
Chat ID or username
Whether the topic should be closed
Optional
shouldWhether to dispatch the returned service message (if any) to the client's update handler.
ID of the topic (i.e. its top message ID)
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
Chat ID or username
Whether the topic should be pinned
ID of the topic (i.e. its top message ID)
Toggle a collectible (Fragment) username
Note: non-collectible usernames must still be changed using setUsername/setChatUsername Available: 👤 users only
Whether to enable or disable the username
Peer ID whose username to toggle
Username to toggle
Toggle whether "General" topic in a forum is hidden or not
Only admins with manageTopics
permission can do this.
Available: ✅ both users and bots
Chat ID or username
Whether the topic should be hidden
Optional
shouldWhether to dispatch the returned service message (if any) to the client's update handler.
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
Chat ID or username
Optional
enabled: booleanWhether join requests should be enabled
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
Chat ID or username
Optional
enabled: booleanWhether join-to-send setting should be enabled
Toggle whether peer's stories are archived (hidden) or not.
This does not archive the chat with that peer, only stories. Available: 👤 users only
Toggle one or more stories pinned status
Available: 👤 users only
Story ID(s) to toggle
Optional
peer?: InputPeerLikePeer ID whose stories to toggle
Whether to pin or unpin the story
IDs of stories that were toggled
Translate message text to a given language.
Returns null
if it could not translate the message.
Available: 👤 users only
Translate text to a given language.
Available: 👤 users only
Text to translate
Target language (two-letter ISO 639-1 language code)
Unarchive one or more chats
Available: 👤 users only
Chat ID(s), username(s), phone number(s), "me"
or "self"
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
Chat ID
User/channel ID who should be unbanned
Unblock a user
Available: 👤 users only
User ID, username or phone number
Unpin all pinned messages in a chat.
Available: ✅ both users and bots
Chat or user ID
Optional
params: { Optional
shouldWhether to dispatch updates that will be generated by this call.
Doesn't follow disableNoDispatch
Optional
topicFor forums - unpin only messages from the given topic
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
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
Chat ID
User/channel ID who should be unbanned
Update your profile details.
Only pass fields that you want to change.
Available: 👤 users only
Optional
bio?: stringNew bio (max 70 chars). Pass ''
(empty string) to remove it
Optional
firstNew first name
Optional
lastNew last name. Pass ''
(empty string) to remove it
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
Upload parameters
Optional
estimatedIf the file size is unknown, you can provide an estimate, which will be used to determine appropriate part size.
Upload file source.
Optional
fileFile MIME type. By default is automatically inferred from magic number
If MIME can't be inferred, it defaults to application/octet-stream
Optional
fileFile 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"
Optional
fileTotal file size. Automatically inferred for Buffer, File and local files.
Optional
partUpload part size (in KB).
By default, automatically selected by file size. Must not be bigger than 512 and must not be a fraction.
Optional
progressFunction that will be called after some part has been uploaded.
Number of bytes already uploaded
Total file size, if known
Optional
requestsNumber of parts to be sent in parallel per connection.
Optional
requireWhen using inputMediaUploadedPhoto
(e.g. when sending an uploaded photo) require
the file extension to be known beforehand.
This will make the library try to guess the file extension from the file mime type, or throw an error if it cannot be guessed.
Optional
requireWhen 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.
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
Media to upload
Optional
params: { Upload parameters
Optional
peer?: InputPeerLikeOptional
progressWrap this client so that all RPC calls will use the specified parameters.
Parameters to use
Wrapped client
Static
addExperimental
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 AbortSignal
s 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]();
}
}
Disposable that removes the abort
listener.
Static
getReturns a copy of the array of listeners for the event named eventName
.
For EventEmitter
s this behaves exactly the same as calling .listeners
on
the emitter.
For EventTarget
s 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] ]
}
Static
getReturns the currently set max amount of listeners.
For EventEmitter
s this behaves exactly the same as calling .getMaxListeners
on
the emitter.
For EventTarget
s 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
}
Static
listenerA class method that returns the number of listeners for the given eventName
registered 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
The emitter to query
The event name
Static
onimport { 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());
The name of the event being listened for
Optional
options: StaticEventEmitterOptionsthat iterates eventName
events emitted by the emitter
Static
onceCreates 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!
Optional
options: StaticEventEmitterOptionsOptional
options: StaticEventEmitterOptionsStatic
setimport { setMaxListeners, EventEmitter } from 'node:events';
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
Optional
n: numberA non-negative number. The maximum number of listeners per EventTarget
event.
Rest
...eventTargets: (EventEmitter | _DOMEventTarget)[]
Value:
Symbol.for('nodejs.rejection')
See how to write a custom
rejection handler
.