108 lines
2.2 KiB
JavaScript
108 lines
2.2 KiB
JavaScript
import tdl from 'tdl';
|
|
import { platform } from 'node:process';
|
|
|
|
class TGClient {
|
|
|
|
static {
|
|
let libdir = null;
|
|
if(platform == 'linux') {
|
|
libdir = './node_modules/prebuilt-tdlib/prebuilds/tdlib-linux-x64';
|
|
} else if(platform == 'darwin') {
|
|
libdir = './node_modules/prebuilt-tdlib/prebuilds/tdlib-macos';
|
|
}
|
|
|
|
tdl.configure({ libdir });
|
|
}
|
|
|
|
constructor(apiId, apiHash) {
|
|
|
|
this.client = tdl.createClient({
|
|
apiId: apiId,
|
|
apiHash: apiHash
|
|
});
|
|
|
|
this.client.on('error', console.error);
|
|
|
|
this.client.on('update', update => {
|
|
//console.log('update: ', update);
|
|
switch(update._) {
|
|
case 'updateMessageSendSucceeded':
|
|
this.sendTasks.get(update.old_message_id)?.resolve(update.message);
|
|
this.sendTasks.delete(update.old_message_id);
|
|
break;
|
|
case 'updateMessageSendFailed':
|
|
this.sendTasks.get(update.old_message_id)?.reject(Error(update.error_message));
|
|
this.sendTasks.delete(update.old_message_id);
|
|
break;
|
|
case 'updateNewMessage':
|
|
this.newMessageCallback?.(update.message);
|
|
break;
|
|
}
|
|
});
|
|
|
|
this.sendTasks = new Map();
|
|
}
|
|
|
|
onNewMessage(callback) {
|
|
this.newMessageCallback = callback;
|
|
}
|
|
|
|
waitAsync(ms) {
|
|
return new Promise(resolve => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async login() {
|
|
await this.client.login();
|
|
}
|
|
|
|
async close() {
|
|
await this.client.close();
|
|
}
|
|
|
|
async getMe() {
|
|
return await this.client.invoke({ _: 'getMe'});
|
|
}
|
|
|
|
async findChat(name) {
|
|
return await this.client.invoke({
|
|
_: 'searchPublicChat',
|
|
username: name
|
|
});
|
|
}
|
|
|
|
async getSavedMessagesChat() {
|
|
let me = await this.getMe();
|
|
return await this.client.invoke({
|
|
_: 'createPrivateChat',
|
|
user_id: me.id
|
|
});
|
|
}
|
|
|
|
async sendMessage(chat, text) {
|
|
let message = await this.client.invoke({
|
|
_: 'sendMessage',
|
|
chat_id: chat.id,
|
|
input_message_content: {
|
|
_: 'inputMessageText',
|
|
text: {
|
|
_: 'formattedText',
|
|
text
|
|
}
|
|
}
|
|
});
|
|
|
|
let sendStatusTask = Promise.withResolvers();
|
|
this.sendTasks.set(message.id, sendStatusTask);
|
|
return await sendStatusTask.promise;
|
|
}
|
|
|
|
async viewMessage(id, chatId) {
|
|
await this.client.invoke({
|
|
_: 'viewMessages',
|
|
chat_id: chatId,
|
|
message_ids: [ id ]
|
|
});
|
|
}
|
|
}
|
|
|
|
export { TGClient }; |