Checks whether the current client is authorized or not. (logged in as a user)
boolean (true of authorized else false)
Logs out the currently authenticated user/bot. Invalidates the session
on Telegram's side (via auth.LogOut), disconnects the client and wipes
local session data so a subsequent session.save() returns nothing.
After this call the client is disconnected and event handlers stop
firing; reconnecting requires going through start/signInUser again.
true if the server-side log out succeeded, false if the
auth.LogOut call failed. Local session data is wiped in both cases.
Resets the login email when the user cannot access their current email. This will cancel the current email verification and allow setting up a new one.
The phone number being used for login
The phone code hash from sendCode
The new sent code result
Sends a telegram authentication code to the phone number.
credentials to be used.
the phone number to send the code to
whether to send it as an SMS or a normal in app message
OptionalreCaptchaCallback: (siteKey: string) => Promise<string>
callback to handle reCAPTCHA verification
the phone code hash and whether it was sent via app
Sends an email verification code for login setup. This is used when Telegram requires email verification during login.
The phone number being used for login
The phone code hash from sendCode
The email address to verify
The email pattern and code length
const result = await client.sendVerifyEmailCode(
"+1234567890",
"abc123hash",
"[email protected]"
);
console.log(`Code sent to ${result.emailPattern}, length: ${result.length}`);
Used to sign in as a bot.
credentials to be used.
user auth params.
instance User of the logged in bot.
Logs in as a user. Should only be used when not already logged in.
This method will send a code when needed.
This will also sign up if needed.
credentials to be used.
user auth params.
await client.connect();
// we should only use this when we are not already authorized.
// This function is very similar to `client.start`
// The minor difference that start checks if already authorized and supports bots as well.
if (!await client.checkAuthorization()){
const phoneNumber = "+123456789";
await client.signIn({
apiId:132456,
apiHash:"132456",
},{
phoneNumber: async () => await input.text("number ?"),
password: async () => await input.text("password?"),
phoneCode: async () => await input.text("Code ?"),
onError: (err) => console.log(err),
})
}
logs the user using a QR code to be scanned.
this function generates the QR code that needs to be scanned by mobile.
The flow can be cancelled at any time (e.g. the user closed the page) by
passing an abortSignal; once aborted it stops polling for tokens and
rejects with an AbortError.
credentials to be used.
user auth params. Pass abortSignal to cancel the flow.
'''ts
await client.connect();
const controller = new AbortController();
// call controller.abort() to cancel the QR login at any time
try {
const user = await client.signInUserWithQrCode({ apiId, apiHash },
{
onError: async function(p1: Error) {
console.log("error", p1);
// true = stop the authentication processes
return true;
},
qrCode: async (code) => {
console.log("Convert the next string to a QR code and scan it");
console.log(
`tg://login?token=${code.token.toString("base64url")}`
);
},
password: async (hint) => {
// password if needed
return "1111";
},
abortSignal: controller.signal,
}
);
console.log("user is", user);
} catch (err) {
if (err.name === "AbortError") console.log("QR login cancelled");
else throw err;
}
'''
Uses the 2FA password to sign in the account.
This function should be used after the user has signed in with the code they received.
credentials to be used.
user auth params.
the logged in user.
Signs in with a web authorization token
(auth.importWebTokenAuthorization).
Users only — bots cannot invoke this. It may be used over an
unauthenticated connection, so a plain TelegramClient.connect is
enough beforehand. The token is short-lived: once expired — or
already redeemed elsewhere, e.g. by the browser that opened the login
URL — the server answers WEBAUTH_TOKEN_EXPIRED.
Your { apiId, apiHash }.
The authorization token.
The signed-in user.
Changes the 2FA settings of the logged in user. Note that this method may be incredibly slow depending on the prime numbers that must be used during the process to make sure that everything is safe.
Has no effect if both current and new password are omitted.
The telegram client instance
Promise
Verifies an email address during login setup.
The phone number being used for login
The phone code hash from sendCode
The verification result (code, Google token, or Apple token)
The verified email and the new sent code for phone verification
Builds a ReplyInlineMarkup or ReplyKeyboardMarkup for the given buttons.
Does nothing if either no buttons are provided or the provided argument is already a reply markup.
this function is called internally when passing an array of buttons.
The button, array of buttons, array of array of buttons or markup to convert into a markup.
Whether the buttons must be inline buttons only or not.
import {Button} from "teleproto/tl/custom/button";
// PS this function is not async
const markup = client.buildReplyMarkup(Button.inline("Hello!"));
await client.sendMessage(chat, {
message: "click me!",
buttons: markup,
}
// The following example can also be used in a simpler way like so
await client.sendMessage(chat, {
message: "click me!",
buttons: [Button.inline("Hello!")],
}
Clears the message draft in the given chat.
The chat whose draft should be cleared.
Closes a poll you sent, preventing further votes.
The chat where the poll message is.
The poll message or its ID.
The closed Api.Poll with its final results. Closing a
poll emits an updateMessagePoll, not a message update, so there is no
message to hand back here — read it with TelegramClient.getMessages if you need one.
Copies messages to another chat without the "forwarded from" header.
Same as forwardMessages with dropAuthor always set.
The chat the messages should be copied to.
see ForwardMessagesParams.
Deletes the given messages, optionally "for everyone".
See also Message.delete`.
From who the message will be deleted. This can actually be undefined for normal chats, but must be present for channels and megagroups.
The IDs (or ID) or messages to be deleted.
Whether the message should be deleted for everyone or not. By default it has the opposite behaviour of official clients, and it will delete the message for everyone. Disabling this has no effect on channels or megagroups, since it will unconditionally delete the message for everyone.
A list of AffectedMessages, each item being the result for the delete calls of the messages in chunks of 100 each.
Deletes scheduled messages before they are sent.
The chat where the scheduled messages are.
The scheduled message ID(s) to delete.
Used to edit a message by changing it's text or media
message refers to the message to be edited not what to edit
text refers to the new text
See also Message.edit()
Notes: It is not possible to edit the media of a message that doesn't contain media.
From which chat to edit the message.
This can also be the message to be edited, and the entity will be inferred from it, so the next parameter will be assumed to be the message text.
You may also pass a InputBotInlineMessageID, which is the only way to edit messages that were sent after the user selects an inline query result. Not supported yet!
see EditMessageParams.
The edited Message.
MESSAGE_AUTHOR_REQUIRED if you're not the author of the message but tried editing it anyway.
MESSAGE_NOT_MODIFIED if the contents of the message were not modified at all.
MESSAGE_ID_INVALID if the ID of the message is invalid (the ID itself may be correct, but the message with that ID cannot be edited).
For example, when trying to edit messages with a reply markup (or clear markup) this error will be raised.
Gets the discussion-group counterpart of a channel post — the message you reply to when leaving a comment under the post.
The broadcast channel where the post is.
The channel post or its ID.
Same as iterMessages() but returns a TotalList instead.
if the limit is not set, it will be 1 by default unless both minId and maxId are set. in which case the entire range will be returned.
The entity from whom to retrieve the message history. see TelegramClient.iterMessages.
see IterMessagesParams.
TotalList of messages.
// The totalList has a .total attribute which will show the complete number of messages even if none are fetched.
// Get 0 photos and print the total to show how many photos there are
import { Api } from "teleproto";
const photos = await client.getMessages(chat, {limit: 0, filter:Api.InputMessagesFilterPhotos})
console.log(photos.total)
// Get all the photos
const photos = await client.getMessages(chat, {limit: undefined, filter:Api.InputMessagesFilterPhotos})
// Get messages by ID:
const messages = await client.getMessages(chat, {ids:1337})
const message_1337 = messages[0];
Gets (and optionally increments) the view/forward counters of channel
posts (messages.getMessagesViews).
Optionalincrement: booleanGets users who reacted to a message.
The chat/channel where the message is.
The message ID.
Optionalparams: { limit?: number; offset?: string; reaction?: string | TypeReaction }
Optionallimit?: numberMaximum number of users to return.
Optionaloffset?: stringPagination offset.
Optionalreaction?: string | TypeReactionFilter by specific emoji string or a raw Api.TypeReaction (e.g. custom emoji).
Fetches the full content of a rich message whose delivery was
truncated — message.richMessage.part set (messages.getRichMessage).
Usually you want Api.Message.fetchRichMessage instead, which
updates the message in place.
The chat where the message is.
The message or its ID.
Gets scheduled messages of a chat.
The chat whose scheduled messages should be fetched.
Optionalids: number | number[]
Specific scheduled message ID(s). Omit to fetch all.
Iterates over a file's contents chunk by chunk — streaming download
without buffering the whole file in memory (upload.getFile).
A message with media, the media itself, or a raw Api.TypeInputFileLocation.
Optionalparams: IterDownloadParams
see IterDownloadParams.
Iterates over the messages for a given chat.
The default order is from newest to oldest but can be changed with the reverse param.
If either search, filter or fromUser are provided this will use Api.messages.Search instead of Api.messages.GetHistory.
The entity from whom to retrieve the message history.
It may be undefined to perform a global search, or to get messages by their ID from no particular chat
Note that some of the offsets will not work if this is the case.
Note that if you want to perform a global search, you must set a non-empty search string, a filter. or fromUser.
IterMessagesParams
Telegram limits GetHistory requests every 10 requests (1 000 messages) therefore a sleep of 1 seconds will be the default for this limit.
// From most-recent to oldest
for await (const message of client.iterMessages(chat,{}){
console.log(message.id, message.text)
}
// From oldest to most-recent
for await (const message of client.iterMessages(chat,{reverse:true}){
console.log(message.id, message.text)
}
// Filter by sender
for await (const message of client.iterMessages(chat,{fromUser:"me"}){
console.log(message.id, message.text)
}
// Server-side search with fuzzy text
for await (const message of client.iterMessages(chat,{search:"hello"}){
console.log(message.id, message.text)
}
// Filter by message type:
import { Api } from "teleproto";
for await (const message of client.iterMessages(chat,{filter: Api.InputMessagesFilterPhotos}){
console.log(message.id, message.photo)
}
// Getting comments from a post in a channel:
* for await (const message of client.iterMessages(chat,{replyTo: 123}){
console.log(message.chat.title,, message.text)
}
Marks messages as read and optionally clears mentions.
This effectively marks a message as read (or more than one) in the given conversation.
If a message or maximum ID is provided, all the messages up to and
including such ID will be marked as read (for all messages whose ID ≤ max_id).
See also Message.markRead`.
The chat where the message should be pinned.
Optionalmessage: MessageIDLike | MessageIDLike[]
The message or the message ID to pin. If it's undefined, all messages will be unpinned instead.
OptionalmarkAsReadParams: MarkAsReadParams
see MarkAsReadParams.
boolean
If neither message nor maximum ID are provided, all messages will be marked as read by assuming that max_id = 0.
// using a Message object
const message = await client.sendMessage(chat, 'teleproto is awesome!');
await client.markAsRead(chat, message)
// ...or using the int ID of a Message
await client.markAsRead(chat, message.id);
// ...or passing a list of messages to mark as read
await client.markAsRead(chat, messages)
This property is the default parse mode used when sending messages. Defaults to MarkdownParser.
It will always be either undefined or an object with parse and unparse methods.
When setting a different value it should be one of:
Pins a message in a chat.
See also Message.pin`.
The chat where the message should be pinned.
Optionalmessage: undefined
The message or the message ID to pin. If it's undefined, all messages will be unpinned instead.
OptionalpinMessageParams: UpdatePinMessageParams
see UpdatePinMessageParams.
The pinned message. if message is undefined the return will be AffectedHistory
Pins a message in a chat.
See also Message.pin`.
The chat where the message should be pinned.
The message or the message ID to pin. If it's undefined, all messages will be unpinned instead.
OptionalpinMessageParams: UpdatePinMessageParams
see UpdatePinMessageParams.
The pinned message. if message is undefined the return will be AffectedHistory
Saves a message draft in the given chat.
The chat where the draft should be saved.
Optionalparams: SaveDraftParams
see SaveDraftParams. Empty params clear the draft.
Sends a message to the specified user, chat or channel.
The default parse mode is the same as the official applications (a custom flavour of markdown). bold, code or italic are available.
In addition you can send links and mentions (or using IDs like in the Bot API: mention) and pre blocks with three backticks.
Sending a /start command with a parameter (like ?start=data) is also done through this method. Simply send '/start data' to the bot.
See also Message.respond() and Message.reply().
Who to sent the message to.
see SendMessageParams
The sent custom Message.
// Markdown is the default.
await client.sendMessage("me",{message:"Hello **world!**});
// Defaults to another parse mode.
client.setParseMode("HTML");
await client.sendMessage('me', {message:'Some <b>bold</b> and <i>italic</i> text'})
await client.sendMessage('me', {message:'An <a href="https://example.com">URL</a>'})
await client.sendMessage('me', {message:'<a href="tg://user?id=me">Mentions</a>'})
// Explicit parse mode.
// No parse mode by default
client.setParseMode(undefined);
//...but here I want markdown
await client.sendMessage('me', {message:'Hello, **world**!', {parseMode:"md"}})
// ...and here I need HTML
await client.sendMessage('me', {message:'Hello, <i>world</i>!', {parseMode='html'}})
// Scheduling a message to be sent after 5 minutes
await client.sendMessage(chat, {message:'Hi, future!', schedule:(60 * 5) + (Date.now() / 1000)})
Sends a poll or quiz to the given chat.
The chat where the poll should be sent.
The poll definition, see SendPollParams.
Optionalparams: Omit<SendFileInterface, "file" | "caption">
Common send options (silent, schedule, replyTo, etc).
Sends a reaction to a message.
The chat/channel where the message is.
The message ID to react to.
Optionalreaction: TypeReaction[]
Array of reactions. Use Api.ReactionEmoji or Api.ReactionCustomEmoji.
Optionalbig: boolean
Whether to show a big animation.
OptionaladdToRecent: boolean
Whether to add the reaction to your recent reactions list.
Sends scheduled messages immediately, without waiting for their date.
The chat where the scheduled messages are.
The scheduled message ID(s) to send now.
The sent messages.
Setter for parseMode. parseMode
can be md,markdown for Markdown or html for html. can also pass a custom mode. pass undefined for no parsing.
Translates messages or raw text (messages.translateText).
see TranslateTextParams.
Unpins a message in a chat.
See also Message.unpin`.
The chat where the message should be unpinned.
Optionalmessage: undefined
The message or the message ID to unpin. If it's undefined, all messages will be unpinned instead.
OptionalpinMessageParams: UpdatePinMessageParams
see UpdatePinMessageParams.
The pinned message. if message is undefined the return will be AffectedHistory
Unpins a message in a chat.
See also Message.unpin`.
The chat where the message should be unpinned.
The message or the message ID to unpin. If it's undefined, all messages will be unpinned instead.
OptionalpinMessageParams: UpdatePinMessageParams
see UpdatePinMessageParams.
The pinned message. if message is undefined the return will be AffectedHistory
Votes in a poll.
The chat where the poll message is.
The poll message or its ID.
Answer index(es) (0-based), or raw option bytes.
Low-level method to download files from their input location. downloadMedia should generally be used over this.
The file location from which the file will be downloaded. See getInputLocation source for a complete list of supported types.
DownloadFileParams
a Buffer downloaded from the inputFile.
Downloads the given media from a message or a media object.
this will return an empty Buffer in case of wrong or empty media.
instance of a message or a media.
OptionaldownloadParams: string | DownloadMediaInterface
a buffer containing the downloaded data if outputFile is undefined else nothing.
Downloads the profile photo from the given user,chat or channel.
This method will return an empty buffer in case of no profile photo.
where to download the photo from.
DownloadProfilePhotoParams
buffer containing the profile photo. can be empty in case of no profile photo.
Sends message with the given file to the specified entity. This uses TelegramClient.uploadFile internally so if you want more control over uploads you can use that.
who will receive the file.
see SendFileInterface
// Normal files like photos
await client.sendFile(chat, {file:'/my/photos/me.jpg', caption:"It's me!"})
// or
await client.sendMessage(chat, {message:"It's me!", file:'/my/photos/me.jpg'})
Voice notes or round videos
await client.sendFile(chat, {file: '/my/songs/song.mp3', voiceNote:True})
await client.sendFile(chat, {file: '/my/videos/video.mp4', videoNote:True})
// Custom thumbnails
await client.sendFile(chat, {file:'/my/documents/doc.txt', thumb:'photo.jpg'})
// Only documents
await client.sendFile(chat, {file:'/my/photos/photo.png', forceDocument:True})
//logging progress
await client.sendFile(chat, {file: file, progressCallback=console.log})
// Dices, including dart and other future emoji
await client.sendFile(chat, {file:new Api.InputMediaDice("")})
await client.sendFile(chat, {file:new Api.InputMediaDice("🎯")})
// Contacts
await client.sendFile(chat, {file: new Api.InputMediaContact({
phoneNumber:'+1 123 456 789',
firstName:'Example',
lastName:'',
vcard:''
}))
Uploads a file to Telegram's servers, without sending it.
see UploadFileParams
Api.InputFileBig if the file size is larger than 10mb otherwise Api.InputFile
generally it's better to use TelegramClient.sendFile instead.
This method returns a handle (an instance of InputFile or InputFileBig, as required) which can be later used before it expires (they are usable during less than a day).
Uploading a file will simply return a "handle" to the file stored remotely in the Telegram servers,
which can be later used on. This will not upload the file to your own chat or any chat at all.
This also can be used to update profile pictures
Creates a new broadcast channel or supergroup
(channels.createChannel).
see CreateChannelParams.
The created Api.Channel.
Creates a new small group chat (messages.createChat).
see CreateChatParams.
The created chat and the users that could not be invited.
Deletes the message history of a chat, optionally for the other side too
(messages.deleteHistory / channels.deleteHistory).
The chat whose history should be deleted.
Optionalparams: DeleteHistoryParams
see DeleteHistoryParams.
Promotes, edits or demotes an admin (channels.editAdmin).
Every unset right is revoked — pass an empty object to demote.
The chat where the rights should apply.
The user to promote/demote.
The rights to grant, see EditAdminParams. A raw Api.ChatAdminRights is also accepted.
Bans or restricts a participant of a channel/supergroup
(channels.editBanned).
Without params the participant is fully banned (viewMessages).
Pass an empty object to lift all restrictions (unban).
The channel/supergroup.
The participant to ban or restrict.
Optionalparams: ChatBannedRights | EditBannedParams
The restrictions to apply, see EditBannedParams. A raw Api.ChatBannedRights is also accepted.
Edits the description of a chat, channel or supergroup
(messages.editChatAbout).
The chat.
The new description.
Edits the default rights of ALL members of a chat
(messages.editChatDefaultBannedRights).
The chat.
The restrictions applying to every member, see EditBannedParams.
Moves chats to a peer folder — 1 is the archive, 0 the main list
(folders.editPeerFolders).
The chat(s) to move.
The destination folder: 1 = archive, 0 = unarchive.
Edits the photo of a chat, channel or supergroup.
The chat.
Optionalphoto: FileLike | TypeInputChatPhoto
The new photo (path, Buffer, uploaded file…), a raw Api.TypeInputChatPhoto, or omit to delete the current photo.
Edits the title of a chat, channel or supergroup.
The chat to rename.
The new title.
Gets the admin log (recent actions) of a channel/supergroup. Same as TelegramClient.iterAdminLog, but returns a collected array.
The channel/supergroup.
Optionalparams: AdminLogParams
see AdminLogParams.
Gets the chats you have in common with a user
(messages.getCommonChats).
The user.
Optionalparams: GetCommonChatsParams
see GetCommonChatsParams.
Gets a single participant of a channel or supergroup.
The channel/supergroup.
The participant to fetch.
Exact same as iterParticipants but returns a TotalList instead.
This can be used if you want to retrieve a list instead of iterating over the users.
entity to get users from.
IterParticipantsParams.
Joins a chat via an invite link (messages.importChatInvite).
The invite link (https://t.me/+hash) or the bare hash.
Iterates over the admin log (recent actions) of a channel/supergroup. Requires admin rights.
The channel/supergroup.
Optionalparams: AdminLogParams
see AdminLogParams. Set filter fields to only receive those event types.
instances of Api.ChannelAdminLogEvent.
Iterates over the participants belonging to a specified chat , channel or supergroup.
Channels can return a maximum of 200 users while supergroups can return up to 10 000.
You must be an admin to retrieve users from a channel.
The entity from which to retrieve the participants list.
IterParticipantsParams
The filter ChannelParticipantsBanned will return restricted users. If you want banned users you should use ChannelParticipantsKicked instead.
The User objects returned by GetParticipants with an additional .participant attribute
which is the matched ChannelParticipant type for channels/supergroup or ChatParticipants for normal chats.
// logs all user IDs in a chat.
for await (const user of client.iterParticipants(chat)){
console.log("User id",user.id);
}
// Searches by name.
for await (const user of client.iterParticipants(chat, {search: "name"})){
console.log("Username is ",user.username); // Some users don't have a username so this can be undefined.
}
// Filter by admins.
import { Api } from "teleproto";
for await (const user of client.iterParticipants(chat, {filter: Api.ChannelParticipantsAdmins})){
console.log("admin first name is ",user.firstName);
}
Joins a channel or supergroup (channels.joinChannel).
To join via an invite link use importChatInvite.
The channel to join.
Kicks a user from a chat.
Kicking yourself ('me') will result in leaving the chat.
Leaves a channel or supergroup (channels.leaveChannel).
The channel to leave.
Sends a chat action — "typing…", "recording video…" etc.
(messages.setTyping). The action disappears automatically after a few
seconds or when a message is sent; repeat the call for long operations.
The chat where the action should be shown.
Optionalaction: The action name or a raw Api.TypeSendMessageAction. Defaults to "typing". Use "cancel" to stop.
Optionalparams: { topMsgId?: number }
OptionaltopMsgId?: numberThe forum topic where the action should be shown.
Enables or changes the slow mode of a supergroup
(channels.toggleSlowMode).
The supergroup.
Optionalseconds: number
Seconds users must wait between messages. 0 (the default) disables slow mode. Allowed values: 0, 10, 30, 60, 300, 900, 3600.
Gets info about a chat by its invite link WITHOUT joining — title,
photo, participant count, and whether you are already a member
(messages.checkChatInvite).
The invite link (https://t.me/+hash) or the bare hash.
Deletes a previously revoked invite link
(messages.deleteExportedChatInvite).
The chat the link belongs to.
The revoked invite link to delete.
Deletes all revoked invite links of an admin
(messages.deleteRevokedExportedChatInvites).
The chat.
Optionaladmin: EntityLike
The admin whose revoked links should be deleted. Defaults to yourself.
Edits or revokes an invite link (messages.editExportedChatInvite).
The chat the link belongs to.
The invite link to edit.
see EditExportedChatInviteParams. Pass { revoked: true } to revoke.
Creates a new invite link for a chat (messages.exportChatInvite).
The chat.
Optionalparams: ExportChatInviteParams
see ExportChatInviteParams.
Gets the list of admins that have created invite links for a chat,
with their link counts (messages.getAdminsWithInvites).
The chat.
Gets the users that joined a chat via invite links, or pending join
requests with requested: true. Same as iterChatInviteImporters,
but returns a collected array.
The chat.
Optionalparams: ChatInviteImportersParams
see ChatInviteImportersParams.
Gets info about a specific invite link, including its usage counters
(messages.getExportedChatInvite).
The chat the link belongs to.
The invite link.
Gets the invite links of a chat. Same as iterExportedChatInvites, but returns a collected array.
The chat.
Optionalparams: ExportedChatInvitesParams
see ExportedChatInvitesParams.
Approves or declines ALL pending join requests of a chat
(messages.hideAllChatJoinRequests).
The chat.
Optionalparams: { approved?: boolean; link?: string }
approved: true approves all; link restricts to requests from one invite link.
Approves or declines a pending join request
(messages.hideChatJoinRequest).
The chat.
The user whose join request should be handled.
Optionalparams: { approved?: boolean }
{ approved: true } approves; omitted or false declines.
Iterates over the users that joined a chat via invite links, or over
pending join requests with requested: true
(messages.getChatInviteImporters).
The chat.
Optionalparams: ChatInviteImportersParams
see ChatInviteImportersParams.
instances of Api.ChatInviteImporter.
Iterates over the invite links of a chat
(messages.getExportedChatInvites).
The chat.
Optionalparams: ExportedChatInvitesParams
see ExportedChatInvitesParams.
instances of Api.TypeExportedChatInvite.
Creates a topic in a forum (messages.createForumTopic).
The forum.
see CreateForumTopicParams.
Edits a forum topic: title, icon, closed/hidden state
(messages.editForumTopic).
The forum.
The topic ID (its top message ID).
see EditForumTopicParams.
Gets the topics of a forum, with their last messages
(messages.getForumTopics).
The forum.
Optionalparams: GetForumTopicsParams
see GetForumTopicsParams.
Posts a story (stories.sendStory).
Where to post: "me" or a channel you manage.
see SendStoryParams.
Reacts to a story (stories.sendReaction).
Optionalreaction: string | BigInteger | TypeReaction
An emoji string, a custom emoji document ID, or a raw Api.TypeReaction. Omit to remove the reaction.
Optionalparams: { addToRecent?: boolean }Adds a user to your contact list (contacts.addContact).
The user to add.
see AddContactParams.
Blocks a peer (contacts.block).
The peer to block.
Optionalparams: { myStoriesFrom?: boolean }
OptionalmyStoriesFrom?: booleanOnly hide your stories from the peer instead of fully blocking.
Removes users from your contact list (contacts.deleteContacts).
The contact(s) to remove.
Deletes profile photos (photos.deletePhotos).
The photos to delete, e.g. from getUserPhotos.
Gets your blocklist (contacts.getBlocked).
Optionalparams: GetBlockedParams
see GetBlockedParams.
Gets the privacy rules of a privacy key (account.getPrivacy).
e.g. new Api.InputPrivacyKeyStatusTimestamp().
Imports phone-book contacts (contacts.importContacts).
The entries to import, see ImportContactEntry.
Which entries were imported and which users were already on Telegram.
Terminates other authorized sessions. Pass a session hash from
getAuthorizations to terminate one, or nothing to terminate
ALL other sessions (account.resetAuthorization / auth.resetAuthorizations).
Optionalhash: BigIntegerChanges the privacy rules of a privacy key (account.setPrivacy).
e.g. new Api.InputPrivacyKeyStatusTimestamp().
e.g. [new Api.InputPrivacyValueAllowContacts()].
Unblocks a peer (contacts.unblock).
The peer to unblock.
Optionalparams: { myStoriesFrom?: boolean }
OptionalmyStoriesFrom?: booleanOnly unhide your stories instead of the full blocklist.
Changes the notification settings of a peer — mute/unmute, sounds,
previews (account.updateNotifySettings).
Updates your profile name and/or bio (account.updateProfile).
Only the fields you set are changed.
see UpdateProfileParams.
Sets an existing photo as the current profile photo
(photos.updateProfilePhoto).
The photo to reuse.
Optionalparams: { bot?: EntityLike; fallback?: boolean }
Optionalbot?: EntityLikeBot owners: change the photo of an owned bot.
Optionalfallback?: booleanSet the fallback photo instead of the main one.
Updates your online status (account.updateStatus).
Optionalonline: boolean
true (the default) to appear online, false to go offline immediately.
Changes your username (account.updateUsername).
The new username. Pass an empty string to remove it.
Same as iterDialogs but returns a TotalList instead of an iterator.
IterDialogsParams
// Get all open conversation, print the title of the first
const dialogs = await client.getDialogs({});
const first = dialogs[0];
console.log(first.title);
<br/>
// Use the dialog somewhere else
await client.sendMessage(first, {message: "hi"});
<br/>
// Getting only non-archived dialogs (both equivalent)
non_archived = await client.get_dialogs({folder:0})
non_archived = await client.get_dialogs({archived:false})
<br/>
// Getting only archived dialogs (both equivalent)
archived = await client.get_dialogs({folder:1})
archived = await client.get_dialogs({archived:true})
Iterator over the dialogs (open conversations/subscribed channels) sequentially.
The order is the same as the one seen in official applications. (dialogs that had recent messages come first)
see IterDialogsParams
Makes an inline query to the specified bot and gets the result list.
This is equivalent to writing @pic something in clients
the bot entity to which the inline query should be made
the query string that should be made for that bot (up to 512 characters). can be empty
Optionalentity: InputPeerSelf
The entity where the inline query is being made from.
Certain bots use this to display different results depending on where it's used, such as private chats, groups or channels.
If specified, it will also be the default entity where the message will be sent after clicked.
Otherwise, the “empty peer” will be used, which some bots may not handle correctly.
Optionaloffset: string
String offset of the results to be returned. can be empty
OptionalgeoPoint: TypeInputGeoPoint
The geo point location information to send to the bot for localised results. Available under some bots.
a list of InlineResults
Bots only: sets the bot's command list (bots.setBotCommands).
see BotCommandEntry.
Optionalparams: BotCommandScopeParams
Scope and language, see BotCommandScopeParams.
Registers a new event handler callback.
The callback will be called when the specified event occurs.
The callable function accepting one parameter to be used.
Note the event type passed in the callback will change depending on the eventBuilder.
The event builder class or instance to be used,
for example new events.NewMessage({});.
If left unspecified, Raw (the Api.TypeUpdate objects with no further processing) will be passed instead.
import {TelegramClient} from "teleproto";
import { NewMessage } from "teleproto/events";
import { NewMessageEvent } from "teleproto/events";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
async function handler(event: NewMessageEvent) {
...
}
client.addEventHandler(handler, new NewMessage({}));
Registers a new event handler callback.
The callback will be called when the specified event occurs.
The callable function accepting one parameter to be used.
Note the event type passed in the callback will change depending on the eventBuilder.
The event builder class or instance to be used,
for example new events.NewMessage({});.
If left unspecified, Raw (the Api.TypeUpdate objects with no further processing) will be passed instead.
import {TelegramClient} from "teleproto";
import { NewMessage } from "teleproto/events";
import { NewMessageEvent } from "teleproto/events";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
async function handler(event: NewMessageEvent) {
...
}
client.addEventHandler(handler, new NewMessage({}));
Registers a new event handler callback.
The callback will be called when the specified event occurs.
The callable function accepting one parameter to be used.
Note the event type passed in the callback will change depending on the eventBuilder.
The event builder class or instance to be used,
for example new events.NewMessage({});.
If left unspecified, Raw (the Api.TypeUpdate objects with no further processing) will be passed instead.
import {TelegramClient} from "teleproto";
import { NewMessage } from "teleproto/events";
import { NewMessageEvent } from "teleproto/events";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
async function handler(event: NewMessageEvent) {
...
}
client.addEventHandler(handler, new NewMessage({}));
Registers a new event handler callback.
The callback will be called when the specified event occurs.
The callable function accepting one parameter to be used.
Note the event type passed in the callback will change depending on the eventBuilder.
The event builder class or instance to be used,
for example new events.NewMessage({});.
If left unspecified, Raw (the Api.TypeUpdate objects with no further processing) will be passed instead.
import {TelegramClient} from "teleproto";
import { NewMessage } from "teleproto/events";
import { NewMessageEvent } from "teleproto/events";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
async function handler(event: NewMessageEvent) {
...
}
client.addEventHandler(handler, new NewMessage({}));
Registers a new event handler callback.
The callback will be called when the specified event occurs.
The callable function accepting one parameter to be used.
Note the event type passed in the callback will change depending on the eventBuilder.
The event builder class or instance to be used,
for example new events.NewMessage({});.
If left unspecified, Raw (the Api.TypeUpdate objects with no further processing) will be passed instead.
import {TelegramClient} from "teleproto";
import { NewMessage } from "teleproto/events";
import { NewMessageEvent } from "teleproto/events";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
async function handler(event: NewMessageEvent) {
...
}
client.addEventHandler(handler, new NewMessage({}));
Registers a new event handler callback.
The callback will be called when the specified event occurs.
The callable function accepting one parameter to be used.
Note the event type passed in the callback will change depending on the eventBuilder.
Optionalevent: EventBuilder
The event builder class or instance to be used,
for example new events.NewMessage({});.
If left unspecified, Raw (the Api.TypeUpdate objects with no further processing) will be passed instead.
import {TelegramClient} from "teleproto";
import { NewMessage } from "teleproto/events";
import { NewMessageEvent } from "teleproto/events";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
async function handler(event: NewMessageEvent) {
...
}
client.addEventHandler(handler, new NewMessage({}));
Lists all registered event handlers.
pair of [eventBuilder,CallableFunction]
Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.
Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.
Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.
Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.
Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.
Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.
Optionalevent: EventBuilderInverse operation of addEventHandler().
the callback function to be removed.
the type of the event.
The update pipeline: middleware, typed subscriptions and live subscriptions to chats. See ClientUpdates.
Returns the DC IP address.
This will do an API request to fill the cache if it's the first time it's called.
The DC ID.
whether to use -1 DCs or not TODO, hardcode IPs. (These only support downloading/uploading and not creating a new AUTH key)
The current teleproto version.
Optionalconnection: ConnectionOptional_Checks whether you can post a story and how many slots remain (stories.canSendStory).
Clears all message drafts in all chats.
Clears your recent stickers (messages.clearRecentStickers).
Optionalparams: { attached?: boolean }a session to be used to save the connection and auth key to. This can be a custom session that inherits MemorySession.
The API ID you obtained from https://my.telegram.org.
The API hash you obtained from https://my.telegram.org.
Deletes stories (stories.deleteStories). Returns the IDs that were actually deleted.
Disconnects all senders and removes all handlers Disconnect is safer as it will not remove your event handlers
Edits a posted story (stories.editStory).
The in-memory entity cache. Exposes size, has, delete and
clear so stale peers can be invalidated without touching internals.
See TelegramClientParams.entityCache for bounding it.
Exports a t.me link to a story (stories.exportStoryLink).
Adds or removes a sticker from your favorites (messages.faveSticker).
Optionalparams: { unfave?: boolean }Forwards the given messages to the specified entity.
If you want to "forward" a message without the forward header
(the "forwarded from" text), you should use sendMessage with
the original message instead. This will send a copy of it.
See also Message.forwardTo`.
To which entity the message(s) will be forwarded.
see ForwardMessagesParams
The list of forwarded Message, Note.
if some messages failed to be forwarded the returned list will have them as undefined.
// a single one await client.forwardMessages(chat, {messages: message}); // or await client.forwardMessages(chat, {messages:messageId,fromPeer:fromChat}); // or await message.forwardTo(chat)
// multiple await client.forwardMessages(chat, {messages:messages}); // or await client.forwardMessages(chat, {messages:messageIds,fromPeer:fromChat});
// Forwarding as a copy await client.sendMessage(chat, {message:message});
@category
Gets the account self-destruction period, in days (account.getAccountTTL).
Gets all your installed sticker sets (messages.getAllStickers).
Gets the active stories of all your peers (stories.getAllStories).
Optionalparams: GetAllStoriesParamsGets the list of your authorized sessions (account.getAuthorizations).
Bots only: gets the bot's command list (bots.getBotCommands).
Optionalparams: BotCommandScopeParamsBots only: gets the menu button of a user's chat with the bot (bots.getBotMenuButton).
Gets custom emoji documents by their IDs (messages.getCustomEmojiDocuments).
Gets your chat folders (messages.getDialogFilters).
Turns the given entity into a valid Telegram Api.User, Api.Chat or Api.Channel.
You can also pass a list or iterable of entities, and they will be efficiently fetched from the network.
If a username is given, the username will be resolved making an API call every time.
Resolving usernames is an expensive operation and will start hitting flood waits around 50 usernames in a short period of time.
Similar limits apply to invite links, and you should use their ID instead.
Using phone numbers (from people in your contact list), exact names, integer IDs or Peer rely on a getInputEntity first,
which in turn needs the entity to be in cache, unless a InputPeer was passed.
If the entity can't be found, ValueError will be raised.
Api.Chat,Api.Chat or Api.Channel corresponding to the input entity. A list will be returned if more than one was given.
Telegram does not allow to get user profile by integer id if current client had never "saw" it.
const me = await client.getEntity("me");
console.log("My name is", utils.getDisplayName(me));
const chat = await client.getInputEntity("username");
for await (const message of client.iterMessages(chat)) {
console.log("Message text is", message.text);
}
// Note that you could have used the username directly, but it's
// good to use getInputEntity if you will reuse it a lot.
Turns the given entity into a valid Telegram Api.User, Api.Chat or Api.Channel.
You can also pass a list or iterable of entities, and they will be efficiently fetched from the network.
If a username is given, the username will be resolved making an API call every time.
Resolving usernames is an expensive operation and will start hitting flood waits around 50 usernames in a short period of time.
Similar limits apply to invite links, and you should use their ID instead.
Using phone numbers (from people in your contact list), exact names, integer IDs or Peer rely on a getInputEntity first,
which in turn needs the entity to be in cache, unless a InputPeer was passed.
If the entity can't be found, ValueError will be raised.
Api.Chat,Api.Chat or Api.Channel corresponding to the input entity. A list will be returned if more than one was given.
Telegram does not allow to get user profile by integer id if current client had never "saw" it.
const me = await client.getEntity("me");
console.log("My name is", utils.getDisplayName(me));
const chat = await client.getInputEntity("username");
for await (const message of client.iterMessages(chat)) {
console.log("Message text is", message.text);
}
// Note that you could have used the username directly, but it's
// good to use getInputEntity if you will reuse it a lot.
Gets your favorite stickers (messages.getFavedStickers).
Gets specific forum topics by their IDs (messages.getForumTopicsByID).
Gets global privacy settings (account.getGlobalPrivacySettings).
Gets who read your message in a small group, with dates (messages.getMessageReadParticipants).
Gets the notification settings of a peer (account.getNotifySettings).
Gets when your message was read in a private chat (messages.getOutboxReadDate).
Gets the active stories of a specific peer (stories.getPeerStories).
Gets the stories pinned on a peer's profile (stories.getPinnedStories).
Optionalparams: GetStoriesPageParamsGets your recently used stickers (messages.getRecentStickers).
Optionalparams: { attached?: boolean }Gets your story archive (stories.getStoriesArchive).
Optionalparams: GetStoriesPageParamsGets stories by their IDs (stories.getStoriesByID).
Gets the viewers of one of your stories (stories.getStoryViewsList).
Optionalparams: GetStoryViewsListParamsIncrements the view counter of stories (stories.incrementStoryViews).
Installs a sticker set (messages.installStickerSet).
Optionalparams: { archived?: boolean }Optionalsender: MTProtoSender | SessionLeaseMarks a peer's stories as read up to maxId (stories.readStories).
OptionalmaxId: numberReorders the pinned forum topics (messages.reorderPinnedForumTopics).
Optionalparams: { force?: boolean }Bots only: clears the bot's command list (bots.resetBotCommands).
Optionalparams: BotCommandScopeParamsAdds or removes a sticker from your recent stickers (messages.saveRecentSticker).
Optionalparams: { attached?: boolean; unsave?: boolean }Sets the account self-destruction period, in days (account.setAccountTTL).
Sets the name/about/description of a bot you own (bots.setBotInfo).
Bots only: sets the menu button of a user's chat with the bot (bots.setBotMenuButton).
Sets global privacy settings (account.setGlobalPrivacySettings).
Used to handle all aspects of connecting to telegram.
This method will connect to the telegram servers and check if the user is already logged in.
in the case of a new connection this will sign in if the phone already exists or sign up otherwise
By using this method you are agreeing to Telegram's Terms of Service https://core.telegram.org/api/terms.
this method also calls getMe to tell telegram that we want to receive updates.
OptionalauthParams: UserAuthParams | BotAuthParams
see UserAuthParams and BotAuthParams
nothing
// this example assumes you've installed and imported the input package. npm i input.
// This package uses CLI to receive input from the user. you can use your own callback function.
import { TelegramClient } from "teleproto";
import { StringSession } from "teleproto/sessions";
const client = new TelegramClient(new StringSession(''), apiId, apiHash, {});
// logging in as a bot account
await client.start(botToken="123456:abcdfgh123456789);
// logging in as a user account
await client.start({
phoneNumber: async () => await input.text("number ?"),
password: async () => await input.text("password?"),
phoneCode: async () => await input.text("Code ?"),
onError: (err) => console.log(err),
});
>Number ? +1234567897
>Code ? 12345
>password ? 111111
Logged in as user...
You can now use the client instance to call other api requests.
@category
Enables or disables forum topics in a supergroup (channels.toggleForum).
Optionaltabs: booleanToggles viewing a forum as a regular chat (channels.toggleViewForumAsMessages).
Uninstalls a sticker set (messages.uninstallStickerSet).
Reorders your chat folders (messages.updateDialogFiltersOrder).
Centralised pts/qts/seq tracker and gap recovery driver.
Pins or unpins a forum topic (messages.updatePinnedForumTopic).
Gets a sticker set with all its stickers (messages.getStickerSet).
The set's short name (from its t.me/addstickers link) or a raw Api.TypeInputStickerSet.
Creates, updates or deletes a chat folder
(messages.updateDialogFilter).
The folder ID (2-255).
Optionalfilter: TypeDialogFilter
The new folder definition, or omit to delete the folder.
Typed 1:1 facade over the raw MTProto methods.
Call client.api.messages.getDialogs({ limit: 10 }) instead of
client.invoke(new Api.messages.GetDialogs({ limit: 10 })) — no new,
no manual invoke, with full autocomplete and strict typing (including
the return type) generated straight from the schema.
Turns the given entity into its input entity version.
Almost all requests use this kind of InputPeer, so this is the most suitable call to make for those cases.
Generally you should let the library do its job and don't worry about getting the input entity first, but if you're going to use an entity often, consider making the call.
If a username or invite link is given, the library will use the cache.
This means that it's possible to be using a username that changed or an old invite link (this only happens if an invite link for a small group chat is used after it was upgraded to a mega-group).
Api.InputPeerUser , Api.InputPeerChat , Api.InputPeerChannel or Api.InputPeerSelf if the parameter is "me" or "self"
// If you're going to use "username" often in your code
// (make a lot of calls), consider getting its input entity
// once, and then using the "user" everywhere instead.
user = await client.getInputEntity('username')
// The same applies to IDs, chats or channels.
chat = await client.getInputEntity(-123456789)
Gets the current logged in Api.User. If the user has not logged in this will throw an error.
Whether to return the input peer version Api.InputPeerUser or the whole user Api.User.
Your own Api.User
Gets the current logged in Api.User. If the user has not logged in this will throw an error.
OptionalinputPeer: false
Whether to return the input peer version Api.InputPeerUser or the whole user Api.User.
Your own Api.User
Gets the ID for the given entity.
This method needs to be async because peer supports usernames, invite-links, phone numbers (from people in your contact list), etc.
If addMark is false, then a positive ID will be returned instead. By default, bot-API style IDs (signed) are returned.
whether to return a bot api style id.
the ID of the entity.
invokes raw Telegram requests.
This is a low level method that can be used to call manually any Telegram API method.
Generally this should only be used when there isn't a friendly method that does what you need.
All available requests and types are found under the Api. namespace.
The request to send. this should be of type request.
OptionaldcId: number
Optional dc id to use when sending.
The response from Telegram.
The TelegramClient uses several methods in different files to provide all the common functionality in a nice interface. In short, to create a client you must do:
You don't need to import any methods that are inside the TelegramClient class as they binding in it.