Skip to content

Instantly share code, notes, and snippets.

@tuscen
Created June 9, 2018 10:33
Show Gist options
  • Save tuscen/12e767d84af15081b33f533a87e2d785 to your computer and use it in GitHub Desktop.
Save tuscen/12e767d84af15081b33f533a87e2d785 to your computer and use it in GitHub Desktop.
In-browser Telegram bot
import { HttpPoller } from './httpPoller.js';
function last(array) {
return array[array.length - 1];
}
const token = "BOT_TOKEN";
const url = `https://api.telegram.org/bot${token}/getUpdates`;
const poller = new HttpPoller(url, "POST");
poller.start(data => {
const apiResponse = JSON.parse(data.response);
console.log(apiResponse);
const updates = apiResponse.result;
if (updates.length > 0) {
data.state.body = {
offset: last(updates).update_id + 1
};
}
});
export class HttpPoller {
constructor(url, method, timeout = 30) {
this.url = url;
this.method = method;
this.timeout = timeout;
this.state = HttpPoller.STOPPED;
}
set timeout(value) {
this._timeout = value * 1000;
}
get timeout() {
return this._timeout;
}
withBody() {
return ["POST", "PUT"].includes(this.method);
}
start(callback, body = null) {
if (this.state == HttpPoller.STARTED) {
return;
}
const pollerState = {
body: body
};
const poller = (callback, pollerState) => {
if (this.state == HttpPoller.STOPPED) {
return;
}
const xhr = new XMLHttpRequest();
xhr.open(this.method, this.url, true);
xhr.timeout = this.timeout;
xhr.onreadystatechange = (e) => {
if (this.state == HttpPoller.STOPPED) {
e.target.abort();
return;
}
if(e.target.readyState == XMLHttpRequest.DONE) {
callback({
response: e.target.response,
state: pollerState
});
setTimeout(() => poller(callback, pollerState));
}
};
xhr.onabort = () => this.stop();
xhr.onerror = () => this.stop();
xhr.ontimeout = () => setTimeout(() => poller(callback, pollerState));
xhr.setRequestHeader("Content-Type", "application/json");
if (this.withBody() && pollerState.body) {
xhr.send(JSON.stringify(pollerState.body));
} else {
xhr.send();
}
};
this.state = HttpPoller.STARTED;
setTimeout(() => poller(callback, pollerState));
}
stop() {
this.state = HttpPoller.STOPPED;
}
}
HttpPoller.STOPPED = 0;
HttpPoller.STARTED = 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment