class Bot{
constructor(token, options){
this.token = token;
this._startPath = Bot._buildStartPath(token);
this.__lastMessageID = null;
this.__updateTime = options && options.updateTime && 1000;
this.__loop = Promise.resolve();
this.__callbacks = [];
this.__callbacksWith = [];
this._start();
}
static _buildStartPath(token){
return `https://api.telegram.org/bot${token}`;
}
static __buildMessageInfo(message){
const messageProps = message.edited_message || message.message;
const messageFilteredProps = {
updateID: message.update_id,
messageID: messageProps.message_id,
username: messageProps.from.username,
userID: messageProps.from.id,
date: messageProps.date,
text: messageProps.text,
};
return messageFilteredProps;
}
static __prepareMessages(response, quantity) {
response = response.result.slice(0, quantity);
return response;
}
static _buildPath(startPath, additionalPath = '', options = {}){
if (typeof additionalPath === 'object'){
options = additionalPath;
additionalPath = '';
}
const question = additionalPath.indexOf('?') === -1 ? '?' : '&';
options = Object.entries(options);
additionalPath = options.reduce(
(path, option) => `${path}${option[0]}=${option[1]}&`, `${additionalPath}${question}`
);
return `${startPath}/${additionalPath}`;
}
async _getUpdates(options = {}){
options.offset = this.__lastMessageID;
const
path = Bot._buildPath(this._startPath, 'getUpdates', options),
request = await fetch(path),
response = await request.json();
return response;
}
__isNewMessageAvailable(messages){
const lastID = messages[messages.length - 1].updateID;
if (this.__lastMessageID !== lastID) {
return lastID;
}
return false;
}
__updateLastMessageID(newMessageID){
this.__lastMessageID = newMessageID;
}
onMessage(message, callback){
this.__callbacks.push({message, callback});
}
onMessageWith(message, callback){
this.__callbacksWith.push({message, callback});
}
__applyCallbacks(message){
const filteredCallbacks = this.__callbacks.filter(
callbackObj => callbackObj.message.toLowerCase() === message.toLowerCase()
);
filteredCallbacks.forEach(callbackObj => callbackObj.callback());
}
__applyCallbacksWith(message) {
const filteredCallbacks = this.__callbacksWith.filter(
callbackObj => message
.toLowerCase()
.startsWith(callbackObj.message.toLowerCase()+':')
);
if(filteredCallbacks.length === 0){
return;
}
const parsedParam = message
.match(/(?:.*:)(.*)/i)[1]
.trim();
filteredCallbacks.forEach(callbackObj => callbackObj.callback(parsedParam));
}
async getMessages(options = {}){
let quantity,
messages;
options.quantity && (quantity = options.quantity);
delete options.quantity;
try {
const response = await this._getUpdates(options);
messages = Bot.__prepareMessages(response, quantity);
} catch (e) {
console.log(e);
}
return messages.map(Bot.__buildMessageInfo);
}
_start(updateTime = 500, timeToLive = 30000) {
const self = this;
let _cTime = 0;
const I = setInterval(async () => {
const messages = await self.getMessages();
const newMessageID = self.__isNewMessageAvailable(messages);
const newMessage = messages[messages.length - 1].text;
if (newMessageID){
this.__applyCallbacks(newMessage);
this.__applyCallbacksWith(newMessage);
self.__updateLastMessageID(newMessageID);
}
if (timeToLive < _cTime + updateTime){
clearInterval(I);
}
}, updateTime);
}
}
const bot = new Bot('872215482:AAEzxIM77DE-yMJlAV74aU_P0tSqh_Joj_w');
bot.onMessage('пока', function() {
document.body.style.display = 'none'
})
bot.onMessageWith('слово', function(text) {
document.body.style.display = 'block';
document.body.innerHTML = `<h1>${text}</h1>`;
})