/tdl

TDLib bindings for Node.js.

Primary LanguageJavaScriptMIT LicenseMIT

tdl

npm GitHub repo size in bytes node Build Status

Node.js wrapper for TDLib (Telegram Database library).

Table of Contents


Getting started

  1. Build the binary (https://github.com/tdlib/td#building)
  2. npm install tdl

API

new Client(options: Object) => Client
const { Client } = require('tdl')

const client = new Client({
  apiId: 2222, // Your api_id
  apiHash: '0123456789abcdef0123456789abcdef', // Your api_hash
})

api_id and api_hash can be obtained at https://my.telegram.org/.

client.connect() => Promise<undefined>

You can use this method to initialize and connect your client with Telegram.
Returns promise.

await client.connect()
client.login(fn: () => LoginDetails) => Promise<undefined>
await client.login(() => ({
  phoneNumber: 'YOUR_PHONE_NUMBER'
}))
client.on(event: string, callback: Function) => Client
client.once(event: string, callback: Function) => Client

Attach an event listener for iterating updates.

client.on('update', console.log)
client.on('error', console.error)
client.removeListener(event: string, listener: Function, once?: boolean) => Client

Remove an event listener.

const listener = v => {
  console.log('New update.', v)
  client.removeListener('update', listener)
}
client.on('update', listener)
client.invoke(query: Object) => Promise<Object>

Send asynchronous message to Telegram and receive response.
Resolves with response, or rejects with an error.

const chats = await client.invoke({
  _: 'getChats',
  offset_order: '9223372036854775807',
  offset_chat_id: 0,
  limit: 100
})
await client.invoke({
  _: 'sendMessage',
  chat_id: 123456789,
  input_message_content: {
    _: 'inputMessageText',
    text: {
      _: 'formattedText',
      text: '👻'
    }
  }
})
client.execute(query: Object) => (Object | null)

Send synchronous message to Telegram and receive response.

const res = client.execute({
  _: 'getTextEntities',
  text: '@telegram /test_command https://telegram.org telegram.me'
})
client.destroy() => undefined

Destroy the client.

client.destroy()
client.setLogFilePath(path: string) => number

Sets the path to the file to where the internal TDLib log will be written. By default TDLib writes logs to stderr or an OS specific log. Use this method to write the log to a file instead.

client.setLogFilePath('log.txt')

See docs.

client.setLogMaxFileSize(maxFileSize: (number | string)) => undefined

Sets maximum size of the file to where the internal TDLib log is written before the file will be auto-rotated. Unused if log is not written to a file. Defaults to 10 MB.

client.setLogMaxFileSize(50000)

See docs.

client.setLogVerbosityLevel(verbosityLevel: number) => undefined

Sets the verbosity level of the internal logging of TDLib.
Default is 2.

client.setLogVerbosityLevel(2)

See docs.

client.setLogFatalErrorCallback(fn: (null | Function)) => undefined

Sets the callback that will be called when a fatal error happens. None of the TDLib methods can be called from the callback. The TDLib will crash as soon as callback returns. By default the callback is not set.

client.setLogFatalErrorCallback(
  errorMessage => console.error('Fatal error:', errorMessage)
)

See docs.

client.invokeFuture(query: Object) => Future

Same as client.invoke, but returns Future instead of Promise.

Low-level TDLib API

See TDLib_API.md.


Login as a bot

const client = new Client({
  apiId: 2222, // Your api_id
  apiHash: '0123456789abcdef0123456789abcdef' // Your api_hash
})

await client.connect()
await client.login(() => ({
  type: 'bot',
  token: 'YOUR_BOT_TOKEN' // Token from @BotFather
}))

Options

type Options = {
  apiId: number, // Can be obtained at https://my.telegram.org
  apiHash: string, // Can be obtained at https://my.telegram.org
  binaryPath: string, // Path to tdlib binary, relative path
  databaseDirectory: string, // Relative path
  filesDirectory: string, // Relative path
  databaseEncryptionKey: string, // Optional key for database encryption
  verbosityLevel: number,
  skipOldUpdates: boolean, // Don't emit old updates
  useTestDc: boolean, // Use telegram dev server
  useMutableRename: boolean, // May increase performance
  tdlibParameters: Object, // See https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1tdlib_parameters.html
  tdlibInstance: TDLib
}

type LoginDetails = {
  type: 'user',
  phoneNumber: string,
  getAuthCode: (retry?: boolean) => Promise<string>,
  getPassword: (passwordHint: string, retry?: boolean) => Promise<string>,
  getName: () => Promise<{ firstName: string, lastName?: string }>
} | {
  type: 'bot',
  token: string
}

Any empty fields may just not be specified.

Defaults
options = {
  binaryPath: 'libtdjson', // (and 'tdjson' on Windows)
  databaseDirectory: '_td_database',
  filesDirectory: '_td_files',
  verbosityLevel: 2,
  skipOldUpdates: false,
  useTestDc: false,
  useMutableRename: false,
  tdlibParameters: {
    use_message_database: true,
    use_secret_chats: false,
    system_language_code: 'en',
    application_version: '1.0',
    device_model: 'tdlib',
    system_version: 'node',
    enable_storage_optimizer: true
  }
}

loginDetails = {
  type: 'user',
  getAuthCode, // read from stdin
  getPassword,  // read from stdin
  getName // read from stdin
}

Typings

tdl supports Flow and TypeScript out of the box. Typings are generated from td_api.tl scheme using tdlib-typings.

You can import TDLib types:

// TypeScript
import { updateMessageViews, messageInvoice /* ... */ } from 'tdl/types/tdlib'

// Flow
import type { updateMessageViews, messageInvoice /* ... */ } from 'tdl/types/tdlib'

Examples

See examples/ folder.


Requirements

  • TDLib binary (libtdjson.so on Linux, libtdjson.dylib on macOS, tdjson.dll on Windows)
  • Node.js 10 preferred (minimum >= 8.6.0)

Note: If you are using Node.js 8.x-9.x, you may encounter a warning message Warning: N-API is an experimental feature and could change at any time., this can be suppressed by upgrading to version 10.

You can also use prebuilt binaries: