@apidog/multibot-sdk-ts
Version: 
Telegram and VK bot SDK for TypeScript
137 lines • 5.92 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Bot = void 0;
const FormData = require("form-data");
const node_fetch_1 = require("node-fetch");
const abstract_bot_1 = require("../abstract-bot");
const matcher_1 = require("./matcher");
class Bot extends abstract_bot_1.default {
    constructor(config) {
        super();
        this.server = undefined;
        this.getApiEndpoint = (method) => `${this.config.apiUrl}/${method}`;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        this.request = (apiMethod, params = {}) => __awaiter(this, void 0, void 0, function* () {
            var _a;
            const form = Object.keys(params).reduce((form, key) => {
                if (params[key] !== undefined) {
                    let v = params[key];
                    if (Array.isArray(v)) {
                        v = v.join(',');
                    }
                    if (typeof v !== 'string') {
                        v = JSON.stringify(v);
                    }
                    form.append(key, v);
                }
                return form;
            }, new FormData());
            form.append('access_token', this.config.token);
            form.append('v', this.config.apiVersion);
            form.append('lang', (_a = this.config.lang) !== null && _a !== void 0 ? _a : 'en');
            const endpoint = this.getApiEndpoint(apiMethod);
            const request = yield (0, node_fetch_1.default)(endpoint, {
                method: 'POST',
                body: form,
                headers: form.getHeaders(),
            });
            const data = yield request.json();
            const { status, statusText } = request;
            if (status !== 200) {
                throw new Error(`Error HTTP ${statusText}`);
            }
            if ('error' in data) {
                throw data.error;
            }
            return data.response;
        });
        /**
         * Polling
         */
        this.isPollingActive = false;
        this.getLongPollServer = () => __awaiter(this, void 0, void 0, function* () { return this.request('groups.getLongPollServer', { group_id: this.config.groupId }); });
        this.startPolling = () => __awaiter(this, void 0, void 0, function* () {
            if (this.isPollingActive) {
                return;
            }
            this.isPollingActive = true;
            this.server = yield this.getLongPollServer();
            (() => __awaiter(this, void 0, void 0, function* () {
                while (this.isPollingActive) {
                    // eslint-disable-next-line no-await-in-loop
                    yield this.poll();
                }
            }))();
        });
        this.getLongPollUrl = () => {
            const { server, key, ts } = this.server;
            return `${server}?act=a_check&key=${key}&ts=${ts}&wait=25`;
        };
        this.waitForResponseLongPoll = () => __awaiter(this, void 0, void 0, function* () {
            const request = yield (0, node_fetch_1.default)(this.getLongPollUrl());
            return request.json();
        });
        this.poll = () => __awaiter(this, void 0, void 0, function* () {
            return new Promise(resolve => {
                this.waitForResponseLongPoll().then(response => {
                    this.server.ts = response.ts;
                    resolve();
                    response.updates.forEach(this.handleUpdate);
                });
            });
        });
        this.events = {};
        this.on = (event, listener) => {
            if (!this.events[event]) {
                this.events[event] = [];
            }
            this.events[event].push(listener);
        };
        this.handleUpdate = (update) => {
            this.matcher.getMatches(update).forEach(match => {
                var _a;
                (_a = this.events[match.type]) === null || _a === void 0 ? void 0 : _a.forEach(callback => callback(match.handle(update)));
            });
        };
        this.stopPolling = () => {
            this.isPollingActive = false;
        };
        if (!config.token) {
            throw new Error('token not specified');
        }
        if (config.groupId <= 0) {
            throw new Error('groupId must be positive');
        }
        this.config = Object.assign(Object.assign({}, Bot.defaultConfig), config);
        this.setMatcher(new matcher_1.VkMatcher(this));
    }
}
exports.Bot = Bot;
Bot.defaultConfig = {
    token: 'never_used',
    groupId: 0,
    apiUrl: 'https://api.vk.com/method',
    apiVersion: '5.103',
};
__exportStar(require("./matcher"), exports);
__exportStar(require("./utils"), exports);
//# sourceMappingURL=index.js.map