teleproto - v1.229.0
    Preparing search index...

    Class TelegramClient<S>

    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:

    import {TelegramClient} from "teleproto";

    const client = new TelegramClient(new StringSession(''),apiId,apiHash,{});

    You don't need to import any methods that are inside the TelegramClient class as they binding in it.

    Type Parameters

    Hierarchy (View Summary)

    Index
    • Checks whether the current client is authorized or not. (logged in as a user)

      Returns Promise<boolean>

      boolean (true of authorized else false)

      await client.connect();
      if (await client.checkAuthorization()){
      console.log("I am logged in!");
      }else{
      console.log("I am connected to telegram servers but not logged in with any account/bot");
      }
    • 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.

      Returns Promise<boolean>

      true if the server-side log out succeeded, false if the auth.LogOut call failed. Local session data is wiped in both cases.

      await client.logOut();
      
    • 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.

      Parameters

      • phoneNumber: string

        The phone number being used for login

      • phoneCodeHash: string

        The phone code hash from sendCode

      Returns Promise<TypeSentCode>

      The new sent code result

      // User can't access their email, reset it
      const newSentCode = await client.resetLoginEmail("+1234567890", "abc123hash");
    • Sends a telegram authentication code to the phone number.

      Parameters

      • apiCredentials: ApiCredentials

        credentials to be used.

      • phoneNumber: string

        the phone number to send the code to

      • forceSMS: boolean = false

        whether to send it as an SMS or a normal in app message

      • OptionalreCaptchaCallback: (siteKey: string) => Promise<string>

        callback to handle reCAPTCHA verification

      Returns Promise<SendCodeResult>

      the phone code hash and whether it was sent via app

      await client.connect();
      const {phoneCodeHash,isCodeViaApp} = await client.sendCode({
      apiId:1234,
      apiHash:"123456789abcfghj",
      },"+123456798"});
    • Sends an email verification code for login setup. This is used when Telegram requires email verification during login.

      Parameters

      • phoneNumber: string

        The phone number being used for login

      • phoneCodeHash: string

        The phone code hash from sendCode

      • email: string

        The email address to verify

      Returns Promise<SentEmailCodeResult>

      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.

      Parameters

      Returns Promise<TypeUser>

      instance User of the logged in bot.

      await client.connect();
      const bot = await client.signInBot({
      apiId:1234,
      apiHash:"12345",
      },{
      botToken:"123456:abcdfghae4fg654",
      });
      // we are now logged in as a bot
      console.log("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.

      Parameters

      Returns Promise<TypeUser>

      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.

      Parameters

      Returns Promise<TypeUser>

      '''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;
      }

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

      Parameters

      • apiCredentials: ApiCredentials

        Your { apiId, apiHash }.

      • webAuthToken: string

        The authorization token.

      Returns Promise<User>

      The signed-in user.

      API_ID_INVALID when the API credentials are wrong.

      WEBAUTH_TOKEN_EXPIRED when the token is no longer valid.

      await client.connect();
      const me = await client.signInWithWebToken({ apiId, apiHash }, token);
      console.log(client.session.save());
    • 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.

      Parameters

      Returns Promise<void>

      Promise

      this method can throw: "PASSWORD_HASH_INVALID" if you entered a wrong password (or set it to undefined). "EMAIL_INVALID" if the entered email is wrong "EMAIL_HASH_EXPIRED" if the user took too long to verify their email

    • Verifies an email address during login setup.

      Parameters

      • phoneNumber: string

        The phone number being used for login

      • phoneCodeHash: string

        The phone code hash from sendCode

      • verification: EmailVerificationResult

        The verification result (code, Google token, or Apple token)

      Returns Promise<EmailVerifiedLoginResult>

      The verified email and the new sent code for phone verification

      // Verify with email code
      const result = await client.verifyEmail(
      "+1234567890",
      "abc123hash",
      { type: "code", code: "12345" }
      );

      // Or verify with Google Sign-In
      const result = await client.verifyEmail(
      "+1234567890",
      "abc123hash",
      { type: "google", token: "google-id-token" }
      );
    • 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.

      Parameters

      • buttons: TypeReplyMarkup | ButtonLike | ButtonLike[] | ButtonLike[][] | undefined

        The button, array of buttons, array of array of buttons or markup to convert into a markup.

      • inlineOnly: boolean = false

        Whether the buttons must be inline buttons only or not.

      Returns TypeReplyMarkup | undefined

      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.

      Parameters

      • entity: EntityLike

        The chat whose draft should be cleared.

      Returns Promise<boolean>

    • Closes a poll you sent, preventing further votes.

      Parameters

      • entity: EntityLike

        The chat where the poll message is.

      • message: MessageIDLike

        The poll message or its ID.

      Returns Promise<Poll>

      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.

    • Deletes the given messages, optionally "for everyone".

      See also Message.delete`.

      Parameters

      • entity: EntityLike | undefined

        From who the message will be deleted. This can actually be undefined for normal chats, but must be present for channels and megagroups.

      • messageIds: MessageIDLike[]

        The IDs (or ID) or messages to be deleted.

      • revoke: { revoke?: boolean }

        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.

      Returns Promise<AffectedMessages[]>

      A list of AffectedMessages, each item being the result for the delete calls of the messages in chunks of 100 each.

      This method does not validate that the message IDs belong to the chat that you passed! It's possible for the method to delete messages from different private chats and small group chats at once, so make sure to pass the right IDs.

       await client.deleteMessages(chat, messages);

      await client.deleteMessages(chat, messages, {revoke:false});
    • Deletes scheduled messages before they are sent.

      Parameters

      • entity: EntityLike

        The chat where the scheduled messages are.

      • ids: number | number[]

        The scheduled message ID(s) to delete.

      Returns Promise<void>

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

      Parameters

      • entity: EntityLike

        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!

      • editMessageParams: EditMessageParams

        see EditMessageParams.

      Returns Promise<Message>

      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.

       const message = await client.sendMessage(chat,{message:"Hi!"});

      await client.editMessage(chat,{message:message,text:"Hello!"}
      // or
      await client.editMessage(chat,{message:message.id,text:"Hello!"}
    • Gets the discussion-group counterpart of a channel post — the message you reply to when leaving a comment under the post.

      Parameters

      • entity: EntityLike

        The broadcast channel where the post is.

      • message: MessageIDLike

        The channel post or its ID.

      Returns Promise<Message | undefined>

    • Fetches a message by its t.me link.

      Supports public (t.me/username/123), private (t.me/c/123456/123), forum-topic and ?comment= discussion links, plus tg:// deep links.

      Parameters

      • link: string

        The message link.

      Returns Promise<Message | undefined>

      The message, or undefined if it does not exist.

      const message = await client.getMessageByLink("https://t.me/durov/123");
      
    • 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.

      Parameters

      Returns Promise<TotalList<Message>>

      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 users who reacted to a message.

      Parameters

      • entity: EntityLike

        The chat/channel where the message is.

      • messageId: number

        The message ID.

      • Optionalparams: { limit?: number; offset?: string; reaction?: string | TypeReaction }
        • Optionallimit?: number

          Maximum number of users to return.

        • Optionaloffset?: string

          Pagination offset.

        • Optionalreaction?: string | TypeReaction

          Filter by specific emoji string or a raw Api.TypeReaction (e.g. custom emoji).

      Returns Promise<MessageReactionsList>

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

      Parameters

      • entity: EntityLike

        The chat where the message is.

      • message: MessageIDLike

        The message or its ID.

      Returns Promise<Message | undefined>

    • Gets scheduled messages of a chat.

      Parameters

      • entity: EntityLike

        The chat whose scheduled messages should be fetched.

      • Optionalids: number | number[]

        Specific scheduled message ID(s). Omit to fetch all.

      Returns Promise<Message[]>

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

      Parameters

      • entity: EntityLike | undefined

        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.

      • iterParams: Partial<IterMessagesParams> = {}

        IterMessagesParams

      Returns _IDsIter | _MessagesIter

      Telegram limits GetHistory requests every 10 requests (1 000 messages) therefore a sleep of 1 seconds will be the default for this limit.

      Instances of custom Message

      // 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`.

      Parameters

      • entity: EntityLike

        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.

      Returns Promise<boolean>

      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)
    • get parseMode(): ParseInterface | undefined

      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:

      • Object with parse and unparse methods.
      • A str indicating the parse_mode. For Markdown 'md' or 'markdown' may be used. For HTML, 'html' may be used.
        The parse method should be a function accepting a single parameter, the text to parse, and returning a tuple consisting of (parsed message str, [MessageEntity instances]).

        The unparse method should be the inverse of parse such that text == unparse(parse(text)).

        See Api.TypeMessageEntity for allowed message entities.

      Returns ParseInterface | undefined

      // gets the current parse mode.
      console.log("parse mode is :", client.parseMode)
    • Pins a message in a chat.

      See also Message.pin`.

      Parameters

      • entity: EntityLike

        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.

      Returns Promise<AffectedHistory>

      The pinned message. if message is undefined the return will be AffectedHistory

      The default behavior is to not notify members, unlike the official applications.

       const message = await client.sendMessage(chat, 'teleproto is awesome!');

      await client.pinMessage(chat, message);
    • Pins a message in a chat.

      See also Message.pin`.

      Parameters

      • entity: EntityLike

        The chat where the message should be pinned.

      • message: MessageIDLike

        The message or the message ID to pin. If it's undefined, all messages will be unpinned instead.

      • OptionalpinMessageParams: UpdatePinMessageParams

        see UpdatePinMessageParams.

      Returns Promise<Message>

      The pinned message. if message is undefined the return will be AffectedHistory

      The default behavior is to not notify members, unlike the official applications.

       const message = await client.sendMessage(chat, 'teleproto is awesome!');

      await client.pinMessage(chat, message);
    • Saves a message draft in the given chat.

      Parameters

      • entity: EntityLike

        The chat where the draft should be saved.

      • Optionalparams: SaveDraftParams

        see SaveDraftParams. Empty params clear the draft.

      Returns Promise<boolean>

      await client.saveDraft(chat, { message: "answer this tomorrow", replyTo: 123 });
      
    • 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().

      Parameters

      • entity: EntityLike

        Who to sent the message to.

      • sendMessageParams: SendMessageParams = {}

        see SendMessageParams

      Returns Promise<Message>

      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.

      Parameters

      • entity: EntityLike

        The chat where the poll should be sent.

      • poll: SendPollParams

        The poll definition, see SendPollParams.

      • Optionalparams: Omit<SendFileInterface, "file" | "caption">

        Common send options (silent, schedule, replyTo, etc).

      Returns Promise<Message>

      await client.sendPoll(chat, {
      question: "Best transport?",
      answers: ["TCP full", "Abridged", "Obfuscated"],
      });
      await client.sendPoll(chat, {
      question: "2 + 2 = ?",
      answers: ["3", "4"],
      quiz: true,
      correctAnswers: 1,
      solution: "Basic arithmetic!",
      });
    • Sends a reaction to a message.

      Parameters

      • entity: EntityLike

        The chat/channel where the message is.

      • messageId: number

        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.

      Returns Promise<TypeUpdates>

      await client.sendReaction(chat, 123, [new Api.ReactionEmoji({ emoticon: "👍" })]);
      
    • Sends scheduled messages immediately, without waiting for their date.

      Parameters

      • entity: EntityLike

        The chat where the scheduled messages are.

      • ids: number | number[]

        The scheduled message ID(s) to send now.

      Returns Promise<Message[]>

      The sent messages.

    • Setter for parseMode. parseMode

      Parameters

      • mode: ParseInterface | "md" | "md2" | "markdown" | "markdownv2" | "html" | undefined

        can be md,markdown for Markdown or html for html. can also pass a custom mode. pass undefined for no parsing.

      Returns void

      // sets the mode to HTML
      client.setParseMode("html");
      await client.sendMessage("me",{message:"<u>This is an underline text</u>"});
      // disable formatting
      client.setParseMode(undefined);
      await client.sendMessage("me",{message:"<u> this will be sent as it is</u> ** with no formatting **});
    • Unpins a message in a chat.

      See also Message.unpin`.

      Parameters

      • entity: EntityLike

        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.

      Returns Promise<AffectedHistory>

      The pinned message. if message is undefined the return will be AffectedHistory

      The default behavior is to not notify members, unlike the official applications.

       const message = await client.sendMessage(chat, 'teleproto is awesome!');

      // unpin one message
      await client.unpinMessage(chat, message);

      // unpin all messages
      await client.unpinMessage(chat);
    • Unpins a message in a chat.

      See also Message.unpin`.

      Parameters

      • entity: EntityLike

        The chat where the message should be unpinned.

      • message: MessageIDLike

        The message or the message ID to unpin. If it's undefined, all messages will be unpinned instead.

      • OptionalpinMessageParams: UpdatePinMessageParams

        see UpdatePinMessageParams.

      Returns Promise<undefined>

      The pinned message. if message is undefined the return will be AffectedHistory

      The default behavior is to not notify members, unlike the official applications.

       const message = await client.sendMessage(chat, 'teleproto is awesome!');

      // unpin one message
      await client.unpinMessage(chat, message);

      // unpin all messages
      await client.unpinMessage(chat);
    • Votes in a poll.

      Parameters

      • entity: EntityLike

        The chat where the poll message is.

      • message: MessageIDLike

        The poll message or its ID.

      • options: number | Buffer<ArrayBufferLike> | Buffer<ArrayBufferLike>[] | number[]

        Answer index(es) (0-based), or raw option bytes.

      Returns Promise<TypeUpdates>

      await client.vote(chat, 123, 0);
      await client.vote(chat, 123, [0, 2]); // multiple-choice poll
    • Low-level method to download files from their input location. downloadMedia should generally be used over this.

      Parameters

      • inputLocation: TypeInputFileLocation

        The file location from which the file will be downloaded. See getInputLocation source for a complete list of supported types.

      • fileParams: DownloadFileParams = {}

        DownloadFileParams

      Returns Promise<string | Buffer<ArrayBufferLike> | undefined>

      a Buffer downloaded from the inputFile.

      const photo = message.photo;
      const buffer = await client.downloadFile(
      new Api.InputPhotoFileLocation({
      id: photo.id,
      accessHash: photo.accessHash,
      fileReference: photo.fileReference,
      thumbSize: size.type
      }),
      {
      dcId: photo.dcId,
      fileSize: "m",
      }
      );
    • Downloads the given media from a message or a media object.
      this will return an empty Buffer in case of wrong or empty media.

      Parameters

      Returns Promise<string | Buffer<ArrayBufferLike> | undefined>

      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.

      Parameters

      • entity: EntityLike

        where to download the photo from.

      • downloadProfilePhotoParams: string | DownloadProfilePhotoParams = ...

        DownloadProfilePhotoParams

      Returns Promise<string | Buffer<ArrayBufferLike> | undefined>

      buffer containing the profile photo. can be empty in case of no profile photo.

      // Download your own profile photo
      const buffer = await client.downloadProfilePhoto('me')
      console.log("Downloaded image is",buffer);
      // if you want to save it as a file you can use the fs module on node for that.
      import { promises as fs } from 'fs';
      await fs.writeFile("picture.jpg",buffer);
    • 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.

      Parameters

      • entity: EntityLike

        who will receive the file.

      • sendFileParams: SendFileInterface

        see SendFileInterface

      Returns Promise<Message>

      // 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.

      Parameters

      Returns Promise<InputFile | InputFileBig>

      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

      import { CustomFile } from "teleproto/client/uploads";
      const toUpload = new CustomFile("photo.jpg", fs.statSync("../photo.jpg").size, "../photo.jpg");
      const file = await client.uploadFile({
      file: toUpload,
      workers: 1,
      });
      await client.invoke(new Api.photos.UploadProfilePhoto({
      file: file,
      }));
    • Promotes, edits or demotes an admin (channels.editAdmin).

      Every unset right is revoked — pass an empty object to demote.

      Parameters

      Returns Promise<boolean | TypeUpdates>

      await client.editAdmin(chat, user, { deleteMessages: true, banUsers: true, rank: "mod" });
      await client.editAdmin(chat, user, {}); // demote
    • 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).

      Parameters

      Returns Promise<TypeUpdates>

      await client.editBanned(chat, user);                       // full ban
      await client.editBanned(chat, user, { sendMedia: true }); // mute media
      await client.editBanned(chat, user, {}); // unban
    • Edits the description of a chat, channel or supergroup (messages.editChatAbout).

      Parameters

      • entity: EntityLike

        The chat.

      • about: string

        The new description.

      Returns Promise<boolean>

    • Moves chats to a peer folder — 1 is the archive, 0 the main list (folders.editPeerFolders).

      Parameters

      • entity: EntityLike | EntityLike[]

        The chat(s) to move.

      • folderId: number

        The destination folder: 1 = archive, 0 = unarchive.

      Returns Promise<TypeUpdates>

      await client.editPeerFolders(chat, 1); // archive
      await client.editPeerFolders([chatA, chatB], 0); // unarchive
    • Gets a single participant of a channel or supergroup.

      Parameters

      • entity: EntityLike

        The channel/supergroup.

      • participant: EntityLike

        The participant to fetch.

      Returns Promise<Api.channels.ChannelParticipant>

      const result = await client.getParticipant(channel, "username");
      console.log(result.participant); // ChannelParticipant | ChannelParticipantAdmin | …
    • Iterates over the admin log (recent actions) of a channel/supergroup. Requires admin rights.

      Parameters

      • entity: EntityLike

        The channel/supergroup.

      • Optionalparams: AdminLogParams

        see AdminLogParams. Set filter fields to only receive those event types.

      Returns _AdminLogIter

      instances of Api.ChannelAdminLogEvent.

      for await (const event of client.iterAdminLog(channel, { ban: true, unban: true })) {
      console.log(event.action.className, event.userId.toString());
      }
    • 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.

      Parameters

      • entity: EntityLike

        The entity from which to retrieve the participants list.

      • params: IterParticipantsParams = {}

        IterParticipantsParams

      Returns _ParticipantsIter

      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);
      }
    • Kicks a user from a chat.

      Kicking yourself ('me') will result in leaving the chat.

      Parameters

      • entity: EntityLike
      • participant: EntityLike

      Returns Promise<
          TypeMessage
          | Map<number, Message>
          | (Message | undefined)[]
          | undefined,
      >

      Attempting to kick someone who was banned will remove their restrictions (and thus unbanning them), since kicking is just ban + unban.

      // Kick some user from some chat, and deleting the service message
      const msg = await client.kickParticipant(chat, user);
      await msg.delete();

      // Leaving chat
      await client.kickParticipant(chat, 'me');
    • 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.

      Parameters

      • entity: EntityLike

        The chat where the action should be shown.

      • Optionalaction:
            | "location"
            | "file"
            | "document"
            | "photo"
            | "typing"
            | "game"
            | "video"
            | "contact"
            | "record-audio"
            | "record-voice"
            | "record-round"
            | "record-video"
            | "audio"
            | "voice"
            | "song"
            | "round"
            | "cancel"
            | TypeSendMessageAction

        The action name or a raw Api.TypeSendMessageAction. Defaults to "typing". Use "cancel" to stop.

      • Optionalparams: { topMsgId?: number }
        • OptionaltopMsgId?: number

          The forum topic where the action should be shown.

      Returns Promise<boolean>

      await client.setTyping(chat);                  // typing…
      await client.setTyping(chat, "record-video"); // recording video…
      await client.setTyping(chat, "cancel"); // stop
    • Enables or changes the slow mode of a supergroup (channels.toggleSlowMode).

      Parameters

      • entity: EntityLike

        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.

      Returns Promise<TypeUpdates>

    • Gets info about a chat by its invite link WITHOUT joining — title, photo, participant count, and whether you are already a member (messages.checkChatInvite).

      Parameters

      • link: string

        The invite link (https://t.me/+hash) or the bare hash.

      Returns Promise<TypeChatInvite>

    • Deletes a previously revoked invite link (messages.deleteExportedChatInvite).

      Parameters

      • entity: EntityLike

        The chat the link belongs to.

      • link: string

        The revoked invite link to delete.

      Returns Promise<boolean>

    • Deletes all revoked invite links of an admin (messages.deleteRevokedExportedChatInvites).

      Parameters

      • entity: EntityLike

        The chat.

      • Optionaladmin: EntityLike

        The admin whose revoked links should be deleted. Defaults to yourself.

      Returns Promise<boolean>

    • Edits or revokes an invite link (messages.editExportedChatInvite).

      Parameters

      • entity: EntityLike

        The chat the link belongs to.

      • link: string

        The invite link to edit.

      • params: EditExportedChatInviteParams

        see EditExportedChatInviteParams. Pass { revoked: true } to revoke.

      Returns Promise<Api.messages.TypeExportedChatInvite>

    • Creates a new invite link for a chat (messages.exportChatInvite).

      Parameters

      • entity: EntityLike

        The chat.

      • Optionalparams: ExportChatInviteParams

        see ExportChatInviteParams.

      Returns Promise<Api.TypeExportedChatInvite>

      const invite = await client.exportChatInvite(chat, { usageLimit: 10, requestNeeded: true });
      if (invite instanceof Api.ChatInviteExported) console.log(invite.link);
    • Approves or declines ALL pending join requests of a chat (messages.hideAllChatJoinRequests).

      Parameters

      • entity: EntityLike

        The chat.

      • Optionalparams: { approved?: boolean; link?: string }

        approved: true approves all; link restricts to requests from one invite link.

      Returns Promise<TypeUpdates>

    • Approves or declines a pending join request (messages.hideChatJoinRequest).

      Parameters

      • entity: EntityLike

        The chat.

      • user: EntityLike

        The user whose join request should be handled.

      • Optionalparams: { approved?: boolean }

        { approved: true } approves; omitted or false declines.

      Returns Promise<TypeUpdates>

    • Iterates over the users that joined a chat via invite links, or over pending join requests with requested: true (messages.getChatInviteImporters).

      Parameters

      • entity: EntityLike

        The chat.

      • Optionalparams: ChatInviteImportersParams

        see ChatInviteImportersParams.

      Returns _ChatInviteImportersIter

      instances of Api.ChatInviteImporter.

      for await (const request of client.iterChatInviteImporters(chat, { requested: true })) {
      await client.hideChatJoinRequest(chat, request.userId, { approved: true });
      }
    • Iterates over the invite links of a chat (messages.getExportedChatInvites).

      Parameters

      • entity: EntityLike

        The chat.

      • Optionalparams: ExportedChatInvitesParams

        see ExportedChatInvitesParams.

      Returns _ExportedChatInvitesIter

      instances of Api.TypeExportedChatInvite.

    • Creates a topic in a forum (messages.createForumTopic).

      Parameters

      • entity: EntityLike

        The forum.

      • params: CreateForumTopicParams

        see CreateForumTopicParams.

      Returns Promise<TypeUpdates>

    • Edits a forum topic: title, icon, closed/hidden state (messages.editForumTopic).

      Parameters

      • entity: EntityLike

        The forum.

      • topicId: number

        The topic ID (its top message ID).

      • params: EditForumTopicParams

        see EditForumTopicParams.

      Returns Promise<TypeUpdates>

      await client.editForumTopic(forum, 123, { closed: true });
      
    • Gets the topics of a forum, with their last messages (messages.getForumTopics).

      Parameters

      • entity: EntityLike

        The forum.

      • Optionalparams: GetForumTopicsParams

        see GetForumTopicsParams.

      Returns Promise<ForumTopics>

    • Posts a story (stories.sendStory).

      Parameters

      • entity: EntityLike

        Where to post: "me" or a channel you manage.

      • params: SendStoryParams

        see SendStoryParams.

      Returns Promise<TypeUpdates>

      await client.sendStory("me", { media: "photo.jpg", caption: "hello" });
      
    • Reacts to a story (stories.sendReaction).

      Parameters

      • entity: EntityLike
      • storyId: number
      • 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 }

      Returns Promise<TypeUpdates>

    • Adds a user to your contact list (contacts.addContact).

      Parameters

      • entity: EntityLike

        The user to add.

      • params: AddContactParams

        see AddContactParams.

      Returns Promise<TypeUpdates>

    • Blocks a peer (contacts.block).

      Parameters

      • entity: EntityLike

        The peer to block.

      • Optionalparams: { myStoriesFrom?: boolean }
        • OptionalmyStoriesFrom?: boolean

          Only hide your stories from the peer instead of fully blocking.

      Returns Promise<boolean>

    • Imports phone-book contacts (contacts.importContacts).

      Parameters

      • contacts: ImportContactEntry[]

        The entries to import, see ImportContactEntry.

      Returns Promise<ImportedContacts>

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

      Parameters

      • Optionalhash: BigInteger

      Returns Promise<boolean>

    • Unblocks a peer (contacts.unblock).

      Parameters

      • entity: EntityLike

        The peer to unblock.

      • Optionalparams: { myStoriesFrom?: boolean }
        • OptionalmyStoriesFrom?: boolean

          Only unhide your stories instead of the full blocklist.

      Returns Promise<boolean>

    • Changes the notification settings of a peer — mute/unmute, sounds, previews (account.updateNotifySettings).

      Parameters

      Returns Promise<boolean>

      await client.updateNotifySettings(chat, { muteUntil: 2147483647 }); // mute forever
      
    • Updates your profile name and/or bio (account.updateProfile). Only the fields you set are changed.

      Parameters

      • params: UpdateProfileParams

        see UpdateProfileParams.

      Returns Promise<TypeUser>

      await client.updateProfile({ about: "using teleproto" });
      
    • Updates your online status (account.updateStatus).

      Parameters

      • Optionalonline: boolean

        true (the default) to appear online, false to go offline immediately.

      Returns Promise<boolean>

    • Uploads and sets a new profile photo or video (photos.uploadProfilePhoto).

      Parameters

      • params: UploadProfilePhotoParams

        see UploadProfilePhotoParams.

      Returns Promise<Api.photos.Photo>

      await client.uploadProfilePhoto({ file: "me.jpg" });
      
    • Same as iterDialogs but returns a TotalList instead of an iterator.

      Parameters

      Returns Promise<TotalList<Dialog>>

      // 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)

      Parameters

      Returns _DialogsIter

      instances of custom Dialog.

      // logs all dialog IDs and their title.
      for await (const dialog of client.iterDialogs({})){
      console.log(`${dialog.id}: ${dialog.title}`);
      }
    • Makes an inline query to the specified bot and gets the result list.
      This is equivalent to writing @pic something in clients

      Parameters

      • bot: EntityLike

        the bot entity to which the inline query should be made

      • query: string

        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.

      Returns Promise<InlineResults>

      a list of InlineResults

      // Makes the query to @pic
      const results = await client.inlineQuery("pic", "something");
      // clicks on the first result
      await results[0].click();
    • Registers a new event handler callback.

      The callback will be called when the specified event occurs.

      Parameters

      • callback: (event: NewMessageEvent) => void

        The callable function accepting one parameter to be used.
        Note the event type passed in the callback will change depending on the eventBuilder.

      • event: NewMessage

        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.

      Returns void

      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.

      Parameters

      • callback: (event: CallbackQueryEvent) => void

        The callable function accepting one parameter to be used.
        Note the event type passed in the callback will change depending on the eventBuilder.

      • event: CallbackQuery

        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.

      Returns void

      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.

      Parameters

      • callback: (event: AlbumEvent) => void

        The callable function accepting one parameter to be used.
        Note the event type passed in the callback will change depending on the eventBuilder.

      • event: Album

        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.

      Returns void

      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.

      Parameters

      • callback: (event: EditedMessageEvent) => void

        The callable function accepting one parameter to be used.
        Note the event type passed in the callback will change depending on the eventBuilder.

      • event: EditedMessage

        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.

      Returns void

      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.

      Parameters

      • callback: (event: DeletedMessageEvent) => void

        The callable function accepting one parameter to be used.
        Note the event type passed in the callback will change depending on the eventBuilder.

      • event: DeletedMessage

        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.

      Returns void

      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.

      Parameters

      • callback: (event: any) => void

        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.

      Returns void

      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({}));
    • Fetches and processes any updates that were missed while disconnected. Call this after reconnecting to ensure no updates are lost.

      Returns Promise<void>

      await client.connect();
      await client.catchUp(); // Fetch missed updates
    • Lists all registered event handlers.

      Returns [EventBuilder, CallableFunction][]

      pair of [eventBuilder,CallableFunction]

    • Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.

      Parameters

      Returns (f: (event: NewMessageEvent) => void) => void

      client.on(new NewMessage({ incoming: true }))(async (event) => {
      console.log(event.message.text);
      });
    • Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.

      Parameters

      Returns (f: (event: CallbackQueryEvent) => void) => void

      client.on(new NewMessage({ incoming: true }))(async (event) => {
      console.log(event.message.text);
      });
    • Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.

      Parameters

      Returns (f: (event: AlbumEvent) => void) => void

      client.on(new NewMessage({ incoming: true }))(async (event) => {
      console.log(event.message.text);
      });
    • Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.

      Parameters

      Returns (f: (event: EditedMessageEvent) => void) => void

      client.on(new NewMessage({ incoming: true }))(async (event) => {
      console.log(event.message.text);
      });
    • Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.

      Parameters

      Returns (f: (event: DeletedMessageEvent) => void) => void

      client.on(new NewMessage({ incoming: true }))(async (event) => {
      console.log(event.message.text);
      });
    • Decorator-style event handler registration. Returns a function that accepts a callback and registers it for the given event.

      Parameters

      • Optionalevent: EventBuilder

      Returns (f: (event: any) => void) => void

      client.on(new NewMessage({ incoming: true }))(async (event) => {
      console.log(event.message.text);
      });
    • Inverse operation of addEventHandler().

      Parameters

      • callback: CallableFunction

        the callback function to be removed.

      • event: EventBuilder

        the type of the event.

      Returns void

    • get updates(): ClientUpdates

      The update pipeline: middleware, typed subscriptions and live subscriptions to chats. See ClientUpdates.

      Returns ClientUpdates

      client.updates.on("newChannelMessage", (update) => console.log(update.message.id));
      client.updates.watch("obitoscasino", (update) => console.log(update.message.id));
    • Returns the DC IP address.
      This will do an API request to fill the cache if it's the first time it's called.

      Parameters

      • dcId: number

        The DC ID.

      • downloadDC: boolean = false

        whether to use -1 DCs or not TODO, hardcode IPs. (These only support downloading/uploading and not creating a new AUTH key)

      Returns Promise<{ id: number; ipAddress: string; port: number }>

    __version__: string = version

    The current teleproto version.

    _connectedDeferred: Deferred<void>
    _lastRequest?: number
    apiHash: string
    apiId: number
    • Clears your recent stickers (messages.clearRecentStickers).

      Parameters

      • Optionalparams: { attached?: boolean }

      Returns Promise<boolean>

    • Deletes stories (stories.deleteStories). Returns the IDs that were actually deleted.

      Parameters

      • entity: EntityLike
      • ids: number | number[]

      Returns Promise<number[]>

    • Edits a posted story (stories.editStory).

      Parameters

      • entity: EntityLike
      • storyId: number
      • params: EditStoryParams

      Returns Promise<TypeUpdates>

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

      Parameters

      • entity: EntityLike

        To which entity the message(s) will be forwarded.

      • forwardMessagesParams: ForwardMessagesParams

        see ForwardMessagesParams

      Returns Promise<Message[]>

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

      Parameters

      • entity: EntityLike

        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.

      Returns Promise<Entity>

      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.

      Parameters

      • entity: EntityLike[]

        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.

      Returns Promise<Entity[]>

      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 specific forum topics by their IDs (messages.getForumTopicsByID).

      Parameters

      • entity: EntityLike
      • topicIds: number | number[]

      Returns Promise<ForumTopics>

    • Gets the stories pinned on a peer's profile (stories.getPinnedStories).

      Parameters

      • entity: EntityLike
      • Optionalparams: GetStoriesPageParams

      Returns Promise<Stories>

    • Gets your story archive (stories.getStoriesArchive).

      Parameters

      • entity: EntityLike
      • Optionalparams: GetStoriesPageParams

      Returns Promise<Stories>

    • Gets the viewers of one of your stories (stories.getStoryViewsList).

      Parameters

      • entity: EntityLike
      • storyId: number
      • Optionalparams: GetStoryViewsListParams

      Returns Promise<StoryViewsList>

    • Increments the view counter of stories (stories.incrementStoryViews).

      Parameters

      • entity: EntityLike
      • ids: number | number[]

      Returns Promise<boolean>

    • Type Parameters

      Parameters

      • request: R
      • Optionalsender: MTProtoSender | SessionLease

      Returns Promise<R["__response"]>

    networkSocket: SocketFactory
    • set onError(handler: (error: Error) => Promise<void>): void

      Custom error handler for the client

      Parameters

      • handler: (error: Error) => Promise<void>

      Returns void

      client.onError = async (error)=>{
      console.log("error is",error)
      }
    • Marks a peer's stories as read up to maxId (stories.readStories).

      Parameters

      • entity: EntityLike
      • OptionalmaxId: number

      Returns Promise<number[]>

    • Reorders the pinned forum topics (messages.reorderPinnedForumTopics).

      Parameters

      • entity: EntityLike
      • order: number[]
      • Optionalparams: { force?: boolean }

      Returns Promise<TypeUpdates>

    session: S
    • Sets the account self-destruction period, in days (account.setAccountTTL).

      Parameters

      • days: number

      Returns Promise<boolean>

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

      Parameters

      Returns Promise<void>

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

      Parameters

      • entity: EntityLike
      • enabled: boolean
      • Optionaltabs: boolean

      Returns Promise<TypeUpdates>

    • Pins stories to the profile after expiration, or unpins them (stories.togglePinned).

      Parameters

      • entity: EntityLike
      • ids: number | number[]
      • Optionalpinned: boolean

      Returns Promise<number[]>

    • Toggles viewing a forum as a regular chat (channels.toggleViewForumAsMessages).

      Parameters

      • entity: EntityLike
      • enabled: boolean

      Returns Promise<TypeUpdates>

    • Uninstalls a sticker set (messages.uninstallStickerSet).

      Parameters

      • set: InputStickerSetLike

      Returns Promise<boolean>

    • Reorders your chat folders (messages.updateDialogFiltersOrder).

      Parameters

      • order: number[]

      Returns Promise<boolean>

    updateManager: UpdateManager

    Centralised pts/qts/seq tracker and gap recovery driver.

    • Pins or unpins a forum topic (messages.updatePinnedForumTopic).

      Parameters

      • entity: EntityLike
      • topicId: number
      • pinned: boolean

      Returns Promise<TypeUpdates>

    • Creates, updates or deletes a chat folder (messages.updateDialogFilter).

      Parameters

      • id: number

        The folder ID (2-255).

      • Optionalfilter: TypeDialogFilter

        The new folder definition, or omit to delete the folder.

      Returns Promise<boolean>

    • get api(): ApiFacade

      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.

      Returns ApiFacade

      const dialogs = await client.api.messages.getDialogs({ limit: 10 });
      const full = await client.api.users.getFullUser({ id: "me" });
    • 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.

      Parameters

      • entity: EntityLike

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

        • If the username or ID from the invite link is not found in the cache, it will be fetched. The same rules apply to phone numbers ('+34 123456789') from people in your contact list.
        • If an exact name is given, it must be in the cache too. This is not reliable as different people can share the same name and which entity is returned is arbitrary,
          and should be used only for quick tests.
        • If a positive integer ID is given, the entity will be searched in cached users, chats or channels, without making any call.
        • If a negative integer ID is given, the entity will be searched exactly as either a chat (prefixed with -) or as a channel (prefixed with -100).
        • If a Peer is given, it will be searched exactly in the cache as either a user, chat or channel.
        • If the given object can be turned into an input entity directly, said operation will be done.
          -If the entity can't be found, this will throw an error.

      Returns Promise<TypeInputPeer>

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

      Parameters

      • peer: EntityLike
      • addMark: boolean = true

        whether to return a bot api style id.

      Returns Promise<string>

      the ID of the entity.

      console.log(await client.getPeerId("me"));
      
    • 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.

      Type Parameters

      Parameters

      • request: R

        The request to send. this should be of type request.

      • OptionaldcId: number

        Optional dc id to use when sending.

      Returns Promise<R["__response"]>

      The response from Telegram.

      //
      const result = await client.invoke(new Api.account.CheckUsername({
      username: 'some string here'
      }));
      console.log("does this username exist?",result);
    • Return true if the signed-in user is a bot, false otherwise.

      Returns Promise<boolean | undefined>

      if (await client.isBot()){
      console.log("I am a bot. PI is 3.14159265359);
      } else {
      console.log("I am a human. Pies are delicious);
      }
    • Returns true if the user is authorized (logged in).

      Returns Promise<boolean>

      if (await client.isUserAuthorized()){
      console.log("I am authorized. I can call functions and use requests");
      }else{
      console.log("I am not logged in. I need to sign in first before being able to call methods");
      }