commit
This commit is contained in:
parent
be4fd23bcf
commit
0bd53741af
728 changed files with 86573 additions and 0 deletions
56
node_modules/telegraf/lib/core/helpers/check.js
generated
vendored
Normal file
56
node_modules/telegraf/lib/core/helpers/check.js
generated
vendored
Normal file
|
@ -0,0 +1,56 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.is2D = exports.hasPropType = exports.hasProp = void 0;
|
||||
/**
|
||||
* Checks if a given object has a property with a given name.
|
||||
*
|
||||
* Example invocation:
|
||||
* ```js
|
||||
* let obj = { 'foo': 'bar', 'baz': () => {} }
|
||||
* hasProp(obj, 'foo') // true
|
||||
* hasProp(obj, 'baz') // true
|
||||
* hasProp(obj, 'abc') // false
|
||||
* ```
|
||||
*
|
||||
* @param obj An object to test
|
||||
* @param prop The name of the property
|
||||
*/
|
||||
function hasProp(obj, prop) {
|
||||
return obj !== undefined && prop in obj;
|
||||
}
|
||||
exports.hasProp = hasProp;
|
||||
/**
|
||||
* Checks if a given object has a property with a given name.
|
||||
* Furthermore performs a `typeof` check on the property if it exists.
|
||||
*
|
||||
* Example invocation:
|
||||
* ```js
|
||||
* let obj = { 'foo': 'bar', 'baz': () => {} }
|
||||
* hasPropType(obj, 'foo', 'string') // true
|
||||
* hasPropType(obj, 'baz', 'function') // true
|
||||
* hasPropType(obj, 'abc', 'number') // false
|
||||
* ```
|
||||
*
|
||||
* @param obj An object to test
|
||||
* @param prop The name of the property
|
||||
* @param type The type the property is expected to have
|
||||
*/
|
||||
function hasPropType(obj, prop, type) {
|
||||
return hasProp(obj, prop) && type === typeof obj[prop];
|
||||
}
|
||||
exports.hasPropType = hasPropType;
|
||||
/**
|
||||
* Checks if the supplied array has two dimensions or not.
|
||||
*
|
||||
* Example invocations:
|
||||
* is2D([]) // false
|
||||
* is2D([[]]) // true
|
||||
* is2D([[], []]) // true
|
||||
* is2D([42]) // false
|
||||
*
|
||||
* @param arr an array with one or two dimensions
|
||||
*/
|
||||
function is2D(arr) {
|
||||
return Array.isArray(arr[0]);
|
||||
}
|
||||
exports.is2D = is2D;
|
13
node_modules/telegraf/lib/core/helpers/compact.js
generated
vendored
Normal file
13
node_modules/telegraf/lib/core/helpers/compact.js
generated
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.compactOptions = void 0;
|
||||
function compactOptions(options) {
|
||||
if (!options) {
|
||||
return options;
|
||||
}
|
||||
const keys = Object.keys(options);
|
||||
const compactKeys = keys.filter((key) => options[key] !== undefined);
|
||||
const compactEntries = compactKeys.map((key) => [key, options[key]]);
|
||||
return Object.fromEntries(compactEntries);
|
||||
}
|
||||
exports.compactOptions = compactOptions;
|
50
node_modules/telegraf/lib/core/helpers/formatting.js
generated
vendored
Normal file
50
node_modules/telegraf/lib/core/helpers/formatting.js
generated
vendored
Normal file
|
@ -0,0 +1,50 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.linkOrMention = exports._fmt = exports.FmtString = void 0;
|
||||
class FmtString {
|
||||
constructor(text, entities) {
|
||||
this.text = text;
|
||||
if (entities) {
|
||||
this.entities = entities;
|
||||
// force parse_mode to undefined if entities are present
|
||||
this.parse_mode = undefined;
|
||||
}
|
||||
}
|
||||
static normalise(content) {
|
||||
if (typeof content === 'string')
|
||||
return new FmtString(content);
|
||||
return content;
|
||||
}
|
||||
}
|
||||
exports.FmtString = FmtString;
|
||||
function _fmt(kind, opts) {
|
||||
return function fmt(parts, ...items) {
|
||||
let text = '';
|
||||
const entities = [];
|
||||
parts = typeof parts === 'string' ? [parts] : parts;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
text += parts[i];
|
||||
const item = items[i];
|
||||
if (!item)
|
||||
continue;
|
||||
if (typeof item === 'string') {
|
||||
text += item;
|
||||
continue;
|
||||
}
|
||||
for (const child of item.entities || [])
|
||||
entities.push({ ...child, offset: text.length + child.offset });
|
||||
text += item.text;
|
||||
}
|
||||
if (kind !== 'very-plain')
|
||||
entities.unshift({ type: kind, offset: 0, length: text.length, ...opts });
|
||||
return new FmtString(text, entities.length ? entities : undefined);
|
||||
};
|
||||
}
|
||||
exports._fmt = _fmt;
|
||||
const linkOrMention = (content, data) => {
|
||||
const { text, entities = [] } = FmtString.normalise(content);
|
||||
entities.unshift(Object.assign(data, { offset: 0, length: text.length }));
|
||||
return new FmtString(text, entities);
|
||||
};
|
||||
exports.linkOrMention = linkOrMention;
|
296
node_modules/telegraf/lib/core/network/client.js
generated
vendored
Normal file
296
node_modules/telegraf/lib/core/network/client.js
generated
vendored
Normal file
|
@ -0,0 +1,296 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
/* eslint @typescript-eslint/restrict-template-expressions: [ "error", { "allowNumber": true, "allowBoolean": true } ] */
|
||||
const crypto = __importStar(require("crypto"));
|
||||
const fs = __importStar(require("fs"));
|
||||
const https = __importStar(require("https"));
|
||||
const path = __importStar(require("path"));
|
||||
const node_fetch_1 = __importDefault(require("node-fetch"));
|
||||
const check_1 = require("../helpers/check");
|
||||
const compact_1 = require("../helpers/compact");
|
||||
const multipart_stream_1 = __importDefault(require("./multipart-stream"));
|
||||
const error_1 = __importDefault(require("./error"));
|
||||
const url_1 = require("url");
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
const debug = require('debug')('telegraf:client');
|
||||
const { isStream } = multipart_stream_1.default;
|
||||
const WEBHOOK_REPLY_METHOD_ALLOWLIST = new Set([
|
||||
'answerCallbackQuery',
|
||||
'answerInlineQuery',
|
||||
'deleteMessage',
|
||||
'leaveChat',
|
||||
'sendChatAction',
|
||||
]);
|
||||
const DEFAULT_EXTENSIONS = {
|
||||
audio: 'mp3',
|
||||
photo: 'jpg',
|
||||
sticker: 'webp',
|
||||
video: 'mp4',
|
||||
animation: 'mp4',
|
||||
video_note: 'mp4',
|
||||
voice: 'ogg',
|
||||
};
|
||||
const DEFAULT_OPTIONS = {
|
||||
apiRoot: 'https://api.telegram.org',
|
||||
apiMode: 'bot',
|
||||
webhookReply: true,
|
||||
agent: new https.Agent({
|
||||
keepAlive: true,
|
||||
keepAliveMsecs: 10000,
|
||||
}),
|
||||
attachmentAgent: undefined,
|
||||
testEnv: false,
|
||||
};
|
||||
function includesMedia(payload) {
|
||||
return Object.values(payload).some((value) => {
|
||||
if (Array.isArray(value)) {
|
||||
return value.some(({ media }) => media && typeof media === 'object' && (media.source || media.url));
|
||||
}
|
||||
return (value &&
|
||||
typeof value === 'object' &&
|
||||
(((0, check_1.hasProp)(value, 'source') && value.source) ||
|
||||
((0, check_1.hasProp)(value, 'url') && value.url) ||
|
||||
((0, check_1.hasPropType)(value, 'media', 'object') &&
|
||||
(((0, check_1.hasProp)(value.media, 'source') && value.media.source) ||
|
||||
((0, check_1.hasProp)(value.media, 'url') && value.media.url)))));
|
||||
});
|
||||
}
|
||||
function replacer(_, value) {
|
||||
if (value == null)
|
||||
return undefined;
|
||||
return value;
|
||||
}
|
||||
function buildJSONConfig(payload) {
|
||||
return Promise.resolve({
|
||||
method: 'POST',
|
||||
compress: true,
|
||||
headers: { 'content-type': 'application/json', connection: 'keep-alive' },
|
||||
body: JSON.stringify(payload, replacer),
|
||||
});
|
||||
}
|
||||
const FORM_DATA_JSON_FIELDS = [
|
||||
'results',
|
||||
'reply_markup',
|
||||
'mask_position',
|
||||
'shipping_options',
|
||||
'errors',
|
||||
];
|
||||
async function buildFormDataConfig(payload, agent) {
|
||||
for (const field of FORM_DATA_JSON_FIELDS) {
|
||||
if ((0, check_1.hasProp)(payload, field) && typeof payload[field] !== 'string') {
|
||||
payload[field] = JSON.stringify(payload[field]);
|
||||
}
|
||||
}
|
||||
const boundary = crypto.randomBytes(32).toString('hex');
|
||||
const formData = new multipart_stream_1.default(boundary);
|
||||
const tasks = Object.keys(payload).map((key) => attachFormValue(formData, key, payload[key], agent));
|
||||
await Promise.all(tasks);
|
||||
return {
|
||||
method: 'POST',
|
||||
compress: true,
|
||||
headers: {
|
||||
'content-type': `multipart/form-data; boundary=${boundary}`,
|
||||
connection: 'keep-alive',
|
||||
},
|
||||
body: formData,
|
||||
};
|
||||
}
|
||||
async function attachFormValue(form, id, value, agent) {
|
||||
if (value == null) {
|
||||
return;
|
||||
}
|
||||
if (typeof value === 'string' ||
|
||||
typeof value === 'boolean' ||
|
||||
typeof value === 'number') {
|
||||
form.addPart({
|
||||
headers: { 'content-disposition': `form-data; name="${id}"` },
|
||||
body: `${value}`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (id === 'thumb') {
|
||||
const attachmentId = crypto.randomBytes(16).toString('hex');
|
||||
await attachFormMedia(form, value, attachmentId, agent);
|
||||
return form.addPart({
|
||||
headers: { 'content-disposition': `form-data; name="${id}"` },
|
||||
body: `attach://${attachmentId}`,
|
||||
});
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
const items = await Promise.all(value.map(async (item) => {
|
||||
if (typeof item.media !== 'object') {
|
||||
return await Promise.resolve(item);
|
||||
}
|
||||
const attachmentId = crypto.randomBytes(16).toString('hex');
|
||||
await attachFormMedia(form, item.media, attachmentId, agent);
|
||||
return { ...item, media: `attach://${attachmentId}` };
|
||||
}));
|
||||
return form.addPart({
|
||||
headers: { 'content-disposition': `form-data; name="${id}"` },
|
||||
body: JSON.stringify(items),
|
||||
});
|
||||
}
|
||||
if (value &&
|
||||
typeof value === 'object' &&
|
||||
(0, check_1.hasProp)(value, 'media') &&
|
||||
(0, check_1.hasProp)(value, 'type') &&
|
||||
typeof value.media !== 'undefined' &&
|
||||
typeof value.type !== 'undefined') {
|
||||
const attachmentId = crypto.randomBytes(16).toString('hex');
|
||||
await attachFormMedia(form, value.media, attachmentId, agent);
|
||||
return form.addPart({
|
||||
headers: { 'content-disposition': `form-data; name="${id}"` },
|
||||
body: JSON.stringify({
|
||||
...value,
|
||||
media: `attach://${attachmentId}`,
|
||||
}),
|
||||
});
|
||||
}
|
||||
return await attachFormMedia(form, value, id, agent);
|
||||
}
|
||||
async function attachFormMedia(form, media, id, agent) {
|
||||
var _a, _b, _c;
|
||||
let fileName = (_a = media.filename) !== null && _a !== void 0 ? _a : `${id}.${(_b = DEFAULT_EXTENSIONS[id]) !== null && _b !== void 0 ? _b : 'dat'}`;
|
||||
if (media.url !== undefined) {
|
||||
const res = await (0, node_fetch_1.default)(media.url, { agent });
|
||||
return form.addPart({
|
||||
headers: {
|
||||
'content-disposition': `form-data; name="${id}"; filename="${fileName}"`,
|
||||
},
|
||||
body: res.body,
|
||||
});
|
||||
}
|
||||
if (media.source) {
|
||||
let mediaSource = media.source;
|
||||
if (fs.existsSync(media.source)) {
|
||||
fileName = (_c = media.filename) !== null && _c !== void 0 ? _c : path.basename(media.source);
|
||||
mediaSource = fs.createReadStream(media.source);
|
||||
}
|
||||
if (isStream(mediaSource) || Buffer.isBuffer(mediaSource)) {
|
||||
form.addPart({
|
||||
headers: {
|
||||
'content-disposition': `form-data; name="${id}"; filename="${fileName}"`,
|
||||
},
|
||||
body: mediaSource,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
async function answerToWebhook(response, payload, options) {
|
||||
if (!includesMedia(payload)) {
|
||||
if (!response.headersSent) {
|
||||
response.setHeader('content-type', 'application/json');
|
||||
}
|
||||
response.end(JSON.stringify(payload), 'utf-8');
|
||||
return true;
|
||||
}
|
||||
const { headers, body } = await buildFormDataConfig(payload, options.attachmentAgent);
|
||||
if (!response.headersSent) {
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
response.setHeader(key, value);
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => {
|
||||
response.on('finish', resolve);
|
||||
body.pipe(response);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
function redactToken(error) {
|
||||
error.message = error.message.replace(/\/(bot|user)(\d+):[^/]+\//, '/$1$2:[REDACTED]/');
|
||||
throw error;
|
||||
}
|
||||
class ApiClient {
|
||||
constructor(token, options, response) {
|
||||
this.token = token;
|
||||
this.response = response;
|
||||
this.options = {
|
||||
...DEFAULT_OPTIONS,
|
||||
...(0, compact_1.compactOptions)(options),
|
||||
};
|
||||
if (this.options.apiRoot.startsWith('http://')) {
|
||||
this.options.agent = undefined;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* If set to `true`, first _eligible_ call will avoid performing a POST request.
|
||||
* Note that such a call:
|
||||
* 1. cannot report errors or return meaningful values,
|
||||
* 2. resolves before bot API has a chance to process it,
|
||||
* 3. prematurely confirms the update as processed.
|
||||
*
|
||||
* https://core.telegram.org/bots/faq#how-can-i-make-requests-in-response-to-updates
|
||||
* https://github.com/telegraf/telegraf/pull/1250
|
||||
*/
|
||||
set webhookReply(enable) {
|
||||
this.options.webhookReply = enable;
|
||||
}
|
||||
get webhookReply() {
|
||||
return this.options.webhookReply;
|
||||
}
|
||||
async callApi(method, payload, { signal } = {}) {
|
||||
const { token, options, response } = this;
|
||||
if (options.webhookReply &&
|
||||
(response === null || response === void 0 ? void 0 : response.writableEnded) === false &&
|
||||
WEBHOOK_REPLY_METHOD_ALLOWLIST.has(method)) {
|
||||
debug('Call via webhook', method, payload);
|
||||
// @ts-expect-error using webhookReply is an optimisation that doesn't respond with normal result
|
||||
// up to the user to deal with this
|
||||
return await answerToWebhook(response, { method, ...payload }, options);
|
||||
}
|
||||
if (!token) {
|
||||
throw new error_1.default({
|
||||
error_code: 401,
|
||||
description: 'Bot Token is required',
|
||||
});
|
||||
}
|
||||
debug('HTTP call', method, payload);
|
||||
const config = includesMedia(payload)
|
||||
? await buildFormDataConfig({ method, ...payload }, options.attachmentAgent)
|
||||
: await buildJSONConfig(payload);
|
||||
const apiUrl = new url_1.URL(`./${options.apiMode}${token}${options.testEnv ? '/test' : ''}/${method}`, options.apiRoot);
|
||||
config.agent = options.agent;
|
||||
config.signal = signal;
|
||||
const res = await (0, node_fetch_1.default)(apiUrl, config).catch(redactToken);
|
||||
if (res.status >= 500) {
|
||||
const errorPayload = {
|
||||
error_code: res.status,
|
||||
description: res.statusText,
|
||||
};
|
||||
throw new error_1.default(errorPayload, { method, payload });
|
||||
}
|
||||
const data = await res.json();
|
||||
if (!data.ok) {
|
||||
debug('API call failed', data);
|
||||
throw new error_1.default(data, { method, payload });
|
||||
}
|
||||
return data.result;
|
||||
}
|
||||
}
|
||||
exports.default = ApiClient;
|
21
node_modules/telegraf/lib/core/network/error.js
generated
vendored
Normal file
21
node_modules/telegraf/lib/core/network/error.js
generated
vendored
Normal file
|
@ -0,0 +1,21 @@
|
|||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.TelegramError = void 0;
|
||||
class TelegramError extends Error {
|
||||
constructor(response, on = {}) {
|
||||
super(`${response.error_code}: ${response.description}`);
|
||||
this.response = response;
|
||||
this.on = on;
|
||||
}
|
||||
get code() {
|
||||
return this.response.error_code;
|
||||
}
|
||||
get description() {
|
||||
return this.response.description;
|
||||
}
|
||||
get parameters() {
|
||||
return this.response.parameters;
|
||||
}
|
||||
}
|
||||
exports.TelegramError = TelegramError;
|
||||
exports.default = TelegramError;
|
61
node_modules/telegraf/lib/core/network/multipart-stream.js
generated
vendored
Normal file
61
node_modules/telegraf/lib/core/network/multipart-stream.js
generated
vendored
Normal file
|
@ -0,0 +1,61 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const stream = __importStar(require("stream"));
|
||||
const check_1 = require("../helpers/check");
|
||||
const sandwich_stream_1 = __importDefault(require("sandwich-stream"));
|
||||
const CRNL = '\r\n';
|
||||
class MultipartStream extends sandwich_stream_1.default {
|
||||
constructor(boundary) {
|
||||
super({
|
||||
head: `--${boundary}${CRNL}`,
|
||||
tail: `${CRNL}--${boundary}--`,
|
||||
separator: `${CRNL}--${boundary}${CRNL}`,
|
||||
});
|
||||
}
|
||||
addPart(part) {
|
||||
const partStream = new stream.PassThrough();
|
||||
for (const [key, header] of Object.entries(part.headers)) {
|
||||
partStream.write(`${key}:${header}${CRNL}`);
|
||||
}
|
||||
partStream.write(CRNL);
|
||||
if (MultipartStream.isStream(part.body)) {
|
||||
part.body.pipe(partStream);
|
||||
}
|
||||
else {
|
||||
partStream.end(part.body);
|
||||
}
|
||||
this.add(partStream);
|
||||
}
|
||||
static isStream(stream) {
|
||||
return (typeof stream === 'object' &&
|
||||
stream !== null &&
|
||||
(0, check_1.hasPropType)(stream, 'pipe', 'function'));
|
||||
}
|
||||
}
|
||||
exports.default = MultipartStream;
|
89
node_modules/telegraf/lib/core/network/polling.js
generated
vendored
Normal file
89
node_modules/telegraf/lib/core/network/polling.js
generated
vendored
Normal file
|
@ -0,0 +1,89 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Polling = void 0;
|
||||
const abort_controller_1 = __importDefault(require("abort-controller"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const util_1 = require("util");
|
||||
const error_1 = require("./error");
|
||||
const debug = (0, debug_1.default)('telegraf:polling');
|
||||
const wait = (0, util_1.promisify)(setTimeout);
|
||||
function always(x) {
|
||||
return () => x;
|
||||
}
|
||||
const noop = always(Promise.resolve());
|
||||
class Polling {
|
||||
constructor(telegram, allowedUpdates) {
|
||||
this.telegram = telegram;
|
||||
this.allowedUpdates = allowedUpdates;
|
||||
this.abortController = new abort_controller_1.default();
|
||||
this.skipOffsetSync = false;
|
||||
this.offset = 0;
|
||||
}
|
||||
async *[Symbol.asyncIterator]() {
|
||||
var _a, _b;
|
||||
debug('Starting long polling');
|
||||
do {
|
||||
try {
|
||||
const updates = await this.telegram.callApi('getUpdates', {
|
||||
timeout: 50,
|
||||
offset: this.offset,
|
||||
allowed_updates: this.allowedUpdates,
|
||||
}, this.abortController);
|
||||
const last = updates[updates.length - 1];
|
||||
if (last !== undefined) {
|
||||
this.offset = last.update_id + 1;
|
||||
}
|
||||
yield updates;
|
||||
}
|
||||
catch (error) {
|
||||
const err = error;
|
||||
if (err.name === 'AbortError')
|
||||
return;
|
||||
if (err.name === 'FetchError' ||
|
||||
(err instanceof error_1.TelegramError && err.code === 429) ||
|
||||
(err instanceof error_1.TelegramError && err.code >= 500)) {
|
||||
const retryAfter = (_b = (_a = err.parameters) === null || _a === void 0 ? void 0 : _a.retry_after) !== null && _b !== void 0 ? _b : 5;
|
||||
debug('Failed to fetch updates, retrying after %ds.', retryAfter, err);
|
||||
await wait(retryAfter * 1000);
|
||||
continue;
|
||||
}
|
||||
if (err instanceof error_1.TelegramError &&
|
||||
// Unauthorized Conflict
|
||||
(err.code === 401 || err.code === 409)) {
|
||||
this.skipOffsetSync = true;
|
||||
throw err;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} while (!this.abortController.signal.aborted);
|
||||
}
|
||||
async syncUpdateOffset() {
|
||||
if (this.skipOffsetSync)
|
||||
return;
|
||||
debug('Syncing update offset...');
|
||||
await this.telegram.callApi('getUpdates', { offset: this.offset, limit: 1 });
|
||||
}
|
||||
async loop(handleUpdate) {
|
||||
if (this.abortController.signal.aborted) {
|
||||
throw new Error('Polling instances must not be reused!');
|
||||
}
|
||||
try {
|
||||
for await (const updates of this) {
|
||||
await Promise.all(updates.map(handleUpdate));
|
||||
}
|
||||
}
|
||||
finally {
|
||||
debug('Long polling stopped');
|
||||
// prevent instance reuse
|
||||
this.stop();
|
||||
await this.syncUpdateOffset().catch(noop);
|
||||
}
|
||||
}
|
||||
stop() {
|
||||
this.abortController.abort();
|
||||
}
|
||||
}
|
||||
exports.Polling = Polling;
|
54
node_modules/telegraf/lib/core/network/webhook.js
generated
vendored
Normal file
54
node_modules/telegraf/lib/core/network/webhook.js
generated
vendored
Normal file
|
@ -0,0 +1,54 @@
|
|||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const debug = (0, debug_1.default)('telegraf:webhook');
|
||||
function generateWebhook(filter, updateHandler) {
|
||||
return async (req, res, next = () => {
|
||||
res.statusCode = 403;
|
||||
debug('Replying with status code', res.statusCode);
|
||||
res.end();
|
||||
}) => {
|
||||
debug('Incoming request', req.method, req.url);
|
||||
if (!filter(req)) {
|
||||
debug('Webhook filter failed', req.method, req.url);
|
||||
return next();
|
||||
}
|
||||
let update;
|
||||
try {
|
||||
if (req.body != null) {
|
||||
/* If req.body is already set, we expect it to be the parsed
|
||||
request body (update object) received from Telegram
|
||||
However, some libraries such as `serverless-http` set req.body to the
|
||||
raw buffer, so we'll handle that additionally */
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let body = req.body;
|
||||
// if body is Buffer, parse it into string
|
||||
if (body instanceof Buffer)
|
||||
body = String(req.body);
|
||||
// if body is string, parse it into object
|
||||
if (typeof body === 'string')
|
||||
body = JSON.parse(body);
|
||||
update = body;
|
||||
}
|
||||
else {
|
||||
let body = '';
|
||||
// parse each buffer to string and append to body
|
||||
for await (const chunk of req)
|
||||
body += String(chunk);
|
||||
// parse body to object
|
||||
update = JSON.parse(body);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
// if any of the parsing steps fails, give up and respond with error
|
||||
res.writeHead(415).end();
|
||||
debug('Failed to parse request body:', error);
|
||||
return;
|
||||
}
|
||||
return await updateHandler(update, res);
|
||||
};
|
||||
}
|
||||
exports.default = generateWebhook;
|
26
node_modules/telegraf/lib/core/types/typegram.js
generated
vendored
Normal file
26
node_modules/telegraf/lib/core/types/typegram.js
generated
vendored
Normal file
|
@ -0,0 +1,26 @@
|
|||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (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);
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
// internal type provisions
|
||||
__exportStar(require("typegram/api"), exports);
|
||||
__exportStar(require("typegram/markup"), exports);
|
||||
__exportStar(require("typegram/menu-button"), exports);
|
||||
__exportStar(require("typegram/inline"), exports);
|
||||
__exportStar(require("typegram/manage"), exports);
|
||||
__exportStar(require("typegram/message"), exports);
|
||||
__exportStar(require("typegram/passport"), exports);
|
||||
__exportStar(require("typegram/payment"), exports);
|
||||
__exportStar(require("typegram/update"), exports);
|
Loading…
Add table
Add a link
Reference in a new issue