tdl
Node.js wrapper for TDLib (Telegram Database library).
Table of Contents
Getting started
- Build the binary (https://github.com/tdlib/td#building)
npm install tdl
API
new Client(options: Object) => Client
const { Client } = require('tdl')
const client = new Client({
apiId: 2222,
apiHash: '0123456789abcdef0123456789abcdef',
})
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()
By default, tdl
asks user for phone number, auth code, and password (if specified) in console.
You can pass your functions:
await client.login(() => ({
getPhoneNumber: retry => retry
? Promise.reject('Invalid phone number')
: Promise.resolve('+9996620001'),
getAuthCode: retry => retry
? Promise.reject('Invalid auth code')
: Promise.resolve('22222'),
getPassword: (passwordHint, retry) => retry
? Promise.reject('Invalid password')
: Promise.resolve('abcdef'),
getName: () =>
Promise.resolve({ firstName: 'John', lastName: 'Doe' })
}))
getName
function is called if user is not registered.
Also see LoginDetails
interface in Options section.
client.connectAndLogin(fn?: () => LoginDetails) => Promise<undefined>
Same as client.connect().then(() => client.login(fn))
.
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)
Ideally you should always have a listener on client.on('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,
apiHash: '0123456789abcdef0123456789abcdef'
})
await client.connectAndLogin(() => ({
type: 'bot',
getToken: retry => retry
? Promise.reject('Token is not valid')
: Promise.resolve('YOUR_BOT_TOKEN')
}))
Options
type Options = {
apiId: number,
apiHash: string,
binaryPath: string,
databaseDirectory: string,
filesDirectory: string,
databaseEncryptionKey: string,
verbosityLevel: number,
useTestDc: boolean,
skipOldUpdates: boolean,
useMutableRename: boolean,
useDefaultVerbosityLevel: boolean,
tdlibParameters: Object,
tdlibInstance: TDLib
}
type LoginDetails = {
type: 'user',
getPhoneNumber: (retry?: boolean) => Promise<string>,
getAuthCode: (retry?: boolean) => Promise<string>,
getPassword: (passwordHint: string, retry?: boolean) => Promise<string>,
getName: () => Promise<{ firstName: string, lastName?: string }>
} | {
type: 'bot',
getToken: (retry?: boolean) => Promise<string>
}
Only apiId
and apiHash
are required fields.
Any other fields can just be not specified.
tdlibParameters
option: See https://core.telegram.org/tdlib/docs/classtd_1_1td__api_1_1tdlib_parameters.html.
Defaults
options = {
binaryPath: 'libtdjson',
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
}
}
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:
import { updateMessageViews, messageInvoice } from 'tdl/types/tdlib'
import type { updateMessageViews, messageInvoice } from 'tdl/types/tdlib'
Warning: TDLib typings does not follow SemVer.
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:
Contributing
See CONTRIBUTING.md.