### Basic Usage of tdl-install-types Source: https://github.com/eilvelia/tdl/blob/main/packages/tdl-install-types/README.md Launches the utility to generate types, attempting to use a prebuilt TDLib version. This is the simplest way to get started. ```bash npx tdl-install-types ``` ```bash npx tdl-install-types prebuilt-tdlib ``` -------------------------------- ### Install Prebuilt TDLib Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Use this command to install the prebuilt TDLib if you encounter 'Library Not Found' errors. ```bash npm install prebuilt-tdlib ``` -------------------------------- ### Minimal TDLib Client Setup and Usage Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/core-functions.md Demonstrates the minimal setup for creating a TDLib client, logging in, invoking a method, and closing the client. Ensure 'apiId' and 'apiHash' are replaced with actual values. ```javascript const tdl = require('tdl') const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) client.on('error', console.error) await client.login() const me = await client.invoke({ _: 'getMe' }) console.log('Logged in as:', me.first_name) await client.close() ``` -------------------------------- ### Install tdl-install-types Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Install the necessary packages as development dependencies for your project. ```bash npm install prebuilt-tdlib tdl-install-types --save-dev ``` -------------------------------- ### Install and Generate Types for Latest prebuilt-tdlib Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Installs the prebuilt-tdlib package and then generates `tdlib-types.d.ts` in the current directory. ```bash npm install prebuilt-tdlib npx tdl-install-types ``` -------------------------------- ### Install tdl and prebuilt-tdlib Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md Install the tdl library and the prebuilt-tdlib package using npm. This is the first step to using tdl in your Node.js project. ```bash npm install tdl prebuilt-tdlib ``` -------------------------------- ### Minimal tdl Client Example Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md A basic example demonstrating how to configure tdl with prebuilt TDLib, create a client, log in, invoke a method, and close the client. Ensure you have your API ID and API Hash. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') tdl.configure({ tdjson: getTdjson() }) const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) client.on('error', console.error) await client.login() const me = await client.invoke({ _: 'getMe' }) console.log('Hello,', me.first_name) await client.close() ``` -------------------------------- ### Install prebuilt-tdlib Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Installs the 'tdl' and 'prebuilt-tdlib' npm packages. For specific TDLib versions, append '@td-x.y.z' to the package name. ```bash npm install tdl prebuilt-tdlib ``` ```bash npm install prebuilt-tdlib@td-1.8.60 ``` -------------------------------- ### Install tdl-install-types Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Install the tdl-install-types package globally using npm or use it directly with npx. ```bash npm install tdl-install-types ``` -------------------------------- ### Client Setup with Custom Directories Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Configures the client to use specific directories for the database and downloaded files. These directories will be created if they do not exist. ```javascript // With custom directories const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', databaseDirectory: './my_database', filesDirectory: './my_files' }) ``` -------------------------------- ### Minimal Client Setup Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Creates a TDLib client with only the mandatory API ID and API hash. This is the most basic configuration. ```javascript // Minimal setup const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) ``` -------------------------------- ### TypeScript Usage Example Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Example demonstrating how to import and use the generated TDLib types in a TypeScript project. ```typescript import type * as Td from 'tdlib-types' const me: Td.user = await client.invoke({ _: 'getMe' }) const chats: Td.chats = await client.invoke({ _: 'getChats', chat_list: { _: 'chatListMain' }, limit: 10 }) ``` -------------------------------- ### Full User Client Setup with TDLib Parameters Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Configures a TDLib client for a full user application with extensive caching and storage optimization enabled. This setup is suitable for desktop or mobile clients requiring fast access to data. ```javascript const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', tdlibParameters: { use_message_database: true, use_chat_info_database: true, use_user_database: true, use_file_database: true, enable_storage_optimizer: true, system_language_code: 'en', application_version: '1.0.0', device_model: 'Desktop App' } }) ``` -------------------------------- ### Install Latest TDLib Version Source: https://github.com/eilvelia/tdl/blob/main/packages/prebuilt-tdlib/README.md Installs the latest supported TDLib version from the prebuilt-tdlib package. Use this for general use cases. ```bash $ npm install prebuilt-tdlib ``` -------------------------------- ### Configure TDLib with System Installation Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/core-functions.md Configures the tdl library to use a TDLib installation found in the system's library directory. This is useful when TDLib is installed globally. ```javascript const tdl = require('tdl') tdl.configure({ libdir: '/usr/local/lib' }) const client = tdl.createClient({ apiId: 2222, apiHash: '...' }) ``` -------------------------------- ### Get TDLib Path and Configure tdl Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Retrieves the path to the pre-built tdjson library for the current platform and configures the tdl client. Ensure `prebuilt-tdlib` is installed alongside `tdl`. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') // Get path and configure tdl const tdjsonPath = getTdjson() console.log('TDLib path:', tdjsonPath) tdl.configure({ tdjson: tdjsonPath }) const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) ``` -------------------------------- ### Login with Custom Prompts Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of authenticating using custom functions to provide phone number, auth code, password, and name. ```javascript await client.login({ getPhoneNumber: async (retry) => '+1234567890', getAuthCode: async (retry) => '12345', getPassword: async (hint, retry) => 'mypassword', getName: async () => ({ firstName: 'John', lastName: 'Doe' }) }) ``` -------------------------------- ### Invoke: Get Current User Info Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of using the invoke method to retrieve information about the current user. ```javascript // Get current user info const me = await client.invoke({ _: 'getMe' }) ``` -------------------------------- ### Version-Specific TDLib Installation Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Specifies the tdl and prebuilt-tdlib versions in package.json for consistent installation. Then, it shows how to retrieve and log TDLib version information and its path. ```json { "dependencies": { "tdl": "^8.0.0", "prebuilt-tdlib": "0.1008061.0" } } ``` ```javascript const { getTdjson, getTdlibInfo } = require('prebuilt-tdlib') const info = getTdlibInfo() console.log(`Using TDLib ${info.version}`) const path = getTdjson() console.log(`Library: ${path}`) ``` -------------------------------- ### Login as Bot with Token String Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of authenticating a bot using a direct bot token string. ```javascript await client.loginAsBot('123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11') ``` -------------------------------- ### Install Specific TDLib Version using Dist Tags Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Installs a specific TDLib version using the provided dist tags. These tags are convenient shortcuts for specific TDLib releases. ```bash npm install prebuilt-tdlib@td-1.8.61 ``` ```bash npm install prebuilt-tdlib@td-1.8.50 ``` -------------------------------- ### Lean Bot Setup with TDLib Parameters Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Configures a TDLib client for a bot with minimal caching enabled. Use this for bots where message history caching is not required. ```javascript const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', tdlibParameters: { use_message_database: false, use_secret_chats: false, device_model: 'My Bot 1.0' } }) ``` -------------------------------- ### Login with Default Console Prompts Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of authenticating with default terminal prompts for phone number, auth code, and password. ```javascript await client.login() ``` -------------------------------- ### Install TypeScript Type Definitions Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md Install the necessary package to generate TypeScript type definitions for TDL. This is recommended for improved type safety in your projects. ```bash npm install tdl-install-types npx tdl-install-types ``` -------------------------------- ### Get Version as String Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Returns the version string that was used to initialize the Version object. Useful for logging or display purposes. ```javascript const v = new Version('1.8.61') console.log(v.toString()) // "1.8.61" ``` -------------------------------- ### Print Tool Version Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Use the `-v` or `--version` flags to display the currently installed version of the tdl-install-types tool. ```bash npx tdl-install-types --version ``` -------------------------------- ### Client Setup with Custom TDLib Parameters Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Allows overriding default TDLib parameters to customize application behavior, such as language, version, and device information. ```javascript // Custom TDLib parameters const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', tdlibParameters: { system_language_code: 'de', application_version: '2.0', device_model: 'My Bot v1', system_version: 'Linux' } }) ``` -------------------------------- ### Flow Types Example Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Example of generated Flow type definitions for TDLib, including interfaces for `Invoke`. ```javascript // @flow // Types for TDLib v1.8.61 (0ada45c3...) // Generated using tdl-install-types v0.3.1 export interface Invoke { (request: Td$getMe): Promise; (request: Td$getChats): Promise; // ... } // ... type definitions for Flow ``` -------------------------------- ### Login as Bot with Token Function Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of authenticating a bot using a function that returns the bot token, useful for environment variables. ```javascript await client.loginAsBot(() => process.env.BOT_TOKEN) ``` -------------------------------- ### Install Specific TDLib Version Source: https://github.com/eilvelia/tdl/blob/main/packages/prebuilt-tdlib/README.md Installs a specific TDLib version using dist-tags. This is useful for maintaining compatibility with older TDLib versions. ```bash $ npm install prebuilt-tdlib@td-1.8.50 ``` -------------------------------- ### Install Node.js from Source with Shared OpenSSL Source: https://github.com/eilvelia/tdl/blob/main/README.md This command uses nvm to install Node.js version 18 from source, linking it dynamically against the system's OpenSSL. This can resolve OpenSSL symbol conflicts by ensuring only one instance of OpenSSL is present. ```console $ nvm install -s 18 --shared-openssl --shared-openssl-includes=/usr/include/ --shared-openssl-libpath=/usr/lib/x86_64-linux-gnu/ ``` -------------------------------- ### TDL Install Types CLI Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md Command-line interface for generating TypeScript types for TDLib. ```APIDOC ## TDL Install Types CLI ### `npx tdl-install-types` - **Purpose**: Generate TypeScript types for TDLib. ### `npx tdl-install-types [target]` - **Purpose**: Generate types from library, schema, or git ref. ``` -------------------------------- ### Client Setup Using Test Servers Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Directs the client to use Telegram's test data centers instead of the production ones. This is useful for development and testing purposes. ```javascript // Using test servers const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', useTestDc: true }) ``` -------------------------------- ### Custom Login Prompts Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/examples.md Implement programmatic credential handling for login instead of relying on console prompts. This example uses hardcoded values for demonstration purposes and should not be used in production. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') async function main() { tdl.configure({ tdjson: getTdjson() }) const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) client.on('error', console.error) // Custom login with hardcoded values (for testing only!) await client.login({ type: 'user', getPhoneNumber: async (retry) => { if (retry) throw new Error('Invalid phone number') return '+1234567890' }, getAuthCode: async (retry) => { if (retry) throw new Error('Invalid code') // In production, fetch from API, read from file, etc. return '12345' }, getPassword: async (hint, retry) => { if (retry) throw new Error('Invalid password') return 'my-2fa-password' } }) console.log('Logged in!') await client.close() } main().catch(console.error) ``` -------------------------------- ### Client Setup with Database Encryption Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Enables database encryption by providing a secret key. The key must be at least 32 characters long for effective security. ```javascript // With encryption const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', databaseEncryptionKey: 'my-secret-key-32-chars-minimum!' }) ``` -------------------------------- ### Using TDLib Types with TypeScript Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md This example demonstrates how to import and use TDLib types in a TypeScript project when using `prebuilt-tdlib`. It shows importing the `Td` type and using it for a `getMe` invocation. ```typescript import type * as Td from 'tdlib-types' const me: Td.user = await client.invoke({ _: 'getMe' }) ``` -------------------------------- ### Handle Authorization State for Bare Client Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/core-functions.md Example of handling the `updateAuthorizationState` for a bare client, specifically when `authorizationStateWaitTdlibParameters` is received, to send the TDLib parameters. ```javascript const client = tdl.createBareClient() client.on('update', async (update) => { if (update._ === 'updateAuthorizationState' && update.authorization_state._ === 'authorizationStateWaitTdlibParameters') { await client.invoke({ _: 'setTdlibParameters', parameters: { ... } }) } }) ``` -------------------------------- ### List Available TDLib Versions Source: https://github.com/eilvelia/tdl/blob/main/packages/prebuilt-tdlib/README.md Retrieves a list of all available TDLib versions published as dist-tags for the prebuilt-tdlib package. This helps in selecting a specific version for installation. ```bash $ npm info prebuilt-tdlib dist-tags --json | jq 'to_entries | sort_by(.value) | .[].key | select(startswith("td-"))' ``` -------------------------------- ### Generate Types for prebuilt-tdlib Package Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Use the special 'prebuilt-tdlib' target to generate types for an installed prebuilt-tdlib package. This is also the default target if no target is specified. ```bash npx tdl-install-types prebuilt-tdlib ``` ```bash npx tdl-install-types # Defaults to prebuilt-tdlib if no target specified ``` -------------------------------- ### Configure tdl with Pre-built TDLib Source: https://github.com/eilvelia/tdl/blob/main/packages/prebuilt-tdlib/README.md Configures the tdl library to use the pre-built TDLib shared library obtained from prebuilt-tdlib. This simplifies the setup process for tdl. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') tdl.configure({ tdjson: getTdjson() }) ``` -------------------------------- ### Invoke: Get Chats Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of using the invoke method to retrieve a list of chats with a specified limit. ```javascript // Get chats const chats = await client.invoke({ _: 'getChats', chat_list: { _: 'chatListMain' }, limit: 10 }) ``` -------------------------------- ### Invoke TDLib Method: Get Chats Source: https://github.com/eilvelia/tdl/blob/main/README.md Invokes a TDLib method to retrieve a list of chats. This example fetches up to 4000 chats from the main chat list. The promise rejects with a `TDLibError` if the request fails. ```javascript const chats = await client.invoke({ _: 'getChats', chat_list: { _: 'chatListMain' }, limit: 4000 }) ``` -------------------------------- ### TypeScript with Type Definitions Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/examples.md Demonstrates how to use TDL with TypeScript, leveraging generated type definitions for better code completion and type safety. Ensure 'tdlib-types' is installed for full type support. ```typescript import * as tdl from 'tdl' import type * as Td from 'tdlib-types' import { getTdjson } from 'prebuilt-tdlib' async function main(): Promise { tdl.configure({ tdjson: getTdjson() }) const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) client.on('error', (err: Error) => { console.error('Client error:', err) }) await client.login() const me: Td.user = await client.invoke({ _: 'getMe' }) console.log(`Logged in as: ${me.first_name}`) const chats: Td.chats = await client.invoke({ _: 'getChats', chat_list: { _: 'chatListMain' }, limit: 10 }) console.log(`Got ${chats.chat_ids.length} chats`) for await (const update of client.iterUpdates()) { if (update._ === 'updateAuthorizationState') { const state: Td.AuthorizationState = update.authorization_state if (state._ === 'authorizationStateClosed') { break } } } await client.close() } main().catch(console.error) ``` -------------------------------- ### Client Setup to Skip Old Updates Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md When enabled, this option prevents the client from emitting updates that occurred while the connection state was `connectionStateUpdating`. This is useful for avoiding background synchronization noise. ```javascript // Skip background updates const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', skipOldUpdates: true }) ``` -------------------------------- ### Print Help Message Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Use the `-h` or `--help` flags to display the help message, which lists all available command-line options and their usage. ```bash npx tdl-install-types --help ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md The basic command structure for using the tdl-install-types CLI tool. ```bash npx tdl-install-types [] [] ``` -------------------------------- ### TDLib Version Check Example Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Demonstrates how the Version class is used internally within tdl to conditionally execute code based on the TDLib version. This allows for handling version-specific API changes or behaviors. ```javascript // From client.ts const TDLIB_1_8_6 = new Version('1.8.6') const TDLIB_DEFAULT = new Version('1.8.61') // ... if (this._version.lt(TDLIB_1_8_6)) { // Older TDLib behavior } else { // Newer TDLib behavior } ``` -------------------------------- ### List Available prebuilt-tdlib Versions Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Lists all available versions of the 'prebuilt-tdlib' package in JSON format, sorted by version number in descending order. Requires 'jq' for parsing. ```bash npm info prebuilt-tdlib dist-tags --json | jq 'to_entries | sort_by(.value) | reverse | .[].key' ``` -------------------------------- ### Create TDLib Client Instance Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Instantiate a TDLib client. Use `createClient` for a standard client with automatic initialization, or `createBareClient` for manual control. ```javascript const client = tdl.createClient({ // client options }); ``` ```javascript const client = tdl.createBareClient(); ``` -------------------------------- ### TypeScript Declarations Example Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Example of generated TypeScript type declarations for TDLib, including interfaces for `Invoke`, `Execute`, and `Update`. ```typescript // Types for TDLib v1.8.61 (0ada45c3...) // Generated using tdl-install-types v0.3.1 export interface Invoke { (request: getMe): Promise (request: getChats): Promise // ... hundreds of method overloads } export interface Execute { (request: getTextEntities): textEntities // ... synchronous methods } export interface Update { // Discriminated union of all update types _: 'updateAuthorizationState' | 'updateConnectionState' | ... // ... fields per type } // ... structures, enums, etc. ``` -------------------------------- ### Configure and Create TDL Client Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Sets up the TDLib path and creates a new TDL client instance. Requires API ID and Hash. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') tdl.configure({ tdjson: getTdjson() }) const client = tdl.createClient({ apiId: 2222, apiHash: '...' }) client.on('error', console.error) await client.login() ``` -------------------------------- ### Handling Missing Prebuilt TDLib Libraries Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Attempts to load the prebuilt TDLib. If it fails, it falls back to using a system-installed TDLib, logging a warning. ```javascript const tdl = require('tdl') let tdjsonPath try { const { getTdjson } = require('prebuilt-tdlib') tdjsonPath = getTdjson() } catch (err) { // Fallback to system library console.warn('prebuilt-tdlib unavailable, using system TDLib') tdjsonPath = 'libtdjson.so' // or 'libtdjson.dylib' on macOS, etc. } tdl.configure({ tdjson: tdjsonPath }) ``` -------------------------------- ### client.login(details) Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Initiates the login process by accepting `LoginDetails` which can be a `Partial` object, a `LoginBot` object, or a function that returns such an object. This allows for customization of authentication prompts. ```APIDOC ## client.login(details) ### Description Initiates the login process by accepting `LoginDetails` which can be a `Partial` object, a `LoginBot` object, or a function that returns such an object. This allows for customization of authentication prompts. ### Method ``` client.login(details: LoginDetails | (() => LoginDetails)) ``` ### Parameters #### Request Body - **details** (LoginDetails | (() => LoginDetails)) - Required - An object or a function returning an object that specifies how to handle authentication steps. `LoginDetails` can be one of the following: - **LoginUser**: An object with optional fields for user authentication. - **type** (`'user' | 'bot'`) - Optional - Defaults to `'user'` unless all fields are for bot login. Specifies the authentication type. - **getPhoneNumber** (Function) - Optional - A function that returns the phone number. Called on `authorizationStateWaitPhoneNumber`. Receives `retry=true` on invalid input. Defaults to console prompt. - **getEmailAddress** (Function) - Optional - A function that returns the email address. TDLib v1.8.6+ only. Called on `authorizationStateWaitEmailAddress`. Defaults to console prompt. - **getEmailCode** (Function) - Optional - A function that returns the email verification code. TDLib v1.8.6+ only. Called on `authorizationStateWaitEmailCode`. Defaults to console prompt. - **confirmOnAnotherDevice** (Function) - Optional - A function called on `authorizationStateWaitOtherDeviceConfirmation`. Receives a confirmation link and should print it to the user. This function is callback-only. - **getAuthCode** (Function) - Optional - A function that returns the 2FA code. Called on `authorizationStateWaitCode`. Receives `retry=true` on invalid input. Defaults to console prompt. - **getPassword** (Function) - Optional - A function that returns the 2FA password. Called on `authorizationStateWaitPassword`. Receives `passwordHint` and `retry=true` on invalid input. Defaults to console prompt. - **getName** (Function) - Optional - A function that returns `{ firstName: string, lastName?: string }` for new user registration. Called on `authorizationStateWaitRegistration`. Defaults to console prompts. - **LoginBot**: An object for bot authentication. - **type** (`'bot'`) - Required - Specifies the authentication type as `'bot'`. - **getToken** (Function) - Optional - A function that returns the bot token. Called on `authorizationStateWaitPhoneNumber` when `type='bot'`. Receives `retry=true` on invalid token. Defaults to console prompt. ### Rules - All fields within `LoginUser` are optional; missing fields will use default console prompts. - `getPhoneNumber`, `getAuthCode`, and `getToken` accept a `retry` parameter. Re-throwing an error within these functions signals invalid input. - `confirmOnAnotherDevice` is a callback-only function and does not return a value. - The provided functions can be asynchronous and return Promises. ### Request Example ```javascript // Default console prompts await client.login() // User with custom prompts await client.login({ getPhoneNumber: async (retry) => { if (retry) throw new Error('Invalid phone') return '+1234567890' }, getAuthCode: async () => '12345', getPassword: async (hint, retry) => 'mypassword' }) // Bot login await client.login({ type: 'bot', getToken: async () => process.env.BOT_TOKEN }) // Function form (lazy evaluation) await client.login(() => ({ getPhoneNumber: async () => await readPhoneFromFile(), getAuthCode: async () => await askUser('Enter code:') })) ``` ``` -------------------------------- ### prebuilt-tdlib Utilities Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Utilities for managing the TDLib binary. ```APIDOC ## getTdjson(options) ### Description Get the path to the tdjson library. ### Parameters #### Path Parameters - **options** (object) - Optional - Options for getting the tdjson path. ### Method `getTdjson` ``` ```APIDOC ## getTdlibInfo() ### Description Get TDLib version and commit information. ### Method `getTdlibInfo` ``` -------------------------------- ### Initialize and Use TDL Client Source: https://github.com/eilvelia/tdl/blob/main/README.md Demonstrates how to import, configure, and use the TDL client for interacting with Telegram. Includes event handling for errors and updates, logging in, invoking TDLib methods like getMe and getChats, and closing the client. ```javascript // Import using CommonJS: const tdl = require('tdl') // Configure tdl to use the tdjson shared library from the prebuilt-tdlib // package (should be installed separately) const { getTdjson } = require('prebuilt-tdlib') tdl.configure({ tdjson: getTdjson() }) // Instead of using the aforementioned prebuilt-tdlib, you can configure // tdl to load libtdjson from specified filename, for example: // tdl.configure({ tdjson: '/usr/local/lib/libtdjson.dylib' }) // With no configuration, tdl loads libtdjson from the system search paths. // The library directory can be set separate from the library name, // example to search for libtdjson in the directory of the current script: // tdl.configure({ libdir: __dirname }) // Create a client. It is mandatory to pass apiId and apiHash, these can be // obtained at https://my.telegram.org/ const client = tdl.createClient({ apiId: 2222, // Replace with your api_id apiHash: '0123456789abcdef0123456789abcdef' // Replace with your api_hash }) client.on('error', console.error) // Aside of sending responses to your requests, TDLib pushes to you // events called "updates", which can be received as follows: client.on('update', update => { console.log('Received update:', update) }) async function main () { // Log in to a Telegram account. By default, with no arguments, this function will // ask for phone number etc. in the console. Instead of logging in as a user, // it's also possible to log in as a bot using `client.loginAsBot('')`. await client.login() // Call a TDLib method. The information regarding TDLib method list and // documentation is below this code block. const me = await client.invoke({ _: 'getMe' }) console.log('My user:', me) // Invoke some other TDLib method. const chats = await client.invoke({ _: 'getChats', chat_list: { _: 'chatListMain' }, limit: 10 }) console.log('A part of my chat list:', chats) // Close the instance so that TDLib finishes gracefully and the JS runtime can // exit the process. await client.close() } main().catch(console.error) ``` -------------------------------- ### Client Instance Methods Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md These methods are available on instances created by `createClient()` or `createBareClient()`. ```APIDOC ## Client Instance Methods ### `login(details)` - **Returns**: Promise - **Purpose**: Authenticate user or bot. ### `loginAsBot(token)` - **Returns**: Promise - **Purpose**: Authenticate as bot. ### `invoke(request)` - **Returns**: Promise - **Purpose**: Call TDLib method asynchronously. ### `close()` - **Returns**: Promise - **Purpose**: Close the client. ### `on(event, listener)` - **Returns**: Client - **Purpose**: Register event listener. ### `once(event, listener)` - **Returns**: Client - **Purpose**: Register one-time event listener. ### `off(event, listener)` - **Returns**: boolean - **Purpose**: Remove event listener. ### `iterUpdates()` - **Returns**: AsyncIterator - **Purpose**: Iterate over updates. ### `getVersion()` - **Returns**: string - **Purpose**: Get TDLib version. ### `isClosed()` - **Returns**: boolean - **Purpose**: Check if client is closed. ### `execute(request)` - **Returns**: any - **Purpose**: Synchronous TDLib call. ``` -------------------------------- ### Invoke: Send Message Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of using the invoke method to send a text message to a specified chat. ```javascript // Send a message await client.invoke({ _: 'sendMessage', chat_id: 123456789, input_message_content: { _: 'inputMessageText', text: { _: 'formattedText', text: 'Hello!' } } }) ``` -------------------------------- ### getVersion() Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Get the TDLib version in major.minor.patch format. Throws an error if the version has not yet been received from TDLib. ```APIDOC ## getVersion() ### Description Get the TDLib version in `major.minor.patch` format. ### Method ```typescript getVersion(): string ``` ### Returns Version string like `"1.8.61"`. ### Throws Error if the version has not yet been received from TDLib. ### Example ```javascript const version = client.getVersion() console.log('TDLib version:', version) ``` ``` -------------------------------- ### Get Path to tdjson Library Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Retrieve the file path to the tdjson library. This is useful for manual configuration or verification. ```javascript const tdjsonPath = prebuiltTdl.getTdjson({ // options }); ``` -------------------------------- ### Create and Login to TDL Client Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md Initializes the TDL client with API credentials and logs in. Ensure API ID and Hash are correctly provided. ```javascript const client = tdl.createClient({ apiId: 2222, apiHash: '...' }) client.on('error', console.error) await client.login() ``` -------------------------------- ### Configure TDLib Paths Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Use `configure` to set the paths for the TDLib native libraries. This is typically the first step before creating a client. ```javascript tdl.configure({ tdjson_path: "/path/to/libtdjson.so", // other options }); ``` -------------------------------- ### Create Bare TDL Client Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/core-functions.md Use `createBareClient` for custom TDLib initialization. You must manually handle authorization state updates and send TDLib parameters using `invoke`. ```typescript function createBareClient(): Client ``` -------------------------------- ### Get Name Prompt Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Prompts the user for their first and last name. Use during new user registration when name input is required. ```typescript async function getName(): Promise<{ firstName: string, lastName?: string }> ``` -------------------------------- ### Create TDLib Client Source: https://github.com/eilvelia/tdl/blob/main/README.md Instantiate a TDLib client. Requires `apiId` and `apiHash`. Optional parameters include `databaseDirectory`, `filesDirectory`, `databaseEncryptionKey`, `useTestDc`, `tdlibParameters`, and `skipOldUpdates`. The `tdlibParameters` can be customized or will default to a predefined set of values. ```javascript const client = tdl.createClient({ apiId: 2222, // Your api_id apiHash: '0123456789abcdef0123456789abcdef' // Your api_hash // ... other options ... }) ``` -------------------------------- ### Get Phone Number Prompt Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Prompts the user to enter a phone number. Use when interactive phone number input is required. ```typescript function getPhoneNumber(retry?: boolean): Promise ``` -------------------------------- ### Create Client with Encrypted Database Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/examples.md Demonstrates how to create a TDL client with an encrypted database. Ensure you have a method to generate or retrieve a secure encryption key. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') const crypto = require('crypto') async function main() { tdl.configure({ tdjson: getTdjson() }) // Generate or retrieve encryption key const key = crypto.randomBytes(32).toString('hex') console.log(`Encryption key: ${key}`) const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', databaseEncryptionKey: key, databaseDirectory: './encrypted_db' }) client.on('error', console.error) await client.login() const me = await client.invoke({ _: 'getMe' }) console.log(`Logged in with encrypted DB: ${me.first_name}`) await client.close() } main().catch(console.error) ``` -------------------------------- ### Get TDLib Version and Commit Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/README.md Obtain information about the TDLib version and its Git commit hash. Useful for debugging and compatibility checks. ```javascript const info = prebuiltTdl.getTdlibInfo(); console.log(info); ``` -------------------------------- ### Get TDLib Version Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Retrieve the TDLib version using `client.getVersion()`. This method throws an error if the version has not yet been received from TDLib. ```javascript const version = client.getVersion() console.log('TDLib version:', version) ``` -------------------------------- ### Dynamic Platform Detection for TDLib Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Detect and log the path of the prebuilt TDLib for the current platform. If not available, it logs an error and exits. ```javascript const { getTdjson } = require('prebuilt-tdlib') try { const path = getTdjson() console.log(`Using TDLib from: ${path}`) } catch (err) { console.error('prebuilt-tdlib not available for this platform') console.error('Install a compatible TDLib manually or use a different platform') process.exit(1) } ``` -------------------------------- ### Catching and Inspecting TDLibError Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/errors.md Example of how to use a try-catch block to handle TDLibError, checking its type and accessing its code, message, and toString() representation. ```javascript try { const user = await client.invoke({ _: 'getUser', user_id: 999999999 }) } catch (err) { if (err instanceof TDLibError) { console.log(`Error code: ${err.code}`) console.log(`Error message: ${err.message}`) console.log(`Full error: ${err.toString()}`) } } ``` -------------------------------- ### Get Authentication Code Prompt Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Prompts the user to enter a 2FA authentication code. Use when interactive 2FA code input is required. ```typescript function getAuthCode(retry?: boolean): Promise ``` -------------------------------- ### Generate TDLib Types Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/tdl-install-types.md Run the tdl-install-types command to generate the TypeScript definition file. ```bash npx tdl-install-types ``` -------------------------------- ### Handling Unknown Errors Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/errors.md Example of listening for the 'error' event and checking if an incoming error is an instance of UnknownError, allowing inspection of the original non-Error value. ```javascript client.on('update', (update) => { throw 'Oops!' // Non-Error exception }) client.on('error', (err) => { if (err instanceof UnknownError) { console.log('Unknown exception type:', typeof err.err) console.log('Value:', err.err) } }) ``` -------------------------------- ### Create TDLib Client Instance Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/core-functions.md Creates a TDLib client instance. The client automatically initializes TDLib if not already done. `apiId` and `apiHash` are required. ```javascript const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef', databaseDirectory: './my_db', filesDirectory: './my_files', useTestDc: false }) client.on('error', console.error) await client.login() ``` -------------------------------- ### Get Password Prompt Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Prompts the user to enter a 2FA password. Provides a hint if available. Use when interactive 2FA password input is required. ```typescript function getPassword(passwordHint: string, retry?: boolean): Promise ``` -------------------------------- ### Merge user options with defaults Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Shows how `mergeDeepRight` is used to combine default client options with user-specified options. ```javascript // From client.ts constructor this._options = mergeDeepRight(defaultOptions, options) ``` ```javascript // From client.ts login() const loginDetails = mergeDeepRight( defaultLoginDetails, typeof arg === 'function' ? arg() : arg ) as StrictLoginDetails ``` -------------------------------- ### Version Constructor Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Initializes a new Version object. Throws an error if the provided version string is invalid. Expects format 'major.minor.patch'. ```typescript constructor(ver: string) ``` -------------------------------- ### Basic tdl Integration with Prebuilt TDLib Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Configure tdl to use the prebuilt TDLib library and perform basic client operations like login and invoking methods. Ensure you have your API ID and Hash. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') async function main() { // Configure tdl to use prebuilt library tdl.configure({ tdjson: getTdjson() }) // Create and use client const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) client.on('error', console.error) await client.login() const me = await client.invoke({ _: 'getMe' }) console.log('Hello,', me.first_name) await client.close() } main().catch(console.error) ``` -------------------------------- ### Handling TDLib Errors Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/client.md Example of how to catch and handle TDLibError exceptions when invoking TDLib methods. It checks if the error is an instance of TDLibError to access its code and message. ```javascript try { await client.invoke({ _: 'getMe' }) } catch (err) { if (err instanceof TDLibError) { console.log(`Error ${err.code}: ${err.message}`) } } ``` -------------------------------- ### Create a new Queue instance Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Instantiates a new, empty Queue object. ```javascript const queue = new Queue() ``` -------------------------------- ### Configure TDL Library Options Source: https://github.com/eilvelia/tdl/blob/main/README.md Call this function before `tdl.createClient` or `tdl.execute`. It allows setting parameters such as the TDLib JSON library path, library directory, and verbosity level. Fields not present in the options object remain unchanged. ```javascript tdl.configure({ // Path to the shared library. By default, it is 'tdjson.dll' on Windows, // 'libtdjson.dylib' on macOS, or 'libtdjson.so' otherwise. tdjson: 'libtdjson.so', // Path to the library directory. Defaults to the empty string. libdir: '/usr/local/lib', // Set the verbosity level of TDLib. Defaults to 1. verbosityLevel: 1, // Advanced options: useOldTdjsonInterface: false, receiveTimeout: 10, }) ``` ```javascript tdl.configure({ tdjson: '/root/libtdjson.so', verbosityLevel: 5 }) ``` ```javascript tdl.configure({ libdir: '/usr/local/lib', tdjson: 'libtdjson.dylib.1.8.6' }) ``` ```javascript tdl.configure({ libdir: __dirname }) ``` ```javascript tdl.configure({ tdjson: require('prebuilt-tdlib').getTdjson() }) ``` -------------------------------- ### Get TDLib Info Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/prebuilt-tdlib.md Retrieves metadata about the pre-built TDLib version, including its git commit hash and version string. This function is part of the 'prebuilt-tdlib' package. ```typescript function getTdlibInfo(): { commit: string, version: string } ``` ```javascript const { getTdlibInfo } = require('prebuilt-tdlib') const info = getTdlibInfo() console.log(`TDLib version: ${info.version}`) console.log(`TDLib commit: ${info.commit}`) ``` -------------------------------- ### Prebuilt-TDLib Functions Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/types.md Functions related to prebuilt TDLib binaries. ```APIDOC ## Prebuilt-TDLib Functions ### `getTdjson(options?: Options): string` Returns the path to the prebuilt tdjson binary. ### `getTdlibInfo(): { commit: string, version: string }` Returns information about the prebuilt TDLib, including commit hash and version. ``` -------------------------------- ### Configure TDLib with System Library Path Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Configure TDLib by specifying the directory where the system's tdjson library is located. This is useful for globally installed TDLib versions. ```javascript // Using system library tdl.configure({ libdir: '/usr/local/lib' }) ``` -------------------------------- ### Default Console Login Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/configuration.md Initiates a login process using default console prompts for all required authentication details. ```javascript // Default console prompts await client.login() ``` -------------------------------- ### init Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/core-functions.md Initializes TDLib explicitly. While TDLib initializes automatically on first use, calling `init()` ensures it's loaded beforehand, which can be useful for managing initialization order. ```APIDOC ## Function: init ### Description Initialize TDLib explicitly. ### Signature ```typescript function init(): void ``` ### Returns `void` ### Example ```javascript tdl.init() // TDLib is now loaded ``` ``` -------------------------------- ### Get Email Address Prompt Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/utility-modules.md Prompts the user to enter an email address. Requires TDLib version 1.8.6 or later. Use when interactive email input is required. ```typescript function getEmailAddress(): Promise ``` -------------------------------- ### Get Chat List and Send Message with TDL Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/examples.md Fetches the first 10 chats and sends a message to the first chat in the list. Requires API ID and Hash. ```javascript const tdl = require('tdl') const { getTdjson } = require('prebuilt-tdlib') async function main() { tdl.configure({ tdjson: getTdjson() }) const client = tdl.createClient({ apiId: 2222, apiHash: '0123456789abcdef0123456789abcdef' }) client.on('error', console.error) await client.login() // Get first 10 chats const chatsResult = await client.invoke({ _: 'getChats', chat_list: { _: 'chatListMain' }, limit: 10 }) console.log(`Got ${chatsResult.chat_ids.length} chats:`) for (const chatId of chatsResult.chat_ids) { const chat = await client.invoke({ _: 'getChat', chat_id: chatId }) const title = chat.title || `(Private: ${chatId})` console.log(` - ${title} (ID: ${chatId})`) } // Send message to first chat if (chatsResult.chat_ids.length > 0) { const chatId = chatsResult.chat_ids[0] const result = await client.invoke({ _: 'sendMessage', chat_id: chatId, input_message_content: { _: 'inputMessageText', text: { _: 'formattedText', text: 'Hello from tdl! 👋' } } }) console.log(`Sent message: ${result._}`) } await client.close() } main().catch(console.error) ``` -------------------------------- ### Prebuilt TDLib Exports Source: https://github.com/eilvelia/tdl/blob/main/_autodocs/index.md Functions for retrieving TDLib paths and information from the `prebuilt-tdlib` package. ```APIDOC ## Prebuilt TDLib Exports ### `getTdjson(options)` - **Type**: Function - **Purpose**: Get path to tdjson library. ### `getTdlibInfo()` - **Type**: Function - **Purpose**: Get TDLib version and commit hash. ```