upd
This commit is contained in:
101
node_modules/telegraf/lib/button.js
generated
vendored
Normal file
101
node_modules/telegraf/lib/button.js
generated
vendored
Normal file
@@ -0,0 +1,101 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.webApp = exports.login = exports.pay = exports.game = exports.switchToCurrentChat = exports.switchToChat = exports.callback = exports.url = exports.channelRequest = exports.groupRequest = exports.botRequest = exports.userRequest = exports.pollRequest = exports.locationRequest = exports.contactRequest = exports.text = void 0;
|
||||
function text(text, hide = false) {
|
||||
return { text, hide };
|
||||
}
|
||||
exports.text = text;
|
||||
function contactRequest(text, hide = false) {
|
||||
return { text, request_contact: true, hide };
|
||||
}
|
||||
exports.contactRequest = contactRequest;
|
||||
function locationRequest(text, hide = false) {
|
||||
return { text, request_location: true, hide };
|
||||
}
|
||||
exports.locationRequest = locationRequest;
|
||||
function pollRequest(text, type, hide = false) {
|
||||
return { text, request_poll: { type }, hide };
|
||||
}
|
||||
exports.pollRequest = pollRequest;
|
||||
function userRequest(text,
|
||||
/** Must fit in a signed 32 bit int */
|
||||
request_id, extra, hide = false) {
|
||||
return {
|
||||
text,
|
||||
request_users: { request_id, ...extra },
|
||||
hide,
|
||||
};
|
||||
}
|
||||
exports.userRequest = userRequest;
|
||||
function botRequest(text,
|
||||
/** Must fit in a signed 32 bit int */
|
||||
request_id, extra, hide = false) {
|
||||
return {
|
||||
text,
|
||||
request_users: { request_id, user_is_bot: true, ...extra },
|
||||
hide,
|
||||
};
|
||||
}
|
||||
exports.botRequest = botRequest;
|
||||
function groupRequest(text,
|
||||
/** Must fit in a signed 32 bit int */
|
||||
request_id, extra, hide = false) {
|
||||
return {
|
||||
text,
|
||||
request_chat: { request_id, chat_is_channel: false, ...extra },
|
||||
hide,
|
||||
};
|
||||
}
|
||||
exports.groupRequest = groupRequest;
|
||||
function channelRequest(text,
|
||||
/** Must fit in a signed 32 bit int */
|
||||
request_id, extra, hide = false) {
|
||||
return {
|
||||
text,
|
||||
request_chat: { request_id, chat_is_channel: true, ...extra },
|
||||
hide,
|
||||
};
|
||||
}
|
||||
exports.channelRequest = channelRequest;
|
||||
function url(text, url, hide = false) {
|
||||
return { text, url, hide };
|
||||
}
|
||||
exports.url = url;
|
||||
function callback(text, data, hide = false) {
|
||||
return { text, callback_data: data, hide };
|
||||
}
|
||||
exports.callback = callback;
|
||||
function switchToChat(text, value, hide = false) {
|
||||
return { text, switch_inline_query: value, hide };
|
||||
}
|
||||
exports.switchToChat = switchToChat;
|
||||
function switchToCurrentChat(text, value, hide = false) {
|
||||
return { text, switch_inline_query_current_chat: value, hide };
|
||||
}
|
||||
exports.switchToCurrentChat = switchToCurrentChat;
|
||||
function game(text, hide = false) {
|
||||
return { text, callback_game: {}, hide };
|
||||
}
|
||||
exports.game = game;
|
||||
function pay(text, hide = false) {
|
||||
return { text, pay: true, hide };
|
||||
}
|
||||
exports.pay = pay;
|
||||
function login(text, url, opts = {}, hide = false) {
|
||||
return {
|
||||
text,
|
||||
login_url: { ...opts, url },
|
||||
hide,
|
||||
};
|
||||
}
|
||||
exports.login = login;
|
||||
function webApp(text, url, hide = false
|
||||
// works as both InlineKeyboardButton and KeyboardButton
|
||||
) {
|
||||
return {
|
||||
text,
|
||||
web_app: { url },
|
||||
hide,
|
||||
};
|
||||
}
|
||||
exports.webApp = webApp;
|
||||
105
node_modules/telegraf/lib/cli.mjs
generated
vendored
Executable file
105
node_modules/telegraf/lib/cli.mjs
generated
vendored
Executable file
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env node
|
||||
import d from 'debug';
|
||||
import parse from 'mri';
|
||||
import path from 'path';
|
||||
import { Telegraf } from './index.js';
|
||||
const debug = d('telegraf:cli');
|
||||
const helpMsg = `Usage: telegraf [opts] <bot-file>
|
||||
|
||||
-t Bot token [$BOT_TOKEN]
|
||||
-d Webhook domain [$BOT_DOMAIN]
|
||||
-H Webhook host [0.0.0.0]
|
||||
-p Webhook port [$PORT or 3000]
|
||||
-l Enable logs
|
||||
-h Show this help message
|
||||
-m Bot API method to run directly
|
||||
-D Data to pass to the Bot API method`;
|
||||
const help = () => console.log(helpMsg);
|
||||
/**
|
||||
* Runs the cli program and returns exit code
|
||||
*/
|
||||
export async function main(argv, env = {}) {
|
||||
const args = parse(argv, {
|
||||
alias: {
|
||||
// string params, all optional
|
||||
t: 'token',
|
||||
d: 'domain',
|
||||
m: 'method',
|
||||
D: 'data',
|
||||
// defaults exist
|
||||
H: 'host',
|
||||
p: 'port',
|
||||
// boolean params
|
||||
l: 'logs',
|
||||
h: 'help',
|
||||
},
|
||||
boolean: ['h', 'l'],
|
||||
default: {
|
||||
H: '0.0.0.0',
|
||||
p: env.PORT || '3000',
|
||||
},
|
||||
});
|
||||
if (args.help) {
|
||||
help();
|
||||
return 0;
|
||||
}
|
||||
const token = args.token || env.BOT_TOKEN;
|
||||
const domain = args.domain || env.BOT_DOMAIN;
|
||||
if (!token) {
|
||||
console.error('Please supply Bot Token');
|
||||
help();
|
||||
return 1;
|
||||
}
|
||||
const bot = new Telegraf(token);
|
||||
if (args.method) {
|
||||
const method = args.method;
|
||||
console.log(await bot.telegram.callApi(method, JSON.parse(args.data || '{}')));
|
||||
return 0;
|
||||
}
|
||||
let [, , file] = args._;
|
||||
if (!file) {
|
||||
try {
|
||||
const packageJson = (await import(path.resolve(process.cwd(), 'package.json')));
|
||||
file = packageJson.main || 'index.js';
|
||||
// eslint-disable-next-line no-empty
|
||||
}
|
||||
catch (err) { }
|
||||
}
|
||||
if (!file) {
|
||||
console.error('Please supply a bot handler file.\n');
|
||||
help();
|
||||
return 2;
|
||||
}
|
||||
if (file[0] !== '/')
|
||||
file = path.resolve(process.cwd(), file);
|
||||
try {
|
||||
if (args.logs)
|
||||
d.enable('telegraf:*');
|
||||
const mod = await import(file);
|
||||
const botHandler = mod.botHandler || mod.default;
|
||||
const httpHandler = mod.httpHandler;
|
||||
const tlsOptions = mod.tlsOptions;
|
||||
const config = {};
|
||||
if (domain) {
|
||||
config.webhook = {
|
||||
domain,
|
||||
host: args.host,
|
||||
port: Number(args.port),
|
||||
tlsOptions,
|
||||
cb: httpHandler,
|
||||
};
|
||||
}
|
||||
bot.use(botHandler);
|
||||
debug(`Starting module ${file}`);
|
||||
await bot.launch(config);
|
||||
}
|
||||
catch (err) {
|
||||
console.error(`Error launching bot from ${file}`, err === null || err === void 0 ? void 0 : err.stack);
|
||||
return 3;
|
||||
}
|
||||
// Enable graceful stop
|
||||
process.once('SIGINT', () => bot.stop('SIGINT'));
|
||||
process.once('SIGTERM', () => bot.stop('SIGTERM'));
|
||||
return 0;
|
||||
}
|
||||
process.exitCode = await main(process.argv, process.env);
|
||||
582
node_modules/telegraf/lib/composer.js
generated
vendored
Normal file
582
node_modules/telegraf/lib/composer.js
generated
vendored
Normal file
@@ -0,0 +1,582 @@
|
||||
"use strict";
|
||||
/** @format */
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Composer = void 0;
|
||||
const context_1 = __importDefault(require("./context"));
|
||||
const filters_1 = require("./filters");
|
||||
const args_1 = require("./core/helpers/args");
|
||||
function always(x) {
|
||||
return () => x;
|
||||
}
|
||||
const anoop = always(Promise.resolve());
|
||||
class Composer {
|
||||
constructor(...fns) {
|
||||
this.handler = Composer.compose(fns);
|
||||
}
|
||||
/**
|
||||
* Registers a middleware.
|
||||
*/
|
||||
use(...fns) {
|
||||
this.handler = Composer.compose([this.handler, ...fns]);
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Registers middleware for handling updates
|
||||
* matching given type guard function.
|
||||
* @deprecated use `Composer::on`
|
||||
*/
|
||||
guard(guardFn, ...fns) {
|
||||
return this.use(Composer.guard(guardFn, ...fns));
|
||||
}
|
||||
on(filters, ...fns) {
|
||||
// @ts-expect-error This should get resolved when the overloads are removed in v5
|
||||
return this.use(Composer.on(filters, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers middleware for handling matching text messages.
|
||||
*/
|
||||
hears(triggers, ...fns) {
|
||||
return this.use(Composer.hears(triggers, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers middleware for handling specified commands.
|
||||
*/
|
||||
command(command, ...fns) {
|
||||
return this.use(Composer.command(command, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers middleware for handling matching callback queries.
|
||||
*/
|
||||
action(triggers, ...fns) {
|
||||
return this.use(Composer.action(triggers, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers middleware for handling matching inline queries.
|
||||
*/
|
||||
inlineQuery(triggers, ...fns) {
|
||||
return this.use(Composer.inlineQuery(triggers, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers middleware for handling game queries
|
||||
*/
|
||||
gameQuery(...fns) {
|
||||
return this.use(Composer.gameQuery(...fns));
|
||||
}
|
||||
reaction(reaction, ...fns) {
|
||||
return this.use(Composer.reaction(reaction, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers middleware for dropping matching updates.
|
||||
*/
|
||||
drop(predicate) {
|
||||
return this.use(Composer.drop(predicate));
|
||||
}
|
||||
/** @deprecated use `Composer::drop` */
|
||||
filter(predicate) {
|
||||
return this.use(Composer.filter(predicate));
|
||||
}
|
||||
entity(predicate, ...fns) {
|
||||
return this.use(Composer.entity(predicate, ...fns));
|
||||
}
|
||||
email(email, ...fns) {
|
||||
return this.use(Composer.email(email, ...fns));
|
||||
}
|
||||
url(url, ...fns) {
|
||||
return this.use(Composer.url(url, ...fns));
|
||||
}
|
||||
textLink(link, ...fns) {
|
||||
return this.use(Composer.textLink(link, ...fns));
|
||||
}
|
||||
textMention(mention, ...fns) {
|
||||
return this.use(Composer.textMention(mention, ...fns));
|
||||
}
|
||||
mention(mention, ...fns) {
|
||||
return this.use(Composer.mention(mention, ...fns));
|
||||
}
|
||||
phone(number, ...fns) {
|
||||
return this.use(Composer.phone(number, ...fns));
|
||||
}
|
||||
hashtag(hashtag, ...fns) {
|
||||
return this.use(Composer.hashtag(hashtag, ...fns));
|
||||
}
|
||||
cashtag(cashtag, ...fns) {
|
||||
return this.use(Composer.cashtag(cashtag, ...fns));
|
||||
}
|
||||
spoiler(text, ...fns) {
|
||||
return this.use(Composer.spoiler(text, ...fns));
|
||||
}
|
||||
/**
|
||||
* Registers a middleware for handling /start
|
||||
*/
|
||||
start(...fns) {
|
||||
const handler = Composer.compose(fns);
|
||||
return this.command('start', (ctx, next) => handler(Object.assign(ctx, { startPayload: ctx.payload }), next));
|
||||
}
|
||||
/**
|
||||
* Registers a middleware for handling /help
|
||||
*/
|
||||
help(...fns) {
|
||||
return this.command('help', ...fns);
|
||||
}
|
||||
/**
|
||||
* Registers a middleware for handling /settings
|
||||
*/
|
||||
settings(...fns) {
|
||||
return this.command('settings', ...fns);
|
||||
}
|
||||
middleware() {
|
||||
return this.handler;
|
||||
}
|
||||
static reply(...args) {
|
||||
return (ctx) => ctx.reply(...args);
|
||||
}
|
||||
static catch(errorHandler, ...fns) {
|
||||
const handler = Composer.compose(fns);
|
||||
// prettier-ignore
|
||||
return (ctx, next) => Promise.resolve(handler(ctx, next))
|
||||
.catch((err) => errorHandler(err, ctx));
|
||||
}
|
||||
/**
|
||||
* Generates middleware that runs in the background.
|
||||
*/
|
||||
static fork(middleware) {
|
||||
const handler = Composer.unwrap(middleware);
|
||||
return async (ctx, next) => {
|
||||
await Promise.all([handler(ctx, anoop), next()]);
|
||||
};
|
||||
}
|
||||
static tap(middleware) {
|
||||
const handler = Composer.unwrap(middleware);
|
||||
return (ctx, next) => Promise.resolve(handler(ctx, anoop)).then(() => next());
|
||||
}
|
||||
/**
|
||||
* Generates middleware that gives up control to the next middleware.
|
||||
*/
|
||||
static passThru() {
|
||||
return (ctx, next) => next();
|
||||
}
|
||||
static lazy(factoryFn) {
|
||||
if (typeof factoryFn !== 'function') {
|
||||
throw new Error('Argument must be a function');
|
||||
}
|
||||
return (ctx, next) => Promise.resolve(factoryFn(ctx)).then((middleware) => Composer.unwrap(middleware)(ctx, next));
|
||||
}
|
||||
static log(logFn = console.log) {
|
||||
return (ctx, next) => {
|
||||
logFn(JSON.stringify(ctx.update, null, 2));
|
||||
return next();
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @param trueMiddleware middleware to run if the predicate returns true
|
||||
* @param falseMiddleware middleware to run if the predicate returns false
|
||||
*/
|
||||
static branch(predicate, trueMiddleware, falseMiddleware) {
|
||||
if (typeof predicate !== 'function') {
|
||||
return Composer.unwrap(predicate ? trueMiddleware : falseMiddleware);
|
||||
}
|
||||
return Composer.lazy((ctx) => Promise.resolve(predicate(ctx)).then((value) => value ? trueMiddleware : falseMiddleware));
|
||||
}
|
||||
/**
|
||||
* Generates optional middleware.
|
||||
* @param predicate predicate to decide on a context object whether to run the middleware
|
||||
* @param fns middleware to run if the predicate returns true
|
||||
*/
|
||||
static optional(predicate, ...fns) {
|
||||
return Composer.branch(predicate, Composer.compose(fns), Composer.passThru());
|
||||
}
|
||||
/** @deprecated use `Composer.drop` */
|
||||
static filter(predicate) {
|
||||
return Composer.branch(predicate, Composer.passThru(), anoop);
|
||||
}
|
||||
/**
|
||||
* Generates middleware for dropping matching updates.
|
||||
*/
|
||||
static drop(predicate) {
|
||||
return Composer.branch(predicate, anoop, Composer.passThru());
|
||||
}
|
||||
static dispatch(routeFn, handlers) {
|
||||
return Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value]));
|
||||
}
|
||||
// EXPLANATION FOR THE ts-expect-error ANNOTATIONS
|
||||
// The annotations around function invocations with `...fns` are there
|
||||
// whenever we perform validation logic that the flow analysis of TypeScript
|
||||
// cannot comprehend. We always make sure that the middleware functions are
|
||||
// only invoked with properly constrained context objects, but this cannot be
|
||||
// determined automatically.
|
||||
/**
|
||||
* Generates optional middleware based on a predicate that only operates on `ctx.update`.
|
||||
*
|
||||
* Example:
|
||||
* ```ts
|
||||
* import { Composer, Update } from 'telegraf'
|
||||
*
|
||||
* const predicate = (u): u is Update.MessageUpdate => 'message' in u
|
||||
* const middleware = Composer.guard(predicate, (ctx) => {
|
||||
* const message = ctx.update.message
|
||||
* })
|
||||
* ```
|
||||
*
|
||||
* Note that `Composer.on('message')` is preferred over this.
|
||||
*
|
||||
* @param guardFn predicate to decide whether to run the middleware based on the `ctx.update` object
|
||||
* @param fns middleware to run if the predicate returns true
|
||||
* @see `Composer.optional` for a more generic version of this method that allows the predicate to operate on `ctx` itself
|
||||
* @deprecated use `Composer.on`
|
||||
*/
|
||||
static guard(guardFn, ...fns) {
|
||||
return Composer.optional((ctx) => guardFn(ctx.update),
|
||||
// @ts-expect-error see explanation above
|
||||
...fns);
|
||||
}
|
||||
static on(updateType, ...fns) {
|
||||
const filters = Array.isArray(updateType) ? updateType : [updateType];
|
||||
const predicate = (update) => {
|
||||
for (const filter of filters) {
|
||||
if (
|
||||
// TODO: this should change to === 'function' once TS bug is fixed
|
||||
// https://github.com/microsoft/TypeScript/pull/51502
|
||||
typeof filter !== 'string'
|
||||
? // filter is a type guard
|
||||
filter(update)
|
||||
: // check if filter is the update type
|
||||
filter in update ||
|
||||
// check if filter is the msg type
|
||||
// TODO: remove in v5!
|
||||
('message' in update && filter in update.message)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return Composer.optional((ctx) => predicate(ctx.update), ...fns);
|
||||
}
|
||||
static entity(predicate, ...fns) {
|
||||
if (typeof predicate !== 'function') {
|
||||
const entityTypes = normaliseTextArguments(predicate);
|
||||
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns);
|
||||
}
|
||||
return Composer.optional((ctx) => {
|
||||
var _a;
|
||||
const msg = (_a = ctx.message) !== null && _a !== void 0 ? _a : ctx.channelPost;
|
||||
if (msg === undefined) {
|
||||
return false;
|
||||
}
|
||||
const text = getText(msg);
|
||||
const entities = getEntities(msg);
|
||||
if (text === undefined)
|
||||
return false;
|
||||
return entities.some((entity) => predicate(entity, text.substring(entity.offset, entity.offset + entity.length), ctx));
|
||||
},
|
||||
// @ts-expect-error see explanation above
|
||||
...fns);
|
||||
}
|
||||
static entityText(entityType, predicate, ...fns) {
|
||||
if (fns.length === 0) {
|
||||
// prettier-ignore
|
||||
return Array.isArray(predicate)
|
||||
// @ts-expect-error predicate is really the middleware
|
||||
? Composer.entity(entityType, ...predicate)
|
||||
// @ts-expect-error predicate is really the middleware
|
||||
: Composer.entity(entityType, predicate);
|
||||
}
|
||||
const triggers = normaliseTriggers(predicate);
|
||||
return Composer.entity(({ type }, value, ctx) => {
|
||||
if (type !== entityType) {
|
||||
return false;
|
||||
}
|
||||
for (const trigger of triggers) {
|
||||
// @ts-expect-error define so far unknown property `match`
|
||||
if ((ctx.match = trigger(value, ctx))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
// @ts-expect-error see explanation above
|
||||
...fns);
|
||||
}
|
||||
static email(email, ...fns) {
|
||||
return Composer.entityText('email', email, ...fns);
|
||||
}
|
||||
static phone(number, ...fns) {
|
||||
return Composer.entityText('phone_number', number, ...fns);
|
||||
}
|
||||
static url(url, ...fns) {
|
||||
return Composer.entityText('url', url, ...fns);
|
||||
}
|
||||
static textLink(link, ...fns) {
|
||||
return Composer.entityText('text_link', link, ...fns);
|
||||
}
|
||||
static textMention(mention, ...fns) {
|
||||
return Composer.entityText('text_mention', mention, ...fns);
|
||||
}
|
||||
static mention(mention, ...fns) {
|
||||
return Composer.entityText('mention', normaliseTextArguments(mention, '@'), ...fns);
|
||||
}
|
||||
static hashtag(hashtag, ...fns) {
|
||||
return Composer.entityText('hashtag', normaliseTextArguments(hashtag, '#'), ...fns);
|
||||
}
|
||||
static cashtag(cashtag, ...fns) {
|
||||
return Composer.entityText('cashtag', normaliseTextArguments(cashtag, '$'), ...fns);
|
||||
}
|
||||
static spoiler(text, ...fns) {
|
||||
return Composer.entityText('spoiler', text, ...fns);
|
||||
}
|
||||
static match(triggers, ...fns) {
|
||||
const handler = Composer.compose(fns);
|
||||
return (ctx, next) => {
|
||||
var _a, _b, _c, _d;
|
||||
const text = (_c = (_b = (_a = getText(ctx.message)) !== null && _a !== void 0 ? _a : getText(ctx.channelPost)) !== null && _b !== void 0 ? _b : getText(ctx.callbackQuery)) !== null && _c !== void 0 ? _c : (_d = ctx.inlineQuery) === null || _d === void 0 ? void 0 : _d.query;
|
||||
if (text === undefined)
|
||||
return next();
|
||||
for (const trigger of triggers) {
|
||||
const match = trigger(text, ctx);
|
||||
if (match)
|
||||
return handler(Object.assign(ctx, { match }), next);
|
||||
}
|
||||
return next();
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Generates middleware for handling matching text messages.
|
||||
*/
|
||||
static hears(triggers, ...fns) {
|
||||
return Composer.on('text', Composer.match(normaliseTriggers(triggers), ...fns));
|
||||
}
|
||||
/**
|
||||
* Generates middleware for handling specified commands.
|
||||
*/
|
||||
static command(command, ...fns) {
|
||||
if (fns.length === 0)
|
||||
// @ts-expect-error command is really the middleware
|
||||
return Composer.entity('bot_command', command);
|
||||
const triggers = normaliseTriggers(command);
|
||||
const filter = (0, filters_1.message)('text');
|
||||
const handler = Composer.compose(fns);
|
||||
return Composer.on(filter, (ctx, next) => {
|
||||
const { entities } = ctx.message;
|
||||
const cmdEntity = entities === null || entities === void 0 ? void 0 : entities[0];
|
||||
if ((cmdEntity === null || cmdEntity === void 0 ? void 0 : cmdEntity.type) !== 'bot_command')
|
||||
return next();
|
||||
if (cmdEntity.offset > 0)
|
||||
return next();
|
||||
const len = cmdEntity.length;
|
||||
const text = ctx.message.text;
|
||||
const [cmdPart, to] = text.slice(0, len).split('@');
|
||||
if (!cmdPart)
|
||||
return next();
|
||||
// always check for bot's own username case-insensitively
|
||||
if (to && to.toLowerCase() !== ctx.me.toLowerCase())
|
||||
return next();
|
||||
const command = cmdPart.slice(1);
|
||||
for (const trigger of triggers) {
|
||||
const match = trigger(command, ctx);
|
||||
if (match) {
|
||||
const payloadOffset = len + 1;
|
||||
const payload = text.slice(payloadOffset);
|
||||
const c = Object.assign(ctx, { match, command, payload, args: [] });
|
||||
let _args = undefined;
|
||||
// using defineProperty only to make parsing lazy on access
|
||||
Object.defineProperty(c, 'args', {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get() {
|
||||
if (_args != null)
|
||||
return _args;
|
||||
// once parsed, cache and don't parse again on every access
|
||||
return (_args = (0, args_1.argsParser)(payload, entities, payloadOffset));
|
||||
},
|
||||
set(args) {
|
||||
_args = args;
|
||||
},
|
||||
});
|
||||
return handler(c, next);
|
||||
}
|
||||
}
|
||||
return next();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Generates middleware for handling matching callback queries.
|
||||
*/
|
||||
static action(triggers, ...fns) {
|
||||
return Composer.on('callback_query', Composer.match(normaliseTriggers(triggers), ...fns));
|
||||
}
|
||||
/**
|
||||
* Generates middleware for handling matching inline queries.
|
||||
*/
|
||||
static inlineQuery(triggers, ...fns) {
|
||||
return Composer.on('inline_query', Composer.match(normaliseTriggers(triggers), ...fns));
|
||||
}
|
||||
static reaction(reaction, ...fns) {
|
||||
const reactions = Array.isArray(reaction) ? reaction : [reaction];
|
||||
const handler = Composer.compose(fns);
|
||||
return Composer.on('message_reaction', (ctx, next) => {
|
||||
const match = reactions.find((r) => typeof r === 'string' && r.startsWith('-')
|
||||
? ctx.reactions.removed.has(r.slice(1))
|
||||
: ctx.reactions.added.has(r));
|
||||
if (match)
|
||||
return handler(Object.assign(ctx, { match }), next);
|
||||
return next();
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Generates middleware responding only to specified users.
|
||||
*/
|
||||
static acl(userId, ...fns) {
|
||||
if (typeof userId === 'function') {
|
||||
return Composer.optional(userId, ...fns);
|
||||
}
|
||||
const allowed = Array.isArray(userId) ? userId : [userId];
|
||||
// prettier-ignore
|
||||
return Composer.optional((ctx) => !ctx.from || allowed.includes(ctx.from.id), ...fns);
|
||||
}
|
||||
static memberStatus(status, ...fns) {
|
||||
const statuses = Array.isArray(status) ? status : [status];
|
||||
return Composer.optional(async (ctx) => {
|
||||
if (ctx.message === undefined)
|
||||
return false;
|
||||
const member = await ctx.getChatMember(ctx.message.from.id);
|
||||
return statuses.includes(member.status);
|
||||
}, ...fns);
|
||||
}
|
||||
/**
|
||||
* Generates middleware responding only to chat admins and chat creator.
|
||||
*/
|
||||
static admin(...fns) {
|
||||
return Composer.memberStatus(['administrator', 'creator'], ...fns);
|
||||
}
|
||||
/**
|
||||
* Generates middleware responding only to chat creator.
|
||||
*/
|
||||
static creator(...fns) {
|
||||
return Composer.memberStatus('creator', ...fns);
|
||||
}
|
||||
/**
|
||||
* Generates middleware running only in specified chat types.
|
||||
*/
|
||||
static chatType(type, ...fns) {
|
||||
const types = Array.isArray(type) ? type : [type];
|
||||
return Composer.optional((ctx) => {
|
||||
const chat = ctx.chat;
|
||||
return chat !== undefined && types.includes(chat.type);
|
||||
}, ...fns);
|
||||
}
|
||||
/**
|
||||
* Generates middleware running only in private chats.
|
||||
*/
|
||||
static privateChat(...fns) {
|
||||
return Composer.chatType('private', ...fns);
|
||||
}
|
||||
/**
|
||||
* Generates middleware running only in groups and supergroups.
|
||||
*/
|
||||
static groupChat(...fns) {
|
||||
return Composer.chatType(['group', 'supergroup'], ...fns);
|
||||
}
|
||||
/**
|
||||
* Generates middleware for handling game queries.
|
||||
*/
|
||||
static gameQuery(...fns) {
|
||||
return Composer.guard((0, filters_1.callbackQuery)('game_short_name'), ...fns);
|
||||
}
|
||||
static unwrap(handler) {
|
||||
if (!handler) {
|
||||
throw new Error('Handler is undefined');
|
||||
}
|
||||
return 'middleware' in handler ? handler.middleware() : handler;
|
||||
}
|
||||
static compose(middlewares) {
|
||||
if (!Array.isArray(middlewares)) {
|
||||
throw new Error('Middlewares must be an array');
|
||||
}
|
||||
if (middlewares.length === 0) {
|
||||
return Composer.passThru();
|
||||
}
|
||||
if (middlewares.length === 1) {
|
||||
// Quite literally asserted in the above condition
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return Composer.unwrap(middlewares[0]);
|
||||
}
|
||||
return (ctx, next) => {
|
||||
let index = -1;
|
||||
return execute(0, ctx);
|
||||
async function execute(i, context) {
|
||||
var _a;
|
||||
if (!(context instanceof context_1.default)) {
|
||||
throw new Error('next(ctx) called with invalid context');
|
||||
}
|
||||
if (i <= index) {
|
||||
throw new Error('next() called multiple times');
|
||||
}
|
||||
index = i;
|
||||
const handler = Composer.unwrap((_a = middlewares[i]) !== null && _a !== void 0 ? _a : next);
|
||||
await handler(context, async (ctx = context) => {
|
||||
await execute(i + 1, ctx);
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
exports.Composer = Composer;
|
||||
/**
|
||||
* Generates middleware for handling provided update types.
|
||||
* @deprecated use `Composer.on` instead
|
||||
*/
|
||||
Composer.mount = Composer.on;
|
||||
function escapeRegExp(s) {
|
||||
// $& means the whole matched string
|
||||
return s.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
function normaliseTriggers(triggers) {
|
||||
if (!Array.isArray(triggers))
|
||||
triggers = [triggers];
|
||||
return triggers.map((trigger) => {
|
||||
if (!trigger)
|
||||
throw new Error('Invalid trigger');
|
||||
if (typeof trigger === 'function')
|
||||
return trigger;
|
||||
if (trigger instanceof RegExp)
|
||||
return (value = '') => {
|
||||
trigger.lastIndex = 0;
|
||||
return trigger.exec(value);
|
||||
};
|
||||
const regex = new RegExp(`^${escapeRegExp(trigger)}$`);
|
||||
return (value) => regex.exec(value);
|
||||
});
|
||||
}
|
||||
function getEntities(msg) {
|
||||
var _a, _b;
|
||||
if (msg == null)
|
||||
return [];
|
||||
if ('caption_entities' in msg)
|
||||
return (_a = msg.caption_entities) !== null && _a !== void 0 ? _a : [];
|
||||
if ('entities' in msg)
|
||||
return (_b = msg.entities) !== null && _b !== void 0 ? _b : [];
|
||||
return [];
|
||||
}
|
||||
function getText(msg) {
|
||||
if (msg == null)
|
||||
return undefined;
|
||||
if ('caption' in msg)
|
||||
return msg.caption;
|
||||
if ('text' in msg)
|
||||
return msg.text;
|
||||
if ('data' in msg)
|
||||
return msg.data;
|
||||
if ('game_short_name' in msg)
|
||||
return msg.game_short_name;
|
||||
return undefined;
|
||||
}
|
||||
function normaliseTextArguments(argument, prefix = '') {
|
||||
const args = Array.isArray(argument) ? argument : [argument];
|
||||
// prettier-ignore
|
||||
return args
|
||||
.filter(Boolean)
|
||||
.map((arg) => prefix && typeof arg === 'string' && !arg.startsWith(prefix) ? `${prefix}${arg}` : arg);
|
||||
}
|
||||
exports.default = Composer;
|
||||
1219
node_modules/telegraf/lib/context.js
generated
vendored
Normal file
1219
node_modules/telegraf/lib/context.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
58
node_modules/telegraf/lib/core/helpers/args.js
generated
vendored
Normal file
58
node_modules/telegraf/lib/core/helpers/args.js
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.argsParser = void 0;
|
||||
const SINGLE_QUOTE = "'";
|
||||
const DOUBLE_QUOTE = '"';
|
||||
function argsParser(str, entities = [], entityOffset = 0) {
|
||||
const mentions = {};
|
||||
for (const entity of entities) // extract all text_mentions into an { offset: length } map
|
||||
if (entity.type === 'text_mention' || entity.type === 'text_link')
|
||||
mentions[entity.offset - entityOffset] = entity.length;
|
||||
const args = [];
|
||||
let done = 0;
|
||||
let inside = undefined;
|
||||
let buf = '';
|
||||
function flush(to) {
|
||||
if (done !== to)
|
||||
args.push(buf + str.slice(done, to)), (inside = undefined);
|
||||
buf = '';
|
||||
done = to + 1;
|
||||
}
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str[i];
|
||||
// quick lookup length of mention starting at i
|
||||
const mention = mentions[i];
|
||||
if (mention) {
|
||||
// if we're inside a quote, eagerly flush existing state
|
||||
flush(i);
|
||||
// this also consumes current index, so decrement
|
||||
done--;
|
||||
// fast forward to end of mention
|
||||
i += mention;
|
||||
flush(i);
|
||||
}
|
||||
else if (char === SINGLE_QUOTE || char === DOUBLE_QUOTE)
|
||||
if (inside)
|
||||
if (inside === char)
|
||||
flush(i);
|
||||
else
|
||||
continue;
|
||||
else
|
||||
flush(i), (inside = char);
|
||||
else if (char === ' ')
|
||||
if (inside)
|
||||
continue;
|
||||
else
|
||||
flush(i);
|
||||
else if (char === '\n')
|
||||
flush(i);
|
||||
else if (char === '\\')
|
||||
(buf += str.slice(done, i)), (done = ++i); // skip parsing the next char
|
||||
else
|
||||
continue;
|
||||
}
|
||||
if (done < str.length)
|
||||
flush(str.length);
|
||||
return args;
|
||||
}
|
||||
exports.argsParser = argsParser;
|
||||
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;
|
||||
17
node_modules/telegraf/lib/core/helpers/compact.js
generated
vendored
Normal file
17
node_modules/telegraf/lib/core/helpers/compact.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.compactOptions = void 0;
|
||||
function compactOptions(options) {
|
||||
if (!options) {
|
||||
return options;
|
||||
}
|
||||
const compacted = {};
|
||||
for (const key in options)
|
||||
if (
|
||||
// todo(mkr): replace with Object.hasOwn in v5 (Node 16+)
|
||||
Object.prototype.hasOwnProperty.call(options, key) &&
|
||||
options[key] !== undefined)
|
||||
compacted[key] = options[key];
|
||||
return compacted;
|
||||
}
|
||||
exports.compactOptions = compactOptions;
|
||||
13
node_modules/telegraf/lib/core/helpers/deunionize.js
generated
vendored
Normal file
13
node_modules/telegraf/lib/core/helpers/deunionize.js
generated
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.deunionize = void 0;
|
||||
/**
|
||||
* Expose properties from all union variants.
|
||||
* @deprectated
|
||||
* @see https://github.com/telegraf/telegraf/issues/1388#issuecomment-791573609
|
||||
* @see https://millsp.github.io/ts-toolbelt/modules/union_strict.html
|
||||
*/
|
||||
function deunionize(t) {
|
||||
return t;
|
||||
}
|
||||
exports.deunionize = deunionize;
|
||||
91
node_modules/telegraf/lib/core/helpers/formatting.js
generated
vendored
Normal file
91
node_modules/telegraf/lib/core/helpers/formatting.js
generated
vendored
Normal file
@@ -0,0 +1,91 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.linkOrMention = exports.createFmt = exports.join = exports.FmtString = void 0;
|
||||
const util_1 = require("./util");
|
||||
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 (content instanceof FmtString)
|
||||
return content;
|
||||
return new FmtString(String(content));
|
||||
}
|
||||
}
|
||||
exports.FmtString = FmtString;
|
||||
const isArray = Array.isArray;
|
||||
/** Given a base FmtString and something to append to it, mutates the base */
|
||||
const _add = (base, next) => {
|
||||
var _a;
|
||||
const len = base.text.length;
|
||||
if (next instanceof FmtString) {
|
||||
base.text = `${base.text}${next.text}`;
|
||||
// next.entities could be undefined and condition will fail
|
||||
for (let i = 0; i < (((_a = next.entities) === null || _a === void 0 ? void 0 : _a.length) || 0); i++) {
|
||||
// because of the above condition, next.entities[i] cannot be undefined
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const entity = next.entities[i];
|
||||
// base.entities is ensured by caller
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
base.entities.push({ ...entity, offset: entity.offset + len });
|
||||
}
|
||||
}
|
||||
else
|
||||
base.text = `${base.text}${next}`;
|
||||
};
|
||||
/**
|
||||
* Given an `Iterable<FmtString | string | Any>` and a separator, flattens the list into a single FmtString.
|
||||
* Analogous to Array#join -> string, but for FmtString
|
||||
*/
|
||||
const join = (fragments, separator) => {
|
||||
const result = new FmtString('');
|
||||
// ensure entities array so loop doesn't need to check
|
||||
result.entities = [];
|
||||
const iter = fragments[Symbol.iterator]();
|
||||
let curr = iter.next();
|
||||
while (!curr.done) {
|
||||
_add(result, curr.value);
|
||||
curr = iter.next();
|
||||
if (separator && !curr.done)
|
||||
_add(result, separator);
|
||||
}
|
||||
// set parse_mode: undefined if entities are present
|
||||
if (result.entities.length)
|
||||
result.parse_mode = undefined;
|
||||
// remove entities array if not relevant
|
||||
else
|
||||
delete result.entities;
|
||||
return result;
|
||||
};
|
||||
exports.join = join;
|
||||
/** Internal constructor for all fmt helpers */
|
||||
function createFmt(kind, opts) {
|
||||
return function fmt(parts, ...items) {
|
||||
var _a;
|
||||
parts = isArray(parts) ? parts : [parts];
|
||||
const result = (0, exports.join)((0, util_1.zip)(parts, items));
|
||||
if (kind) {
|
||||
(_a = result.entities) !== null && _a !== void 0 ? _a : (result.entities = []);
|
||||
result.entities.unshift({
|
||||
type: kind,
|
||||
offset: 0,
|
||||
length: result.text.length,
|
||||
...opts,
|
||||
});
|
||||
result.parse_mode = undefined;
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
exports.createFmt = createFmt;
|
||||
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;
|
||||
50
node_modules/telegraf/lib/core/helpers/util.js
generated
vendored
Normal file
50
node_modules/telegraf/lib/core/helpers/util.js
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.indexed = exports.zip = exports.fmtCaption = exports.env = void 0;
|
||||
exports.env = process.env;
|
||||
function fmtCaption(extra) {
|
||||
if (!extra)
|
||||
return;
|
||||
const caption = extra.caption;
|
||||
if (!caption || typeof caption === 'string')
|
||||
return extra;
|
||||
const { text, entities } = caption;
|
||||
return {
|
||||
...extra,
|
||||
caption: text,
|
||||
...(entities && {
|
||||
caption_entities: entities,
|
||||
parse_mode: undefined,
|
||||
}),
|
||||
};
|
||||
}
|
||||
exports.fmtCaption = fmtCaption;
|
||||
function* zip(xs, ys) {
|
||||
const x = xs[Symbol.iterator]();
|
||||
const y = ys[Symbol.iterator]();
|
||||
let x1 = x.next();
|
||||
let y1 = y.next();
|
||||
while (!x1.done) {
|
||||
yield x1.value;
|
||||
if (!y1.done)
|
||||
yield y1.value;
|
||||
x1 = x.next();
|
||||
y1 = y.next();
|
||||
}
|
||||
while (!y1.done) {
|
||||
yield y1.value;
|
||||
y1 = y.next();
|
||||
}
|
||||
}
|
||||
exports.zip = zip;
|
||||
function indexed(target, indexer) {
|
||||
return new Proxy(target, {
|
||||
get: function (target, prop, receiver) {
|
||||
if ((typeof prop === 'string' || typeof prop === 'number') &&
|
||||
!isNaN(+prop))
|
||||
return indexer.call(target, +prop);
|
||||
return Reflect.get(target, prop, receiver);
|
||||
},
|
||||
});
|
||||
}
|
||||
exports.indexed = indexed;
|
||||
320
node_modules/telegraf/lib/core/network/client.js
generated
vendored
Normal file
320
node_modules/telegraf/lib/core/network/client.js
generated
vendored
Normal file
@@ -0,0 +1,320 @@
|
||||
"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 promises_1 = require("fs/promises");
|
||||
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.entries(payload).some(([key, value]) => {
|
||||
if (key === 'link_preview_options')
|
||||
return false;
|
||||
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);
|
||||
await Promise.all(Object.keys(payload).map((key) =>
|
||||
// @ts-expect-error payload[key] can obviously index payload, but TS doesn't trust us
|
||||
attachFormValue(formData, key, payload[key], agent)));
|
||||
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' || id === 'thumbnail') {
|
||||
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) => {
|
||||
var _a;
|
||||
if (typeof item.media !== 'object') {
|
||||
return await Promise.resolve(item);
|
||||
}
|
||||
const attachmentId = crypto.randomBytes(16).toString('hex');
|
||||
await attachFormMedia(form, item.media, attachmentId, agent);
|
||||
const thumb = (_a = item.thumb) !== null && _a !== void 0 ? _a : item.thumbnail;
|
||||
if (typeof thumb === 'object') {
|
||||
const thumbAttachmentId = crypto.randomBytes(16).toString('hex');
|
||||
await attachFormMedia(form, thumb, thumbAttachmentId, agent);
|
||||
return {
|
||||
...item,
|
||||
media: `attach://${attachmentId}`,
|
||||
thumbnail: `attach://${thumbAttachmentId}`,
|
||||
};
|
||||
}
|
||||
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 ('url' in media && media.url !== undefined) {
|
||||
const timeout = 500000; // ms
|
||||
const res = await (0, node_fetch_1.default)(media.url, { agent, timeout });
|
||||
return form.addPart({
|
||||
headers: {
|
||||
'content-disposition': `form-data; name="${id}"; filename="${fileName}"`,
|
||||
},
|
||||
body: res.body,
|
||||
});
|
||||
}
|
||||
if ('source' in media && media.source) {
|
||||
let mediaSource = media.source;
|
||||
if (typeof media.source === 'string') {
|
||||
const source = await (0, promises_1.realpath)(media.source);
|
||||
if ((await (0, promises_1.stat)(source)).isFile()) {
|
||||
fileName = (_c = media.filename) !== null && _c !== void 0 ? _c : path.basename(media.source);
|
||||
mediaSource = await fs.createReadStream(media.source);
|
||||
}
|
||||
else {
|
||||
throw new TypeError(`Unable to upload '${media.source}', not a file`);
|
||||
}
|
||||
}
|
||||
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;
|
||||
// @ts-expect-error AbortSignal shim is missing some props from Request.AbortSignal
|
||||
config.signal = signal;
|
||||
config.timeout = 500000; // ms
|
||||
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;
|
||||
87
node_modules/telegraf/lib/core/network/polling.js
generated
vendored
Normal file
87
node_modules/telegraf/lib/core/network/polling.js
generated
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
"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;
|
||||
27
node_modules/telegraf/lib/core/types/typegram.js
generated
vendored
Normal file
27
node_modules/telegraf/lib/core/types/typegram.js
generated
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
"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("@telegraf/types/api"), exports);
|
||||
__exportStar(require("@telegraf/types/inline"), exports);
|
||||
__exportStar(require("@telegraf/types/manage"), exports);
|
||||
__exportStar(require("@telegraf/types/markup"), exports);
|
||||
__exportStar(require("@telegraf/types/message"), exports);
|
||||
__exportStar(require("@telegraf/types/methods"), exports);
|
||||
__exportStar(require("@telegraf/types/passport"), exports);
|
||||
__exportStar(require("@telegraf/types/payment"), exports);
|
||||
__exportStar(require("@telegraf/types/settings"), exports);
|
||||
__exportStar(require("@telegraf/types/update"), exports);
|
||||
69
node_modules/telegraf/lib/filters.js
generated
vendored
Normal file
69
node_modules/telegraf/lib/filters.js
generated
vendored
Normal file
@@ -0,0 +1,69 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.allOf = exports.anyOf = exports.callbackQuery = exports.editedChannelPost = exports.channelPost = exports.editedMessage = exports.message = void 0;
|
||||
const message = (...keys) => (update) => {
|
||||
if (!('message' in update))
|
||||
return false;
|
||||
for (const key of keys) {
|
||||
if (!(key in update.message))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
exports.message = message;
|
||||
const editedMessage = (...keys) => (update) => {
|
||||
if (!('edited_message' in update))
|
||||
return false;
|
||||
for (const key of keys) {
|
||||
if (!(key in update.edited_message))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
exports.editedMessage = editedMessage;
|
||||
const channelPost = (...keys) => (update) => {
|
||||
if (!('channel_post' in update))
|
||||
return false;
|
||||
for (const key of keys) {
|
||||
if (!(key in update.channel_post))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
exports.channelPost = channelPost;
|
||||
const editedChannelPost = (...keys) => (update) => {
|
||||
if (!('edited_channel_post' in update))
|
||||
return false;
|
||||
for (const key of keys) {
|
||||
if (!(key in update.edited_channel_post))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
exports.editedChannelPost = editedChannelPost;
|
||||
const callbackQuery = (...keys) => (update) => {
|
||||
if (!('callback_query' in update))
|
||||
return false;
|
||||
for (const key of keys) {
|
||||
if (!(key in update.callback_query))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
exports.callbackQuery = callbackQuery;
|
||||
/** Any of the provided filters must match */
|
||||
const anyOf = (...filters) => (update) => {
|
||||
for (const filter of filters)
|
||||
if (filter(update))
|
||||
return true;
|
||||
return false;
|
||||
};
|
||||
exports.anyOf = anyOf;
|
||||
/** All of the provided filters must match */
|
||||
const allOf = (...filters) => (update) => {
|
||||
for (const filter of filters)
|
||||
if (!filter(update))
|
||||
return false;
|
||||
return true;
|
||||
};
|
||||
exports.allOf = allOf;
|
||||
38
node_modules/telegraf/lib/format.js
generated
vendored
Normal file
38
node_modules/telegraf/lib/format.js
generated
vendored
Normal file
@@ -0,0 +1,38 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.mention = exports.link = exports.pre = exports.code = exports.quote = exports.underline = exports.strikethrough = exports.spoiler = exports.italic = exports.bold = exports.fmt = exports.join = exports.FmtString = void 0;
|
||||
const formatting_1 = require("./core/helpers/formatting");
|
||||
Object.defineProperty(exports, "FmtString", { enumerable: true, get: function () { return formatting_1.FmtString; } });
|
||||
// Nests<A, B> means the function will return A, and it can nest B
|
||||
// Nests<'fmt', string> means it will nest anything
|
||||
// Nests<'code', never> means it will not nest anything
|
||||
// Allowing everything to nest 'fmt' is a necessary evil; it allows to indirectly nest illegal entities
|
||||
// Except for 'code' and 'pre', which don't nest anything anyway, so they only deal with strings
|
||||
exports.join = formatting_1.join;
|
||||
exports.fmt = (0, formatting_1.createFmt)();
|
||||
exports.bold = (0, formatting_1.createFmt)('bold');
|
||||
exports.italic = (0, formatting_1.createFmt)('italic');
|
||||
exports.spoiler = (0, formatting_1.createFmt)('spoiler');
|
||||
exports.strikethrough =
|
||||
//
|
||||
(0, formatting_1.createFmt)('strikethrough');
|
||||
exports.underline =
|
||||
//
|
||||
(0, formatting_1.createFmt)('underline');
|
||||
exports.quote =
|
||||
//
|
||||
(0, formatting_1.createFmt)('blockquote');
|
||||
exports.code = (0, formatting_1.createFmt)('code');
|
||||
const pre = (language) => (0, formatting_1.createFmt)('pre', { language });
|
||||
exports.pre = pre;
|
||||
const link = (content, url) =>
|
||||
//
|
||||
(0, formatting_1.linkOrMention)(content, { type: 'text_link', url });
|
||||
exports.link = link;
|
||||
const mention = (name, user) => typeof user === 'number'
|
||||
? (0, exports.link)(name, 'tg://user?id=' + user)
|
||||
: (0, formatting_1.linkOrMention)(name, {
|
||||
type: 'text_mention',
|
||||
user,
|
||||
});
|
||||
exports.mention = mention;
|
||||
150
node_modules/telegraf/lib/future.js
generated
vendored
Normal file
150
node_modules/telegraf/lib/future.js
generated
vendored
Normal file
@@ -0,0 +1,150 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.useNewReplies = void 0;
|
||||
function makeReply(ctx, extra) {
|
||||
if (ctx.msgId)
|
||||
return {
|
||||
// overrides in this order so user can override all properties
|
||||
reply_parameters: {
|
||||
message_id: ctx.msgId,
|
||||
...extra === null || extra === void 0 ? void 0 : extra.reply_parameters,
|
||||
},
|
||||
...extra,
|
||||
};
|
||||
else
|
||||
return extra;
|
||||
}
|
||||
const replyContext = {
|
||||
replyWithChatAction: function () {
|
||||
throw new TypeError('ctx.replyWithChatAction has been removed, use ctx.sendChatAction instead');
|
||||
},
|
||||
reply(text, extra) {
|
||||
this.assert(this.chat, 'reply');
|
||||
return this.telegram.sendMessage(this.chat.id, text, makeReply(this, extra));
|
||||
},
|
||||
replyWithAnimation(animation, extra) {
|
||||
this.assert(this.chat, 'replyWithAnimation');
|
||||
return this.telegram.sendAnimation(this.chat.id, animation, makeReply(this, extra));
|
||||
},
|
||||
replyWithAudio(audio, extra) {
|
||||
this.assert(this.chat, 'replyWithAudio');
|
||||
return this.telegram.sendAudio(this.chat.id, audio, makeReply(this, extra));
|
||||
},
|
||||
replyWithContact(phoneNumber, firstName, extra) {
|
||||
this.assert(this.chat, 'replyWithContact');
|
||||
return this.telegram.sendContact(this.chat.id, phoneNumber, firstName, makeReply(this, extra));
|
||||
},
|
||||
replyWithDice(extra) {
|
||||
this.assert(this.chat, 'replyWithDice');
|
||||
return this.telegram.sendDice(this.chat.id, makeReply(this, extra));
|
||||
},
|
||||
replyWithDocument(document, extra) {
|
||||
this.assert(this.chat, 'replyWithDocument');
|
||||
return this.telegram.sendDocument(this.chat.id, document, makeReply(this, extra));
|
||||
},
|
||||
replyWithGame(gameName, extra) {
|
||||
this.assert(this.chat, 'replyWithGame');
|
||||
return this.telegram.sendGame(this.chat.id, gameName, makeReply(this, extra));
|
||||
},
|
||||
replyWithHTML(html, extra) {
|
||||
this.assert(this.chat, 'replyWithHTML');
|
||||
return this.telegram.sendMessage(this.chat.id, html, {
|
||||
parse_mode: 'HTML',
|
||||
...makeReply(this, extra),
|
||||
});
|
||||
},
|
||||
replyWithInvoice(invoice, extra) {
|
||||
this.assert(this.chat, 'replyWithInvoice');
|
||||
return this.telegram.sendInvoice(this.chat.id, invoice, makeReply(this, extra));
|
||||
},
|
||||
replyWithLocation(latitude, longitude, extra) {
|
||||
this.assert(this.chat, 'replyWithLocation');
|
||||
return this.telegram.sendLocation(this.chat.id, latitude, longitude, makeReply(this, extra));
|
||||
},
|
||||
replyWithMarkdown(markdown, extra) {
|
||||
this.assert(this.chat, 'replyWithMarkdown');
|
||||
return this.telegram.sendMessage(this.chat.id, markdown, {
|
||||
parse_mode: 'Markdown',
|
||||
...makeReply(this, extra),
|
||||
});
|
||||
},
|
||||
replyWithMarkdownV2(markdown, extra) {
|
||||
this.assert(this.chat, 'replyWithMarkdownV2');
|
||||
return this.telegram.sendMessage(this.chat.id, markdown, {
|
||||
parse_mode: 'MarkdownV2',
|
||||
...makeReply(this, extra),
|
||||
});
|
||||
},
|
||||
replyWithMediaGroup(media, extra) {
|
||||
this.assert(this.chat, 'replyWithMediaGroup');
|
||||
return this.telegram.sendMediaGroup(this.chat.id, media, makeReply(this, extra));
|
||||
},
|
||||
replyWithPhoto(photo, extra) {
|
||||
this.assert(this.chat, 'replyWithPhoto');
|
||||
return this.telegram.sendPhoto(this.chat.id, photo, makeReply(this, extra));
|
||||
},
|
||||
replyWithPoll(question, options, extra) {
|
||||
this.assert(this.chat, 'replyWithPoll');
|
||||
return this.telegram.sendPoll(this.chat.id, question, options, makeReply(this, extra));
|
||||
},
|
||||
replyWithQuiz(question, options, extra) {
|
||||
this.assert(this.chat, 'replyWithQuiz');
|
||||
return this.telegram.sendQuiz(this.chat.id, question, options, makeReply(this, extra));
|
||||
},
|
||||
replyWithSticker(sticker, extra) {
|
||||
this.assert(this.chat, 'replyWithSticker');
|
||||
return this.telegram.sendSticker(this.chat.id, sticker, makeReply(this, extra));
|
||||
},
|
||||
replyWithVenue(latitude, longitude, title, address, extra) {
|
||||
this.assert(this.chat, 'replyWithVenue');
|
||||
return this.telegram.sendVenue(this.chat.id, latitude, longitude, title, address, makeReply(this, extra));
|
||||
},
|
||||
replyWithVideo(video, extra) {
|
||||
this.assert(this.chat, 'replyWithVideo');
|
||||
return this.telegram.sendVideo(this.chat.id, video, makeReply(this, extra));
|
||||
},
|
||||
replyWithVideoNote(videoNote, extra) {
|
||||
this.assert(this.chat, 'replyWithVideoNote');
|
||||
return this.telegram.sendVideoNote(this.chat.id, videoNote, makeReply(this, extra));
|
||||
},
|
||||
replyWithVoice(voice, extra) {
|
||||
this.assert(this.chat, 'replyWithVoice');
|
||||
return this.telegram.sendVoice(this.chat.id, voice, makeReply(this, extra));
|
||||
},
|
||||
};
|
||||
/**
|
||||
* Sets up Context to use the new reply methods.
|
||||
* This middleware makes `ctx.reply()` and `ctx.replyWith*()` methods will actually reply to the message they are replying to.
|
||||
* Use `ctx.sendMessage()` to send a message in chat without replying to it.
|
||||
*
|
||||
* If the message to reply is deleted, `reply()` will send a normal message.
|
||||
* If the update is not a message and we are unable to reply, `reply()` will send a normal message.
|
||||
*/
|
||||
function useNewReplies() {
|
||||
return (ctx, next) => {
|
||||
ctx.reply = replyContext.reply;
|
||||
ctx.replyWithPhoto = replyContext.replyWithPhoto;
|
||||
ctx.replyWithMediaGroup = replyContext.replyWithMediaGroup;
|
||||
ctx.replyWithAudio = replyContext.replyWithAudio;
|
||||
ctx.replyWithDice = replyContext.replyWithDice;
|
||||
ctx.replyWithDocument = replyContext.replyWithDocument;
|
||||
ctx.replyWithSticker = replyContext.replyWithSticker;
|
||||
ctx.replyWithVideo = replyContext.replyWithVideo;
|
||||
ctx.replyWithAnimation = replyContext.replyWithAnimation;
|
||||
ctx.replyWithVideoNote = replyContext.replyWithVideoNote;
|
||||
ctx.replyWithInvoice = replyContext.replyWithInvoice;
|
||||
ctx.replyWithGame = replyContext.replyWithGame;
|
||||
ctx.replyWithVoice = replyContext.replyWithVoice;
|
||||
ctx.replyWithPoll = replyContext.replyWithPoll;
|
||||
ctx.replyWithQuiz = replyContext.replyWithQuiz;
|
||||
ctx.replyWithChatAction = replyContext.replyWithChatAction;
|
||||
ctx.replyWithLocation = replyContext.replyWithLocation;
|
||||
ctx.replyWithVenue = replyContext.replyWithVenue;
|
||||
ctx.replyWithContact = replyContext.replyWithContact;
|
||||
ctx.replyWithMarkdown = replyContext.replyWithMarkdown;
|
||||
ctx.replyWithMarkdownV2 = replyContext.replyWithMarkdownV2;
|
||||
ctx.replyWithHTML = replyContext.replyWithHTML;
|
||||
return next();
|
||||
};
|
||||
}
|
||||
exports.useNewReplies = useNewReplies;
|
||||
48
node_modules/telegraf/lib/index.js
generated
vendored
Normal file
48
node_modules/telegraf/lib/index.js
generated
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
"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;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Scenes = exports.MemorySessionStore = exports.session = exports.deunionize = exports.Format = exports.Input = exports.Markup = exports.Types = exports.Telegram = exports.TelegramError = exports.Router = exports.Composer = exports.Context = exports.Telegraf = void 0;
|
||||
var telegraf_1 = require("./telegraf");
|
||||
Object.defineProperty(exports, "Telegraf", { enumerable: true, get: function () { return telegraf_1.Telegraf; } });
|
||||
var context_1 = require("./context");
|
||||
Object.defineProperty(exports, "Context", { enumerable: true, get: function () { return context_1.Context; } });
|
||||
var composer_1 = require("./composer");
|
||||
Object.defineProperty(exports, "Composer", { enumerable: true, get: function () { return composer_1.Composer; } });
|
||||
var router_1 = require("./router");
|
||||
Object.defineProperty(exports, "Router", { enumerable: true, get: function () { return router_1.Router; } });
|
||||
var error_1 = require("./core/network/error");
|
||||
Object.defineProperty(exports, "TelegramError", { enumerable: true, get: function () { return error_1.TelegramError; } });
|
||||
var telegram_1 = require("./telegram");
|
||||
Object.defineProperty(exports, "Telegram", { enumerable: true, get: function () { return telegram_1.Telegram; } });
|
||||
exports.Types = __importStar(require("./telegram-types"));
|
||||
exports.Markup = __importStar(require("./markup"));
|
||||
exports.Input = __importStar(require("./input"));
|
||||
exports.Format = __importStar(require("./format"));
|
||||
var deunionize_1 = require("./core/helpers/deunionize");
|
||||
Object.defineProperty(exports, "deunionize", { enumerable: true, get: function () { return deunionize_1.deunionize; } });
|
||||
var session_1 = require("./session");
|
||||
Object.defineProperty(exports, "session", { enumerable: true, get: function () { return session_1.session; } });
|
||||
Object.defineProperty(exports, "MemorySessionStore", { enumerable: true, get: function () { return session_1.MemorySessionStore; } });
|
||||
exports.Scenes = __importStar(require("./scenes"));
|
||||
61
node_modules/telegraf/lib/input.js
generated
vendored
Normal file
61
node_modules/telegraf/lib/input.js
generated
vendored
Normal file
@@ -0,0 +1,61 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.fromFileId = exports.fromURL = exports.fromURLStream = exports.fromReadableStream = exports.fromBuffer = exports.fromLocalFile = void 0;
|
||||
/**
|
||||
* The local file specified by path will be uploaded to Telegram using multipart/form-data.
|
||||
*
|
||||
* 10 MB max size for photos, 50 MB for other files.
|
||||
*/
|
||||
// prettier-ignore
|
||||
const fromLocalFile = (path, filename) => ({ source: path, filename });
|
||||
exports.fromLocalFile = fromLocalFile;
|
||||
/**
|
||||
* The buffer will be uploaded as file to Telegram using multipart/form-data.
|
||||
*
|
||||
* 10 MB max size for photos, 50 MB for other files.
|
||||
*/
|
||||
// prettier-ignore
|
||||
const fromBuffer = (buffer, filename) => ({ source: buffer, filename });
|
||||
exports.fromBuffer = fromBuffer;
|
||||
/**
|
||||
* Contents of the stream will be uploaded as file to Telegram using multipart/form-data.
|
||||
*
|
||||
* 10 MB max size for photos, 50 MB for other files.
|
||||
*/
|
||||
// prettier-ignore
|
||||
const fromReadableStream = (stream, filename) => ({ source: stream, filename });
|
||||
exports.fromReadableStream = fromReadableStream;
|
||||
/**
|
||||
* Contents of the URL will be streamed to Telegram.
|
||||
*
|
||||
* 10 MB max size for photos, 50 MB for other files.
|
||||
*/
|
||||
// prettier-ignore
|
||||
const fromURLStream = (url, filename) => ({ url: url.toString(), filename });
|
||||
exports.fromURLStream = fromURLStream;
|
||||
/**
|
||||
* Provide Telegram with an HTTP URL for the file to be sent.
|
||||
* Telegram will download and send the file.
|
||||
*
|
||||
* * The target file must have the correct MIME type (e.g., audio/mpeg for `sendAudio`, etc.).
|
||||
* * `sendDocument` with URL will currently only work for GIF, PDF and ZIP files.
|
||||
* * To use `sendVoice`, the file must have the type audio/ogg and be no more than 1MB in size.
|
||||
* 1-20MB voice notes will be sent as files.
|
||||
*
|
||||
* 5 MB max size for photos and 20 MB max for other types of content.
|
||||
*/
|
||||
const fromURL = (url) => url.toString();
|
||||
exports.fromURL = fromURL;
|
||||
/**
|
||||
* If the file is already stored somewhere on the Telegram servers, you don't need to reupload it:
|
||||
* each file object has a file_id field, simply pass this file_id as a parameter instead of uploading.
|
||||
*
|
||||
* It is not possible to change the file type when resending by file_id.
|
||||
*
|
||||
* It is not possible to resend thumbnails using file_id.
|
||||
* They have to be uploaded using one of the other Input methods.
|
||||
*
|
||||
* There are no limits for files sent this way.
|
||||
*/
|
||||
const fromFileId = (fileId) => fileId;
|
||||
exports.fromFileId = fromFileId;
|
||||
111
node_modules/telegraf/lib/markup.js
generated
vendored
Normal file
111
node_modules/telegraf/lib/markup.js
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
"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;
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.inlineKeyboard = exports.keyboard = exports.forceReply = exports.removeKeyboard = exports.button = exports.Markup = void 0;
|
||||
const check_1 = require("./core/helpers/check");
|
||||
class Markup {
|
||||
constructor(reply_markup) {
|
||||
this.reply_markup = reply_markup;
|
||||
}
|
||||
selective(value = true) {
|
||||
return new Markup({ ...this.reply_markup, selective: value });
|
||||
}
|
||||
placeholder(placeholder) {
|
||||
return new Markup({
|
||||
...this.reply_markup,
|
||||
input_field_placeholder: placeholder,
|
||||
});
|
||||
}
|
||||
resize(value = true) {
|
||||
return new Markup({
|
||||
...this.reply_markup,
|
||||
resize_keyboard: value,
|
||||
});
|
||||
}
|
||||
oneTime(value = true) {
|
||||
return new Markup({
|
||||
...this.reply_markup,
|
||||
one_time_keyboard: value,
|
||||
});
|
||||
}
|
||||
persistent(value = true) {
|
||||
return new Markup({
|
||||
...this.reply_markup,
|
||||
is_persistent: value,
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Markup = Markup;
|
||||
exports.button = __importStar(require("./button"));
|
||||
function removeKeyboard() {
|
||||
return new Markup({ remove_keyboard: true });
|
||||
}
|
||||
exports.removeKeyboard = removeKeyboard;
|
||||
function forceReply() {
|
||||
return new Markup({ force_reply: true });
|
||||
}
|
||||
exports.forceReply = forceReply;
|
||||
function keyboard(buttons, options) {
|
||||
const keyboard = buildKeyboard(buttons, {
|
||||
columns: 1,
|
||||
...options,
|
||||
});
|
||||
return new Markup({ keyboard });
|
||||
}
|
||||
exports.keyboard = keyboard;
|
||||
function inlineKeyboard(buttons, options) {
|
||||
const inlineKeyboard = buildKeyboard(buttons, {
|
||||
columns: buttons.length,
|
||||
...options,
|
||||
});
|
||||
return new Markup({ inline_keyboard: inlineKeyboard });
|
||||
}
|
||||
exports.inlineKeyboard = inlineKeyboard;
|
||||
function buildKeyboard(buttons, options) {
|
||||
const result = [];
|
||||
if (!Array.isArray(buttons)) {
|
||||
return result;
|
||||
}
|
||||
if ((0, check_1.is2D)(buttons)) {
|
||||
return buttons.map((row) => row.filter((button) => !button.hide));
|
||||
}
|
||||
const wrapFn = options.wrap !== undefined
|
||||
? options.wrap
|
||||
: (_btn, _index, currentRow) => currentRow.length >= options.columns;
|
||||
let currentRow = [];
|
||||
let index = 0;
|
||||
for (const btn of buttons.filter((button) => !button.hide)) {
|
||||
if (wrapFn(btn, index, currentRow) && currentRow.length > 0) {
|
||||
result.push(currentRow);
|
||||
currentRow = [];
|
||||
}
|
||||
currentRow.push(btn);
|
||||
index++;
|
||||
}
|
||||
if (currentRow.length > 0) {
|
||||
result.push(currentRow);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
2
node_modules/telegraf/lib/middleware.js
generated
vendored
Normal file
2
node_modules/telegraf/lib/middleware.js
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
84
node_modules/telegraf/lib/reactions.js
generated
vendored
Normal file
84
node_modules/telegraf/lib/reactions.js
generated
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.MessageReactions = exports.ReactionList = exports.Digit = void 0;
|
||||
const util_1 = require("./core/helpers/util");
|
||||
exports.Digit = new Set(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']);
|
||||
const inspectReaction = (reaction) => {
|
||||
if (reaction.type === 'custom_emoji')
|
||||
return `Custom(${reaction.custom_emoji_id})`;
|
||||
else
|
||||
return reaction.emoji;
|
||||
};
|
||||
class ReactionList {
|
||||
constructor(list) {
|
||||
this.list = list;
|
||||
}
|
||||
static fromArray(list = []) {
|
||||
return (0, util_1.indexed)(new ReactionList(list), function (index) {
|
||||
return this.list[index];
|
||||
});
|
||||
}
|
||||
static has(reactions, reaction) {
|
||||
if (typeof reaction === 'string')
|
||||
if (exports.Digit.has(reaction[0]))
|
||||
return reactions.some((r) => r.custom_emoji_id === reaction);
|
||||
else
|
||||
return reactions.some((r) => r.emoji === reaction);
|
||||
return reactions.some((r) => {
|
||||
if (r.type === 'custom_emoji')
|
||||
return r.custom_emoji_id === reaction.custom_emoji_id;
|
||||
else if (r.type === 'emoji')
|
||||
return r.emoji === reaction.emoji;
|
||||
});
|
||||
}
|
||||
toArray() {
|
||||
return [...this.list];
|
||||
}
|
||||
filter(filterFn) {
|
||||
return ReactionList.fromArray(this.list.filter(filterFn));
|
||||
}
|
||||
has(reaction) {
|
||||
return ReactionList.has(this.list, reaction);
|
||||
}
|
||||
get count() {
|
||||
return this.list.length;
|
||||
}
|
||||
[Symbol.iterator]() {
|
||||
return this.list[Symbol.iterator]();
|
||||
}
|
||||
[Symbol.for('nodejs.util.inspect.custom')]() {
|
||||
const flattened = this.list.map(inspectReaction).join(', ');
|
||||
return ['ReactionList {', flattened, '}'].join(' ');
|
||||
}
|
||||
}
|
||||
exports.ReactionList = ReactionList;
|
||||
class MessageReactions extends ReactionList {
|
||||
constructor(ctx) {
|
||||
var _a, _b;
|
||||
super((_b = (_a = ctx.update.message_reaction) === null || _a === void 0 ? void 0 : _a.new_reaction) !== null && _b !== void 0 ? _b : []);
|
||||
this.ctx = ctx;
|
||||
}
|
||||
static from(ctx) {
|
||||
return (0, util_1.indexed)(new MessageReactions(ctx), function (index) {
|
||||
return this.list[index];
|
||||
});
|
||||
}
|
||||
get old() {
|
||||
var _a;
|
||||
return ReactionList.fromArray((_a = this.ctx.update.message_reaction) === null || _a === void 0 ? void 0 : _a.old_reaction);
|
||||
}
|
||||
get new() {
|
||||
var _a;
|
||||
return ReactionList.fromArray((_a = this.ctx.update.message_reaction) === null || _a === void 0 ? void 0 : _a.new_reaction);
|
||||
}
|
||||
get added() {
|
||||
return this.new.filter((reaction) => !this.old.has(reaction));
|
||||
}
|
||||
get removed() {
|
||||
return this.old.filter((reaction) => !this.new.has(reaction));
|
||||
}
|
||||
get kept() {
|
||||
return this.new.filter((reaction) => this.old.has(reaction));
|
||||
}
|
||||
}
|
||||
exports.MessageReactions = MessageReactions;
|
||||
46
node_modules/telegraf/lib/router.js
generated
vendored
Normal file
46
node_modules/telegraf/lib/router.js
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
"use strict";
|
||||
/** @format */
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Router = void 0;
|
||||
const composer_1 = __importDefault(require("./composer"));
|
||||
/** @deprecated in favor of {@link Composer.dispatch} */
|
||||
class Router {
|
||||
constructor(routeFn, handlers = new Map()) {
|
||||
this.routeFn = routeFn;
|
||||
this.handlers = handlers;
|
||||
this.otherwiseHandler = composer_1.default.passThru();
|
||||
if (typeof routeFn !== 'function') {
|
||||
throw new Error('Missing routing function');
|
||||
}
|
||||
}
|
||||
on(route, ...fns) {
|
||||
if (fns.length === 0) {
|
||||
throw new TypeError('At least one handler must be provided');
|
||||
}
|
||||
this.handlers.set(route, composer_1.default.compose(fns));
|
||||
return this;
|
||||
}
|
||||
otherwise(...fns) {
|
||||
if (fns.length === 0) {
|
||||
throw new TypeError('At least one otherwise handler must be provided');
|
||||
}
|
||||
this.otherwiseHandler = composer_1.default.compose(fns);
|
||||
return this;
|
||||
}
|
||||
middleware() {
|
||||
return composer_1.default.lazy((ctx) => {
|
||||
var _a;
|
||||
const result = this.routeFn(ctx);
|
||||
if (result == null) {
|
||||
return this.otherwiseHandler;
|
||||
}
|
||||
Object.assign(ctx, result.context);
|
||||
Object.assign(ctx.state, result.state);
|
||||
return (_a = this.handlers.get(result.route)) !== null && _a !== void 0 ? _a : this.otherwiseHandler;
|
||||
});
|
||||
}
|
||||
}
|
||||
exports.Router = Router;
|
||||
17
node_modules/telegraf/lib/scenes.js
generated
vendored
Normal file
17
node_modules/telegraf/lib/scenes.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
"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 });
|
||||
__exportStar(require("./scenes/index.js"), exports);
|
||||
39
node_modules/telegraf/lib/scenes/base.js
generated
vendored
Normal file
39
node_modules/telegraf/lib/scenes/base.js
generated
vendored
Normal file
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BaseScene = void 0;
|
||||
const composer_1 = __importDefault(require("../composer"));
|
||||
const { compose } = composer_1.default;
|
||||
class BaseScene extends composer_1.default {
|
||||
constructor(id, options) {
|
||||
const opts = {
|
||||
handlers: [],
|
||||
enterHandlers: [],
|
||||
leaveHandlers: [],
|
||||
...options,
|
||||
};
|
||||
super(...opts.handlers);
|
||||
this.id = id;
|
||||
this.ttl = opts.ttl;
|
||||
this.enterHandler = compose(opts.enterHandlers);
|
||||
this.leaveHandler = compose(opts.leaveHandlers);
|
||||
}
|
||||
enter(...fns) {
|
||||
this.enterHandler = compose([this.enterHandler, ...fns]);
|
||||
return this;
|
||||
}
|
||||
leave(...fns) {
|
||||
this.leaveHandler = compose([this.leaveHandler, ...fns]);
|
||||
return this;
|
||||
}
|
||||
enterMiddleware() {
|
||||
return this.enterHandler;
|
||||
}
|
||||
leaveMiddleware() {
|
||||
return this.leaveHandler;
|
||||
}
|
||||
}
|
||||
exports.BaseScene = BaseScene;
|
||||
exports.default = BaseScene;
|
||||
104
node_modules/telegraf/lib/scenes/context.js
generated
vendored
Normal file
104
node_modules/telegraf/lib/scenes/context.js
generated
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const composer_1 = __importDefault(require("../composer"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const debug = (0, debug_1.default)('telegraf:scenes:context');
|
||||
const noop = () => Promise.resolve();
|
||||
const now = () => Math.floor(Date.now() / 1000);
|
||||
class SceneContextScene {
|
||||
constructor(ctx, scenes, options) {
|
||||
this.ctx = ctx;
|
||||
this.scenes = scenes;
|
||||
this.leaving = false;
|
||||
// @ts-expect-error {} might not be assignable to D
|
||||
const fallbackSessionDefault = {};
|
||||
this.options = { defaultSession: fallbackSessionDefault, ...options };
|
||||
}
|
||||
get session() {
|
||||
var _a, _b;
|
||||
const defaultSession = Object.assign({}, this.options.defaultSession);
|
||||
let session = (_b = (_a = this.ctx.session) === null || _a === void 0 ? void 0 : _a.__scenes) !== null && _b !== void 0 ? _b : defaultSession;
|
||||
if (session.expires !== undefined && session.expires < now()) {
|
||||
session = defaultSession;
|
||||
}
|
||||
if (this.ctx.session === undefined) {
|
||||
this.ctx.session = { __scenes: session };
|
||||
}
|
||||
else {
|
||||
this.ctx.session.__scenes = session;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
get state() {
|
||||
var _a;
|
||||
var _b;
|
||||
return ((_a = (_b = this.session).state) !== null && _a !== void 0 ? _a : (_b.state = {}));
|
||||
}
|
||||
set state(value) {
|
||||
this.session.state = { ...value };
|
||||
}
|
||||
get current() {
|
||||
var _a;
|
||||
const sceneId = (_a = this.session.current) !== null && _a !== void 0 ? _a : this.options.default;
|
||||
return sceneId === undefined || !this.scenes.has(sceneId)
|
||||
? undefined
|
||||
: this.scenes.get(sceneId);
|
||||
}
|
||||
reset() {
|
||||
if (this.ctx.session !== undefined)
|
||||
this.ctx.session.__scenes = Object.assign({}, this.options.defaultSession);
|
||||
}
|
||||
async enter(sceneId, initialState = {}, silent = false) {
|
||||
var _a, _b;
|
||||
if (!this.scenes.has(sceneId)) {
|
||||
throw new Error(`Can't find scene: ${sceneId}`);
|
||||
}
|
||||
if (!silent) {
|
||||
await this.leave();
|
||||
}
|
||||
debug('Entering scene', sceneId, initialState, silent);
|
||||
this.session.current = sceneId;
|
||||
this.state = initialState;
|
||||
const ttl = (_b = (_a = this.current) === null || _a === void 0 ? void 0 : _a.ttl) !== null && _b !== void 0 ? _b : this.options.ttl;
|
||||
if (ttl !== undefined) {
|
||||
this.session.expires = now() + ttl;
|
||||
}
|
||||
if (this.current === undefined || silent) {
|
||||
return;
|
||||
}
|
||||
const handler = 'enterMiddleware' in this.current &&
|
||||
typeof this.current.enterMiddleware === 'function'
|
||||
? this.current.enterMiddleware()
|
||||
: this.current.middleware();
|
||||
return await handler(this.ctx, noop);
|
||||
}
|
||||
reenter() {
|
||||
return this.session.current === undefined
|
||||
? undefined
|
||||
: this.enter(this.session.current, this.state);
|
||||
}
|
||||
async leave() {
|
||||
if (this.leaving)
|
||||
return;
|
||||
debug('Leaving scene');
|
||||
try {
|
||||
this.leaving = true;
|
||||
if (this.current === undefined) {
|
||||
return;
|
||||
}
|
||||
const handler = 'leaveMiddleware' in this.current &&
|
||||
typeof this.current.leaveMiddleware === 'function'
|
||||
? this.current.leaveMiddleware()
|
||||
: composer_1.default.passThru();
|
||||
await handler(this.ctx, noop);
|
||||
return this.reset();
|
||||
}
|
||||
finally {
|
||||
this.leaving = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.default = SceneContextScene;
|
||||
21
node_modules/telegraf/lib/scenes/index.js
generated
vendored
Normal file
21
node_modules/telegraf/lib/scenes/index.js
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @see https://github.com/telegraf/telegraf/issues/705#issuecomment-549056045
|
||||
* @see https://www.npmjs.com/package/telegraf-stateless-question
|
||||
* @packageDocumentation
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WizardContextWizard = exports.WizardScene = exports.BaseScene = exports.SceneContextScene = exports.Stage = void 0;
|
||||
var stage_1 = require("./stage");
|
||||
Object.defineProperty(exports, "Stage", { enumerable: true, get: function () { return stage_1.Stage; } });
|
||||
var context_1 = require("./context");
|
||||
Object.defineProperty(exports, "SceneContextScene", { enumerable: true, get: function () { return __importDefault(context_1).default; } });
|
||||
var base_1 = require("./base");
|
||||
Object.defineProperty(exports, "BaseScene", { enumerable: true, get: function () { return base_1.BaseScene; } });
|
||||
var wizard_1 = require("./wizard");
|
||||
Object.defineProperty(exports, "WizardScene", { enumerable: true, get: function () { return wizard_1.WizardScene; } });
|
||||
var context_2 = require("./wizard/context");
|
||||
Object.defineProperty(exports, "WizardContextWizard", { enumerable: true, get: function () { return __importDefault(context_2).default; } });
|
||||
49
node_modules/telegraf/lib/scenes/stage.js
generated
vendored
Normal file
49
node_modules/telegraf/lib/scenes/stage.js
generated
vendored
Normal file
@@ -0,0 +1,49 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Stage = void 0;
|
||||
const session_1 = require("../session");
|
||||
const context_1 = __importDefault(require("./context"));
|
||||
const composer_1 = require("../composer");
|
||||
class Stage extends composer_1.Composer {
|
||||
constructor(scenes = [], options) {
|
||||
super();
|
||||
this.options = { ...options };
|
||||
this.scenes = new Map();
|
||||
scenes.forEach((scene) => this.register(scene));
|
||||
}
|
||||
register(...scenes) {
|
||||
scenes.forEach((scene) => {
|
||||
if ((scene === null || scene === void 0 ? void 0 : scene.id) == null || typeof scene.middleware !== 'function') {
|
||||
throw new Error('telegraf: Unsupported scene');
|
||||
}
|
||||
this.scenes.set(scene.id, scene);
|
||||
});
|
||||
return this;
|
||||
}
|
||||
middleware() {
|
||||
const handler = composer_1.Composer.compose([
|
||||
(ctx, next) => {
|
||||
const scenes = this.scenes;
|
||||
const scene = new context_1.default(ctx, scenes, this.options);
|
||||
ctx.scene = scene;
|
||||
return next();
|
||||
},
|
||||
super.middleware(),
|
||||
composer_1.Composer.lazy((ctx) => { var _a; return (_a = ctx.scene.current) !== null && _a !== void 0 ? _a : composer_1.Composer.passThru(); }),
|
||||
]);
|
||||
return composer_1.Composer.optional(session_1.isSessionContext, handler);
|
||||
}
|
||||
static enter(...args) {
|
||||
return (ctx) => ctx.scene.enter(...args);
|
||||
}
|
||||
static reenter(...args) {
|
||||
return (ctx) => ctx.scene.reenter(...args);
|
||||
}
|
||||
static leave(...args) {
|
||||
return (ctx) => ctx.scene.leave(...args);
|
||||
}
|
||||
}
|
||||
exports.Stage = Stage;
|
||||
31
node_modules/telegraf/lib/scenes/wizard/context.js
generated
vendored
Normal file
31
node_modules/telegraf/lib/scenes/wizard/context.js
generated
vendored
Normal file
@@ -0,0 +1,31 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
class WizardContextWizard {
|
||||
constructor(ctx, steps) {
|
||||
var _a;
|
||||
this.ctx = ctx;
|
||||
this.steps = steps;
|
||||
this.state = ctx.scene.state;
|
||||
this.cursor = (_a = ctx.scene.session.cursor) !== null && _a !== void 0 ? _a : 0;
|
||||
}
|
||||
get step() {
|
||||
return this.steps[this.cursor];
|
||||
}
|
||||
get cursor() {
|
||||
return this.ctx.scene.session.cursor;
|
||||
}
|
||||
set cursor(cursor) {
|
||||
this.ctx.scene.session.cursor = cursor;
|
||||
}
|
||||
selectStep(index) {
|
||||
this.cursor = index;
|
||||
return this;
|
||||
}
|
||||
next() {
|
||||
return this.selectStep(this.cursor + 1);
|
||||
}
|
||||
back() {
|
||||
return this.selectStep(this.cursor - 1);
|
||||
}
|
||||
}
|
||||
exports.default = WizardContextWizard;
|
||||
45
node_modules/telegraf/lib/scenes/wizard/index.js
generated
vendored
Normal file
45
node_modules/telegraf/lib/scenes/wizard/index.js
generated
vendored
Normal file
@@ -0,0 +1,45 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.WizardScene = void 0;
|
||||
const base_1 = __importDefault(require("../base"));
|
||||
const context_1 = __importDefault(require("./context"));
|
||||
const composer_1 = __importDefault(require("../../composer"));
|
||||
class WizardScene extends base_1.default {
|
||||
constructor(id, options, ...steps) {
|
||||
let opts;
|
||||
let s;
|
||||
if (typeof options === 'function' || 'middleware' in options) {
|
||||
opts = undefined;
|
||||
s = [options, ...steps];
|
||||
}
|
||||
else {
|
||||
opts = options;
|
||||
s = steps;
|
||||
}
|
||||
super(id, opts);
|
||||
this.steps = s;
|
||||
}
|
||||
middleware() {
|
||||
return composer_1.default.compose([
|
||||
(ctx, next) => {
|
||||
ctx.wizard = new context_1.default(ctx, this.steps);
|
||||
return next();
|
||||
},
|
||||
super.middleware(),
|
||||
(ctx, next) => {
|
||||
if (ctx.wizard.step === undefined) {
|
||||
ctx.wizard.selectStep(0);
|
||||
return ctx.scene.leave();
|
||||
}
|
||||
return composer_1.default.unwrap(ctx.wizard.step)(ctx, next);
|
||||
},
|
||||
]);
|
||||
}
|
||||
enterMiddleware() {
|
||||
return composer_1.default.compose([this.enterHandler, this.middleware()]);
|
||||
}
|
||||
}
|
||||
exports.WizardScene = WizardScene;
|
||||
166
node_modules/telegraf/lib/session.js
generated
vendored
Normal file
166
node_modules/telegraf/lib/session.js
generated
vendored
Normal file
@@ -0,0 +1,166 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.isSessionContext = exports.MemorySessionStore = exports.session = void 0;
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const debug = (0, debug_1.default)('telegraf:session');
|
||||
/**
|
||||
* Returns middleware that adds `ctx.session` for storing arbitrary state per session key.
|
||||
*
|
||||
* The default `getSessionKey` is `${ctx.from.id}:${ctx.chat.id}`.
|
||||
* If either `ctx.from` or `ctx.chat` is `undefined`, default session key and thus `ctx.session` are also `undefined`.
|
||||
*
|
||||
* > ⚠️ Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
|
||||
* >
|
||||
* > If you want to persist data across process restarts, or share it among multiple instances, you should use
|
||||
* [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.
|
||||
*
|
||||
* @see {@link https://github.com/feathers-studio/telegraf-docs/blob/b694bcc36b4f71fb1cd650a345c2009ab4d2a2a5/guide/session.md Telegraf Docs | Session}
|
||||
* @see {@link https://github.com/feathers-studio/telegraf-docs/blob/master/examples/session-bot.ts Example}
|
||||
*/
|
||||
function session(options) {
|
||||
var _a, _b, _c;
|
||||
const prop = (_a = options === null || options === void 0 ? void 0 : options.property) !== null && _a !== void 0 ? _a : 'session';
|
||||
const getSessionKey = (_b = options === null || options === void 0 ? void 0 : options.getSessionKey) !== null && _b !== void 0 ? _b : defaultGetSessionKey;
|
||||
const store = (_c = options === null || options === void 0 ? void 0 : options.store) !== null && _c !== void 0 ? _c : new MemorySessionStore();
|
||||
// caches value from store in-memory while simultaneous updates share it
|
||||
// when counter reaches 0, the cached ref will be freed from memory
|
||||
const cache = new Map();
|
||||
// temporarily stores concurrent requests
|
||||
const concurrents = new Map();
|
||||
// this function must be handled with care
|
||||
// read full description on the original PR: https://github.com/telegraf/telegraf/pull/1713
|
||||
// make sure to update the tests in test/session.js if you make any changes or fix bugs here
|
||||
return async (ctx, next) => {
|
||||
var _a;
|
||||
const updId = ctx.update.update_id;
|
||||
let released = false;
|
||||
function releaseChecks() {
|
||||
if (released && process.env.EXPERIMENTAL_SESSION_CHECKS)
|
||||
throw new Error("Session was accessed or assigned to after the middleware chain exhausted. This is a bug in your code. You're probably accessing session asynchronously and missing awaits.");
|
||||
}
|
||||
// because this is async, requests may still race here, but it will get autocorrected at (1)
|
||||
// v5 getSessionKey should probably be synchronous to avoid that
|
||||
const key = await getSessionKey(ctx);
|
||||
if (!key) {
|
||||
// Leaving this here could be useful to check for `prop in ctx` in future middleware
|
||||
ctx[prop] = undefined;
|
||||
return await next();
|
||||
}
|
||||
let cached = cache.get(key);
|
||||
if (cached) {
|
||||
debug(`(${updId}) found cached session, reusing from cache`);
|
||||
++cached.counter;
|
||||
}
|
||||
else {
|
||||
debug(`(${updId}) did not find cached session`);
|
||||
// if another concurrent request has already sent a store request, fetch that instead
|
||||
let promise = concurrents.get(key);
|
||||
if (promise)
|
||||
debug(`(${updId}) found a concurrent request, reusing promise`);
|
||||
else {
|
||||
debug(`(${updId}) fetching from upstream store`);
|
||||
promise = store.get(key);
|
||||
}
|
||||
// synchronously store promise so concurrent requests can share response
|
||||
concurrents.set(key, promise);
|
||||
const upstream = await promise;
|
||||
// all concurrent awaits will have promise in their closure, safe to remove now
|
||||
concurrents.delete(key);
|
||||
debug(`(${updId}) updating cache`);
|
||||
// another request may have beaten us to the punch
|
||||
const c = cache.get(key);
|
||||
if (c) {
|
||||
// another request did beat us to the punch
|
||||
c.counter++;
|
||||
// (1) preserve cached reference; in-memory reference is always newer than from store
|
||||
cached = c;
|
||||
}
|
||||
else {
|
||||
// we're the first, so we must cache the reference
|
||||
cached = { ref: upstream !== null && upstream !== void 0 ? upstream : (_a = options === null || options === void 0 ? void 0 : options.defaultSession) === null || _a === void 0 ? void 0 : _a.call(options, ctx), counter: 1 };
|
||||
cache.set(key, cached);
|
||||
}
|
||||
}
|
||||
// TS already knows cached is always defined by this point, but does not guard cached.
|
||||
// It will, however, guard `c` here.
|
||||
const c = cached;
|
||||
let touched = false;
|
||||
Object.defineProperty(ctx, prop, {
|
||||
get() {
|
||||
releaseChecks();
|
||||
touched = true;
|
||||
return c.ref;
|
||||
},
|
||||
set(value) {
|
||||
releaseChecks();
|
||||
touched = true;
|
||||
c.ref = value;
|
||||
},
|
||||
});
|
||||
try {
|
||||
await next();
|
||||
released = true;
|
||||
}
|
||||
finally {
|
||||
if (--c.counter === 0) {
|
||||
// decrement to avoid memory leak
|
||||
debug(`(${updId}) refcounter reached 0, removing cached`);
|
||||
cache.delete(key);
|
||||
}
|
||||
debug(`(${updId}) middlewares completed, checking session`);
|
||||
// only update store if ctx.session was touched
|
||||
if (touched)
|
||||
if (c.ref == null) {
|
||||
debug(`(${updId}) ctx.${prop} missing, removing from store`);
|
||||
await store.delete(key);
|
||||
}
|
||||
else {
|
||||
debug(`(${updId}) ctx.${prop} found, updating store`);
|
||||
await store.set(key, c.ref);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
exports.session = session;
|
||||
function defaultGetSessionKey(ctx) {
|
||||
var _a, _b;
|
||||
const fromId = (_a = ctx.from) === null || _a === void 0 ? void 0 : _a.id;
|
||||
const chatId = (_b = ctx.chat) === null || _b === void 0 ? void 0 : _b.id;
|
||||
if (fromId == null || chatId == null)
|
||||
return undefined;
|
||||
return `${fromId}:${chatId}`;
|
||||
}
|
||||
/** @deprecated Use `Map` */
|
||||
class MemorySessionStore {
|
||||
constructor(ttl = Infinity) {
|
||||
this.ttl = ttl;
|
||||
this.store = new Map();
|
||||
}
|
||||
get(name) {
|
||||
const entry = this.store.get(name);
|
||||
if (entry == null) {
|
||||
return undefined;
|
||||
}
|
||||
else if (entry.expires < Date.now()) {
|
||||
this.delete(name);
|
||||
return undefined;
|
||||
}
|
||||
return entry.session;
|
||||
}
|
||||
set(name, value) {
|
||||
const now = Date.now();
|
||||
this.store.set(name, { session: value, expires: now + this.ttl });
|
||||
}
|
||||
delete(name) {
|
||||
this.store.delete(name);
|
||||
}
|
||||
}
|
||||
exports.MemorySessionStore = MemorySessionStore;
|
||||
/** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
|
||||
function isSessionContext(ctx) {
|
||||
return 'session' in ctx;
|
||||
}
|
||||
exports.isSessionContext = isSessionContext;
|
||||
246
node_modules/telegraf/lib/telegraf.js
generated
vendored
Normal file
246
node_modules/telegraf/lib/telegraf.js
generated
vendored
Normal file
@@ -0,0 +1,246 @@
|
||||
"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 });
|
||||
exports.Telegraf = void 0;
|
||||
const crypto = __importStar(require("crypto"));
|
||||
const http = __importStar(require("http"));
|
||||
const https = __importStar(require("https"));
|
||||
const composer_1 = require("./composer");
|
||||
const compact_1 = require("./core/helpers/compact");
|
||||
const context_1 = __importDefault(require("./context"));
|
||||
const debug_1 = __importDefault(require("debug"));
|
||||
const webhook_1 = __importDefault(require("./core/network/webhook"));
|
||||
const polling_1 = require("./core/network/polling");
|
||||
const p_timeout_1 = __importDefault(require("p-timeout"));
|
||||
const telegram_1 = __importDefault(require("./telegram"));
|
||||
const url_1 = require("url");
|
||||
const safeCompare = require("safe-compare");
|
||||
const debug = (0, debug_1.default)('telegraf:main');
|
||||
const DEFAULT_OPTIONS = {
|
||||
telegram: {},
|
||||
handlerTimeout: 90000,
|
||||
contextType: context_1.default,
|
||||
};
|
||||
function always(x) {
|
||||
return () => x;
|
||||
}
|
||||
const anoop = always(Promise.resolve());
|
||||
const TOKEN_HEADER = 'x-telegram-bot-api-secret-token';
|
||||
class Telegraf extends composer_1.Composer {
|
||||
constructor(token, options) {
|
||||
super();
|
||||
this.context = {};
|
||||
/** Assign to this to customise the webhook filter middleware.
|
||||
* `{ path, secretToken }` will be bound to this rather than the Telegraf instance.
|
||||
* Remember to assign a regular function and not an arrow function so it's bindable.
|
||||
*/
|
||||
this.webhookFilter = function (req) {
|
||||
const debug = (0, debug_1.default)('telegraf:webhook');
|
||||
if (req.method === 'POST') {
|
||||
if (safeCompare(this.path, req.url)) {
|
||||
// no need to check if secret_token was not set
|
||||
if (!this.secretToken)
|
||||
return true;
|
||||
else {
|
||||
const token = req.headers[TOKEN_HEADER];
|
||||
if (safeCompare(this.secretToken, token))
|
||||
return true;
|
||||
else
|
||||
debug('Secret token does not match:', token, this.secretToken);
|
||||
}
|
||||
}
|
||||
else
|
||||
debug('Path does not match:', req.url, this.path);
|
||||
}
|
||||
else
|
||||
debug('Unexpected request method, not POST. Received:', req.method);
|
||||
return false;
|
||||
};
|
||||
this.handleError = (err, ctx) => {
|
||||
// set exit code to emulate `warn-with-error-code` behavior of
|
||||
// https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode
|
||||
// to prevent a clean exit despite an error being thrown
|
||||
process.exitCode = 1;
|
||||
console.error('Unhandled error while processing', ctx.update);
|
||||
throw err;
|
||||
};
|
||||
// @ts-expect-error Trust me, TS
|
||||
this.options = {
|
||||
...DEFAULT_OPTIONS,
|
||||
...(0, compact_1.compactOptions)(options),
|
||||
};
|
||||
this.telegram = new telegram_1.default(token, this.options.telegram);
|
||||
debug('Created a `Telegraf` instance');
|
||||
}
|
||||
get token() {
|
||||
return this.telegram.token;
|
||||
}
|
||||
/** @deprecated use `ctx.telegram.webhookReply` */
|
||||
set webhookReply(webhookReply) {
|
||||
this.telegram.webhookReply = webhookReply;
|
||||
}
|
||||
/** @deprecated use `ctx.telegram.webhookReply` */
|
||||
get webhookReply() {
|
||||
return this.telegram.webhookReply;
|
||||
}
|
||||
/**
|
||||
* _Override_ error handling
|
||||
*/
|
||||
catch(handler) {
|
||||
this.handleError = handler;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* You must call `bot.telegram.setWebhook` for this to work.
|
||||
* You should probably use {@link Telegraf.createWebhook} instead.
|
||||
*/
|
||||
webhookCallback(path = '/', opts = {}) {
|
||||
const { secretToken } = opts;
|
||||
return (0, webhook_1.default)(this.webhookFilter.bind({ hookPath: path, path, secretToken }), (update, res) => this.handleUpdate(update, res));
|
||||
}
|
||||
getDomainOpts(opts) {
|
||||
var _a;
|
||||
const protocol = opts.domain.startsWith('https://') || opts.domain.startsWith('http://');
|
||||
if (protocol)
|
||||
debug('Unexpected protocol in domain, telegraf will use https:', opts.domain);
|
||||
const domain = protocol ? new url_1.URL(opts.domain).host : opts.domain;
|
||||
const path = (_a = opts.path) !== null && _a !== void 0 ? _a : `/telegraf/${this.secretPathComponent()}`;
|
||||
const url = `https://${domain}${path}`;
|
||||
return { domain, path, url };
|
||||
}
|
||||
/**
|
||||
* Specify a url to receive incoming updates via webhook.
|
||||
* Returns an Express-style middleware you can pass to app.use()
|
||||
*/
|
||||
async createWebhook(opts) {
|
||||
const { domain, path, ...extra } = opts;
|
||||
const domainOpts = this.getDomainOpts({ domain, path });
|
||||
await this.telegram.setWebhook(domainOpts.url, extra);
|
||||
debug(`Webhook set to ${domainOpts.url}`);
|
||||
return this.webhookCallback(domainOpts.path, {
|
||||
secretToken: extra.secret_token,
|
||||
});
|
||||
}
|
||||
startPolling(allowedUpdates = []) {
|
||||
this.polling = new polling_1.Polling(this.telegram, allowedUpdates);
|
||||
return this.polling.loop(async (update) => {
|
||||
await this.handleUpdate(update);
|
||||
});
|
||||
}
|
||||
startWebhook(path, tlsOptions, port, host, cb, secretToken) {
|
||||
const webhookCb = this.webhookCallback(path, { secretToken });
|
||||
const callback = typeof cb === 'function'
|
||||
? (req, res) => webhookCb(req, res, () => cb(req, res))
|
||||
: webhookCb;
|
||||
this.webhookServer =
|
||||
tlsOptions != null
|
||||
? https.createServer(tlsOptions, callback)
|
||||
: http.createServer(callback);
|
||||
this.webhookServer.listen(port, host, () => {
|
||||
debug('Webhook listening on port: %s', port);
|
||||
});
|
||||
return this;
|
||||
}
|
||||
secretPathComponent() {
|
||||
return crypto
|
||||
.createHash('sha3-256')
|
||||
.update(this.token)
|
||||
.update(process.version) // salt
|
||||
.digest('hex');
|
||||
}
|
||||
/**
|
||||
* @see https://github.com/telegraf/telegraf/discussions/1344#discussioncomment-335700
|
||||
*/
|
||||
async launch(config = {},
|
||||
/** @experimental */
|
||||
onLaunch) {
|
||||
var _a, _b;
|
||||
const [cfg, onMe] = typeof config === 'function' ? [{}, config] : [config, onLaunch];
|
||||
const drop_pending_updates = cfg.dropPendingUpdates;
|
||||
const allowed_updates = cfg.allowedUpdates;
|
||||
const webhook = cfg.webhook;
|
||||
debug('Connecting to Telegram');
|
||||
(_a = this.botInfo) !== null && _a !== void 0 ? _a : (this.botInfo = await this.telegram.getMe());
|
||||
onMe === null || onMe === void 0 ? void 0 : onMe();
|
||||
debug(`Launching @${this.botInfo.username}`);
|
||||
if (webhook === undefined) {
|
||||
await this.telegram.deleteWebhook({ drop_pending_updates });
|
||||
debug('Bot started with long polling');
|
||||
await this.startPolling(allowed_updates);
|
||||
return;
|
||||
}
|
||||
const domainOpts = this.getDomainOpts({
|
||||
domain: webhook.domain,
|
||||
path: (_b = webhook.path) !== null && _b !== void 0 ? _b : webhook.hookPath,
|
||||
});
|
||||
const { tlsOptions, port, host, cb, secretToken } = webhook;
|
||||
this.startWebhook(domainOpts.path, tlsOptions, port, host, cb, secretToken);
|
||||
await this.telegram.setWebhook(domainOpts.url, {
|
||||
drop_pending_updates: drop_pending_updates,
|
||||
allowed_updates: allowed_updates,
|
||||
ip_address: webhook.ipAddress,
|
||||
max_connections: webhook.maxConnections,
|
||||
secret_token: webhook.secretToken,
|
||||
certificate: webhook.certificate,
|
||||
});
|
||||
debug(`Bot started with webhook @ ${domainOpts.url}`);
|
||||
}
|
||||
stop(reason = 'unspecified') {
|
||||
var _a, _b;
|
||||
debug('Stopping bot... Reason:', reason);
|
||||
// https://github.com/telegraf/telegraf/pull/1224#issuecomment-742693770
|
||||
if (this.polling === undefined && this.webhookServer === undefined) {
|
||||
throw new Error('Bot is not running!');
|
||||
}
|
||||
(_a = this.webhookServer) === null || _a === void 0 ? void 0 : _a.close();
|
||||
(_b = this.polling) === null || _b === void 0 ? void 0 : _b.stop();
|
||||
}
|
||||
async handleUpdate(update, webhookResponse) {
|
||||
var _a, _b;
|
||||
(_a = this.botInfo) !== null && _a !== void 0 ? _a : (this.botInfo = (debug('Update %d is waiting for `botInfo` to be initialized', update.update_id),
|
||||
await ((_b = this.botInfoCall) !== null && _b !== void 0 ? _b : (this.botInfoCall = this.telegram.getMe()))));
|
||||
debug('Processing update', update.update_id);
|
||||
const tg = new telegram_1.default(this.token, this.telegram.options, webhookResponse);
|
||||
const TelegrafContext = this.options.contextType;
|
||||
const ctx = new TelegrafContext(update, tg, this.botInfo);
|
||||
Object.assign(ctx, this.context);
|
||||
try {
|
||||
await (0, p_timeout_1.default)(Promise.resolve(this.middleware()(ctx, anoop)), this.options.handlerTimeout);
|
||||
}
|
||||
catch (err) {
|
||||
return await this.handleError(err, ctx);
|
||||
}
|
||||
finally {
|
||||
if ((webhookResponse === null || webhookResponse === void 0 ? void 0 : webhookResponse.writableEnded) === false) {
|
||||
webhookResponse.end();
|
||||
}
|
||||
debug('Finished processing update', update.update_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.Telegraf = Telegraf;
|
||||
6
node_modules/telegraf/lib/telegram-types.js
generated
vendored
Normal file
6
node_modules/telegraf/lib/telegram-types.js
generated
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
"use strict";
|
||||
/** @format */
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Markup = void 0;
|
||||
var markup_1 = require("./markup");
|
||||
Object.defineProperty(exports, "Markup", { enumerable: true, get: function () { return markup_1.Markup; } });
|
||||
1240
node_modules/telegraf/lib/telegram.js
generated
vendored
Normal file
1240
node_modules/telegraf/lib/telegram.js
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2
node_modules/telegraf/lib/types.js
generated
vendored
Normal file
2
node_modules/telegraf/lib/types.js
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
5
node_modules/telegraf/lib/utils.js
generated
vendored
Normal file
5
node_modules/telegraf/lib/utils.js
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.argsParser = void 0;
|
||||
var args_1 = require("./core/helpers/args");
|
||||
Object.defineProperty(exports, "argsParser", { enumerable: true, get: function () { return args_1.argsParser; } });
|
||||
Reference in New Issue
Block a user