AutoCatBackend/data_providers/tgprovider.js

82 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { TGClient } from './tgclient.js';
import Utils from '../utils/utils.js';
class TGProvider {
constructor() {
this.tgClient = new TGClient(869171, 'c3731f831b212a314f71172daf233f9d');
this.checksMap = new Map();
this.tgClient.onNewMessage(message => {
if(message.chat_id == this.chat.id) {
let messageText = message?.content?.text?.text;
if(messageText && messageText.includes('#️⃣')) {
let number = this.findFirst(messageText, /Номер: (.*)\n/);
if(number) {
this.checksMap.get(number).resolve({
id: message.id,
text: messageText
});
}
}
}
});
//this.init();
}
findFirst(string, regex) {
let result = string.match(regex);
if(result && result.length > 1) {
return result[1];
} else {
return null;
}
}
async init() {
await this.tgClient.login();
this.chat = await this.tgClient.findChat('@l0r3m1psum_bot');
}
async close() {
await this.tgClient.close();
}
async getReport(number) {
try {
await this.tgClient.sendMessage(this.chat, number);
let waitResponseTask = Utils.promiseWithResolvers();
this.checksMap.set(number, waitResponseTask);
setTimeout(() => {
waitResponseTask.reject(Error('TG report timeout'));
}, 25000);
let { id, text } = await waitResponseTask.promise;
await this.tgClient.viewMessage(id, this.chat.id);
return this.parseReport(text);
} finally {
this.checksMap.delete(number);
}
}
parseReport(text) {
let number = this.findFirst(text, /Номер: (.*)\n/);
let vin = this.findFirst(text, /VIN: (.*)\n/);
let owner = this.findFirst(text, /Владелец: (.*)\n/);
let year = this.findFirst(text, /Год: (.*)\n/);
let color = this.findFirst(text, /Цвет: (.*)\n/);
let sts = this.findFirst(text, /СТС: (.*)\n/);
return {
number,
vin,
owner,
year,
color,
sts
};
}
}
export { TGProvider };