Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TelegramClient

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 "telegram";

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.

Hierarchy

Index

Constructors

Methods

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

    example
    // 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 "telegram";
    import { StringSession } from "telegram/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.

    Parameters

    Returns Promise<void>

    nothing

  • checkAuthorization(): Promise<boolean>
  • Checks whether the current client is authorized or not. (logged in as a user)

    example
    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");
    }

    Returns Promise<boolean>

    boolean (true of authorized else false)

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

    example
    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),
    })
    }

    Parameters

    Returns Promise<TypeUser>

  • logs the user using a QR code to be scanned.
    this function generates the QR code that needs to be scanned by mobile.

    example

    '''ts await client.connect(); 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"; } } ); console.log("user is", user);

    '''

    Parameters

    Returns Promise<TypeUser>

  • sendCode(apiCredentials: ApiCredentials, phoneNumber: string, forceSMS?: boolean): Promise<{ phoneCodeHash: string; isCodeViaApp: boolean }>
  • Sends a telegram authentication code to the phone number.

    example
    await client.connect();
    const {phoneCodeHash,isCodeViaApp} = await client.sendCode({
    apiId:1234,
    apiHash:"123456789abcfghj",
    },"+123456798"});

    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

    Returns Promise<{ phoneCodeHash: string; isCodeViaApp: boolean }>

    the phone code hash and whether it was sent via app

  • Used to sign in as a bot.

    example
    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);

    Parameters

    Returns Promise<TypeUser>

    instance User of the logged in bot.

  • updateTwoFaSettings(__namedParameters: TwoFaParams): Promise<void>
  • 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.

    throws

    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

    Parameters

    Returns Promise<void>

    Promise

  • Makes an inline query to the specified bot and gets the result list.
    This is equivalent to writing @pic something in clients

    example
    // Makes the query to @pic
    const results = await client.inlineQuery("pic", "something");
    // clicks on the first result
    await results[0].click();

    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

    • Optional entity: 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.

    • Optional offset: string

      String offset of the results to be returned. can be empty

    • Optional geoPoint: 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

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

    example
    import {Button} from "telegram/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!")],
    }

    Parameters

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

      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 undefined | TypeReplyMarkup

  • Low-level method to download files from their input location. downloadMedia should generally be used over this.

    example
    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",
    }
    );

    Parameters

    Returns Promise<undefined | string | Buffer>

    a Buffer downloaded from the inputFile.

  • Iterates over a file download, yielding chunks of the file. This method can be used to stream files in a more convenient way, since it offers more control (pausing, resuming, etc.)

    example
    const photo = message.photo;
    for await (const chunk of client.iterDownload({
    file: new Api.InputPhotoFileLocation({
    id: photo.id,
    accessHash: photo.accessHash,
    fileReference: photo.fileReference,
    thumbSize: size.type
    }),
    offset: start,
    limit: end,
    requestSize:2048*1024
    )){
    console.log("Downloaded chunk of size",chunk.length);
    };

    Parameters

    Returns DirectDownloadIter

    a Buffer downloaded from the inputFile.

  • Downloads the profile photo from the given user,chat or channel.
    This method will return an empty buffer in case of no profile photo.

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

    Parameters

    Returns Promise<undefined | string | Buffer>

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

  • Downloads the given media from a message or a media object.
    this will return an empty Buffer in case of wrong or empty media.

    example
    const buffer = await client.downloadMedia(message, {})
    // to save it to a file later on using fs.
    import { promises as fs } from 'fs';
    await fs.writeFile("file",buffer);
    // to use a progress callback you can pass it like so.
    const buffer = await client.downloadMedia(message, {
    progressCallback : console.log
    })

    Parameters

    Returns Promise<undefined | string | Buffer>

    a buffer containing the downloaded data if outputFile is undefined else nothing.

  • setParseMode(mode: undefined | ParseInterface | "md" | "md2" | "markdown" | "markdownv2" | "html"): void
  • Setter for parseMode. parseMode

    example

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

    Parameters

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

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

    Returns void

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

    remarks

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

    yield

    Instances of custom Message

    example
    // 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 "telegram";
    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)
    }

    Parameters

    • entity: undefined | EntityLike

      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> = {}

    Returns _IDsIter | _MessagesIter

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

    example
    // 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 "telegram";
    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];

    Parameters

    Returns Promise<TotalList<Message>>

    TotalList of messages.

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

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

    Parameters

    Returns Promise<Message>

    The sent custom Message.

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

    example
    // 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});

    Parameters

    Returns Promise<Message[]>

    The list of forwarded Message, Note.
    if some messages failed to be forwarded the returned list will have them as undefined.

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

    throws

    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.

    example
    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!"}

    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

    Returns Promise<Message>

    The edited Message.

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

    See also Message.delete`.

    remarks

    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.

    example
    await client.deleteMessages(chat, messages);

    await client.deleteMessages(chat, messages, {revoke:false});

    Parameters

    • entity: undefined | EntityLike

      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: Object

      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.

  • 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 {@link Message.markRead}`.

    remarks

    If neither message nor maximum ID are provided, all messages will be marked as read by assuming that max_id = 0.

    example
    // using a Message object
    const message = await client.sendMessage(chat, 'GramJS 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)

    Parameters

    Returns Promise<boolean>

    boolean

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

    yield

    instances of custom Dialog.

    example
    // logs all dialog IDs and their title.
    for await (const dialog of client.iterDialogs({})){
    console.log(`${dialog.id}: ${dialog.title}`);
    }

    Parameters

    Returns _DialogsIter

  • Same as iterDialogs but returns a TotalList instead of an iterator.

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

    Parameters

    Returns Promise<TotalList<custom.Dialog>>

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

    remarks

    The filter ChannelParticipantsBanned will return restricted users. If you want banned users you should use ChannelParticipantsKicked instead.

    yield

    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.

    example
    // 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 "telegram";

    for await (const user of client.iterParticipants(chat, {filter: Api.ChannelParticipantsAdmins})){
    console.log("admin first name is ",user.firstName);
    }

    Parameters

    Returns _ParticipantsIter

  • on(event: any): ((f: ((event: any) => void)) => ((event: any) => void))
  • TODO

    Parameters

    • event: any

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

      • (f: ((event: any) => void)): ((event: any) => void)
      • Parameters

        • f: ((event: any) => void)
            • (event: any): void
            • Parameters

              • event: any

              Returns void

        Returns ((event: any) => void)

          • (event: any): void
          • Parameters

            • event: any

            Returns void

  • removeEventHandler(callback: CallableFunction, event: EventBuilder): void
  • Uploads a file to Telegram's servers, without sending it.

    remarks

    generally it's better to use 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

    example
    import { CustomFile } from "telegram/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,
    }));

    Parameters

    Returns Promise<InputFile | InputFileBig>

    Api.InputFileBig if the file size is larger than 10mb otherwise Api.InputFile

  • Sends message with the given file to the specified entity. This uses uploadFile internally so if you want more control over uploads you can use that.

    example
    // 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:''
    }))

    Parameters

    Returns Promise<Message>

  • invoke<R>(request: R, dcId?: number): Promise<R["__response"]>
  • 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.

    example
    //
    const result = await client.invoke(new Api.account.CheckUsername({
    username: 'some string here'
    }));
    console.log("does this username exist?",result);

    Type Parameters

    Parameters

    • request: R

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

    • Optional dcId: number

      Optional dc id to use when sending.

    Returns Promise<R["__response"]>

    The response from Telegram.

  • invokeWithSender<R>(request: R, sender?: MTProtoSender): Promise<R["__response"]>
  • isBot(): Promise<undefined | boolean>
  • Return true if the signed-in user is a bot, false otherwise.

    example
    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 Promise<undefined | boolean>

  • isUserAuthorized(): Promise<boolean>
  • Returns true if the user is authorized (logged in).

    example

    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"); }

    Returns Promise<boolean>

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

    remarks

    Telegram does not allow to get user profile by integer id if current client had never "saw" it.

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

    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.

  • Parameters

    Returns Promise<Entity[]>

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

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

    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>

  • getPeerId(peer: EntityLike, addMark?: boolean): Promise<string>
  • 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.

    example
    console.log(await client.getPeerId("me"));
    

    Parameters

    • peer: EntityLike
    • addMark: boolean = true

      whether to return a bot api style id.

    Returns Promise<string>

    the ID of the entity.

  • connect(): Promise<boolean>
  • getDC(dcId: number, downloadDC?: boolean, web?: boolean): Promise<{ id: number; ipAddress: string; port: number }>
  • Returns the DC ip in case of node or the DC web address in case of browser.
    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

    • web: boolean = false

      if true this will get the web DCs. TODO, hardcode IPs. (These only support downloading/uploading and not creating a new AUTH key)

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

  • _initSession(): Promise<void>
  • disconnect(): Promise<void>
  • _disconnect(): Promise<void>
  • destroy(): Promise<void>

Accessors

  • This property is the default parse mode used when sending messages. Defaults to {@link 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.
    example
    // gets the current parse mode.
    console.log("parse mode is :", client.parseMode)

    Returns undefined | ParseInterface

  • get events(): any
  • get floodSleepThreshold(): number
  • set floodSleepThreshold(value: number): void
  • set maxConcurrentDownloads(value: number): void
  • get connected(): undefined | boolean
  • get disconnected(): boolean

Properties

__version__: string = version

The current gramJS version.

session: Session
apiHash: string
apiId: number
_connectedDeferred: default<void>

Generated using TypeDoc