Proyecto audio control. inicado con panel y control.

This commit is contained in:
2025-11-11 02:26:04 -05:00
parent 7ea49a026e
commit 6895960127
4248 changed files with 493435 additions and 0 deletions

21
node_modules/telegraf/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016-2021 Vitaly Domnikov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

108
node_modules/telegraf/bin/telegraf generated vendored Executable file
View File

@@ -0,0 +1,108 @@
#!/usr/bin/env node
const debug = require('debug')
const path = require('path')
const parse = require('minimist')
const { addAlias } = require('module-alias')
const Telegraf = require('../')
const log = debug('telegraf:cli')
const help = () => {
console.log(`Usage: telegraf [opts] <bot-file>
-t Bot token [$BOT_TOKEN]
-d Webhook domain
-H Webhook host [0.0.0.0]
-p Webhook port [$PORT or 3000]
-s Stop on error
-l Enable logs
-h Show this help message`)
}
const args = parse(process.argv, {
alias: {
t: 'token',
d: 'domain',
H: 'host',
h: 'help',
l: 'logs',
s: 'stop',
p: 'port'
},
boolean: ['h', 'l', 's'],
default: {
H: '0.0.0.0',
p: process.env.PORT || 3000
}
})
if (args.help) {
help()
process.exit(0)
}
const token = args.token || process.env.BOT_TOKEN
const domain = args.domain || process.env.BOT_DOMAIN
if (!token) {
console.error('Please supply Bot Token')
help()
process.exit(1)
}
let [, , file] = args._
if (!file) {
try {
const packageJson = require(path.resolve(process.cwd(), 'package.json'))
file = packageJson.main || 'index.js'
} catch (err) {
}
}
if (!file) {
console.error('Please supply a bot handler file.\n')
help()
process.exit(1)
}
if (file[0] !== '/') {
file = path.resolve(process.cwd(), file)
}
let botHandler
let httpHandler
let tlsOptions
try {
if (args.logs) {
debug.enable('telegraf:*')
}
addAlias('telegraf', path.join(__dirname, '../'))
const mod = require(file)
botHandler = mod.botHandler || mod
httpHandler = mod.httpHandler
tlsOptions = mod.tlsOptions
} catch (err) {
console.error(`Error importing ${file}`, err.stack)
process.exit(1)
}
const config = {}
if (domain) {
config.webhook = {
tlsOptions,
host: args.host,
port: args.port,
domain: domain,
cb: httpHandler
}
}
const bot = new Telegraf(token)
if (!args.stop) {
bot.catch(log)
}
bot.use(botHandler)
log(`Starting module ${file}`)
bot.launch(config)

408
node_modules/telegraf/composer.js generated vendored Normal file
View File

@@ -0,0 +1,408 @@
const Context = require('./context')
class Composer {
constructor (...fns) {
this.handler = Composer.compose(fns)
}
use (...fns) {
this.handler = Composer.compose([this.handler, ...fns])
return this
}
on (updateTypes, ...fns) {
return this.use(Composer.mount(updateTypes, ...fns))
}
hears (triggers, ...fns) {
return this.use(Composer.hears(triggers, ...fns))
}
command (commands, ...fns) {
return this.use(Composer.command(commands, ...fns))
}
action (triggers, ...fns) {
return this.use(Composer.action(triggers, ...fns))
}
inlineQuery (triggers, ...fns) {
return this.use(Composer.inlineQuery(triggers, ...fns))
}
gameQuery (...fns) {
return this.use(Composer.gameQuery(...fns))
}
drop (predicate) {
return this.use(Composer.drop(predicate))
}
filter (predicate) {
return this.use(Composer.filter(predicate))
}
entity (...args) {
return this.use(Composer.entity(...args))
}
email (...args) {
return this.use(Composer.email(...args))
}
phone (...args) {
return this.use(Composer.phone(...args))
}
url (...args) {
return this.use(Composer.url(...args))
}
textLink (...args) {
return this.use(Composer.textLink(...args))
}
textMention (...args) {
return this.use(Composer.textMention(...args))
}
mention (...args) {
return this.use(Composer.mention(...args))
}
hashtag (...args) {
return this.use(Composer.hashtag(...args))
}
cashtag (...args) {
return this.use(Composer.cashtag(...args))
}
start (...fns) {
return this.command('start', Composer.tap((ctx) => {
ctx.startPayload = ctx.message.text.substring(7)
}), ...fns)
}
help (...fns) {
return this.command('help', ...fns)
}
settings (...fns) {
return this.command('settings', ...fns)
}
middleware () {
return this.handler
}
static reply (...args) {
return (ctx) => ctx.reply(...args)
}
static catchAll (...fns) {
return Composer.catch((err) => {
console.error()
console.error((err.stack || err.toString()).replace(/^/gm, ' '))
console.error()
}, ...fns)
}
static catch (errorHandler, ...fns) {
const handler = Composer.compose(fns)
return (ctx, next) => Promise.resolve(handler(ctx, next))
.catch((err) => errorHandler(err, ctx))
}
static fork (middleware) {
const handler = Composer.unwrap(middleware)
return (ctx, next) => {
setImmediate(handler, ctx, Composer.safePassThru())
return next(ctx)
}
}
static tap (middleware) {
const handler = Composer.unwrap(middleware)
return (ctx, next) => Promise.resolve(handler(ctx, Composer.safePassThru())).then(() => next(ctx))
}
static passThru () {
return (ctx, next) => next(ctx)
}
static safePassThru () {
return (ctx, next) => typeof next === 'function' ? next(ctx) : Promise.resolve()
}
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 Composer.fork((ctx) => logFn(JSON.stringify(ctx.update, null, 2)))
}
static branch (predicate, trueMiddleware, falseMiddleware) {
if (typeof predicate !== 'function') {
return predicate ? trueMiddleware : falseMiddleware
}
return Composer.lazy((ctx) => Promise.resolve(predicate(ctx))
.then((value) => value ? trueMiddleware : falseMiddleware))
}
static optional (predicate, ...fns) {
return Composer.branch(predicate, Composer.compose(fns), Composer.safePassThru())
}
static filter (predicate) {
return Composer.branch(predicate, Composer.safePassThru(), () => { })
}
static drop (predicate) {
return Composer.branch(predicate, () => { }, Composer.safePassThru())
}
static dispatch (routeFn, handlers) {
return typeof routeFn === 'function'
? Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value]))
: handlers[routeFn]
}
static mount (updateType, ...fns) {
const updateTypes = normalizeTextArguments(updateType)
const predicate = (ctx) => updateTypes.includes(ctx.updateType) || updateTypes.some((type) => ctx.updateSubTypes.includes(type))
return Composer.optional(predicate, ...fns)
}
static entity (predicate, ...fns) {
if (typeof predicate !== 'function') {
const entityTypes = normalizeTextArguments(predicate)
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns)
}
return Composer.optional((ctx) => {
const message = ctx.message || ctx.channelPost
const entities = message && (message.entities || message.caption_entities)
const text = message && (message.text || message.caption)
return entities && entities.some((entity) =>
predicate(entity, text.substring(entity.offset, entity.offset + entity.length), ctx)
)
}, ...fns)
}
static entityText (entityType, predicate, ...fns) {
if (fns.length === 0) {
return Array.isArray(predicate)
? Composer.entity(entityType, ...predicate)
: Composer.entity(entityType, predicate)
}
const triggers = normalizeTriggers(predicate)
return Composer.entity(({ type }, value, ctx) => {
if (type !== entityType) {
return false
}
for (const trigger of triggers) {
ctx.match = trigger(value, ctx)
if (ctx.match) {
return true
}
}
}, ...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', normalizeTextArguments(mention, '@'), ...fns)
}
static hashtag (hashtag, ...fns) {
return Composer.entityText('hashtag', normalizeTextArguments(hashtag, '#'), ...fns)
}
static cashtag (cashtag, ...fns) {
return Composer.entityText('cashtag', normalizeTextArguments(cashtag, '$'), ...fns)
}
static match (triggers, ...fns) {
return Composer.optional((ctx) => {
const text = (
(ctx.message && (ctx.message.caption || ctx.message.text)) ||
(ctx.callbackQuery && ctx.callbackQuery.data) ||
(ctx.inlineQuery && ctx.inlineQuery.query)
)
for (const trigger of triggers) {
ctx.match = trigger(text, ctx)
if (ctx.match) {
return true
}
}
}, ...fns)
}
static hears (triggers, ...fns) {
return Composer.mount('text', Composer.match(normalizeTriggers(triggers), ...fns))
}
static command (command, ...fns) {
if (fns.length === 0) {
return Composer.entity(['bot_command'], command)
}
const commands = normalizeTextArguments(command, '/')
return Composer.mount('text', Composer.lazy((ctx) => {
const groupCommands = ctx.me && (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup')
? commands.map((command) => `${command}@${ctx.me}`)
: []
return Composer.entity(({ offset, type }, value) =>
offset === 0 &&
type === 'bot_command' &&
(commands.includes(value) || groupCommands.includes(value))
, ...fns)
}))
}
static action (triggers, ...fns) {
return Composer.mount('callback_query', Composer.match(normalizeTriggers(triggers), ...fns))
}
static inlineQuery (triggers, ...fns) {
return Composer.mount('inline_query', Composer.match(normalizeTriggers(triggers), ...fns))
}
static acl (userId, ...fns) {
if (typeof userId === 'function') {
return Composer.optional(userId, ...fns)
}
const allowed = Array.isArray(userId) ? userId : [userId]
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((ctx) => ctx.message && ctx.getChatMember(ctx.message.from.id)
.then(member => member && statuses.includes(member.status))
, ...fns)
}
static admin (...fns) {
return Composer.memberStatus(['administrator', 'creator'], ...fns)
}
static creator (...fns) {
return Composer.memberStatus('creator', ...fns)
}
static chatType (type, ...fns) {
const types = Array.isArray(type) ? type : [type]
return Composer.optional((ctx) => ctx.chat && types.includes(ctx.chat.type), ...fns)
}
static privateChat (...fns) {
return Composer.chatType('private', ...fns)
}
static groupChat (...fns) {
return Composer.chatType(['group', 'supergroup'], ...fns)
}
static gameQuery (...fns) {
return Composer.mount('callback_query', Composer.optional((ctx) => ctx.callbackQuery.game_short_name, ...fns))
}
static unwrap (handler) {
if (!handler) {
throw new Error('Handler is undefined')
}
return typeof handler.middleware === 'function'
? handler.middleware()
: handler
}
static compose (middlewares) {
if (!Array.isArray(middlewares)) {
throw new Error('Middlewares must be an array')
}
if (middlewares.length === 0) {
return Composer.safePassThru()
}
if (middlewares.length === 1) {
return Composer.unwrap(middlewares[0])
}
return (ctx, next) => {
let index = -1
return execute(0, ctx)
function execute (i, context) {
if (!(context instanceof Context)) {
return Promise.reject(new Error('next(ctx) called with invalid context'))
}
if (i <= index) {
return Promise.reject(new Error('next() called multiple times'))
}
index = i
const handler = middlewares[i] ? Composer.unwrap(middlewares[i]) : next
if (!handler) {
return Promise.resolve()
}
try {
return Promise.resolve(
handler(context, (ctx = context) => execute(i + 1, ctx))
)
} catch (err) {
return Promise.reject(err)
}
}
}
}
}
function normalizeTriggers (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 || '')
}
}
return (value) => trigger === value ? value : null
})
}
function normalizeTextArguments (argument, prefix) {
const args = Array.isArray(argument) ? argument : [argument]
return args
.filter(Boolean)
.map((arg) => prefix && typeof arg === 'string' && !arg.startsWith(prefix) ? `${prefix}${arg}` : arg)
}
module.exports = Composer

700
node_modules/telegraf/context.js generated vendored Normal file
View File

@@ -0,0 +1,700 @@
const UpdateTypes = [
'callback_query',
'channel_post',
'chosen_inline_result',
'edited_channel_post',
'edited_message',
'inline_query',
'shipping_query',
'pre_checkout_query',
'message',
'poll',
'poll_answer',
'my_chat_member',
'chat_member'
]
const MessageSubTypes = [
'voice',
'video_note',
'video',
'animation',
'venue',
'text',
'supergroup_chat_created',
'successful_payment',
'sticker',
'pinned_message',
'photo',
'new_chat_title',
'new_chat_photo',
'new_chat_members',
'migrate_to_chat_id',
'migrate_from_chat_id',
'location',
'left_chat_member',
'invoice',
'group_chat_created',
'game',
'dice',
'document',
'delete_chat_photo',
'contact',
'channel_chat_created',
'audio',
'connected_website',
'passport_data',
'poll',
'forward_date',
'message_auto_delete_timer_changed',
'video_chat_started',
'video_chat_ended',
'video_chat_participants_invited',
'video_chat_scheduled',
'web_app_data'
]
const MessageSubTypesMapping = {
forward_date: 'forward'
}
class TelegrafContext {
constructor (update, telegram, options) {
this.tg = telegram
this.update = update
this.options = options
this.updateType = UpdateTypes.find((key) => key in this.update)
if (this.updateType === 'message' || (this.options.channelMode && this.updateType === 'channel_post')) {
this.updateSubTypes = MessageSubTypes
.filter((key) => key in this.update[this.updateType])
.map((type) => MessageSubTypesMapping[type] || type)
} else {
this.updateSubTypes = []
}
Object.getOwnPropertyNames(TelegrafContext.prototype)
.filter((key) => key !== 'constructor' && typeof this[key] === 'function')
.forEach((key) => (this[key] = this[key].bind(this)))
}
get me () {
return this.options && this.options.username
}
get telegram () {
return this.tg
}
get message () {
return this.update.message
}
get editedMessage () {
return this.update.edited_message
}
get inlineQuery () {
return this.update.inline_query
}
get shippingQuery () {
return this.update.shipping_query
}
get preCheckoutQuery () {
return this.update.pre_checkout_query
}
get chosenInlineResult () {
return this.update.chosen_inline_result
}
get channelPost () {
return this.update.channel_post
}
get editedChannelPost () {
return this.update.edited_channel_post
}
get callbackQuery () {
return this.update.callback_query
}
get poll () {
return this.update.poll
}
get pollAnswer () {
return this.update.poll_answer
}
get myChatMember () {
return this.update.my_chat_member
}
get chatMember () {
return this.update.chat_member
}
get chat () {
return (this.message && this.message.chat) ||
(this.editedMessage && this.editedMessage.chat) ||
(this.callbackQuery && this.callbackQuery.message && this.callbackQuery.message.chat) ||
(this.channelPost && this.channelPost.chat) ||
(this.editedChannelPost && this.editedChannelPost.chat) ||
(this.myChatMember && this.myChatMember.chat) ||
(this.chatMember && this.chatMember.chat)
}
get from () {
return (this.message && this.message.from) ||
(this.editedMessage && this.editedMessage.from) ||
(this.callbackQuery && this.callbackQuery.from) ||
(this.inlineQuery && this.inlineQuery.from) ||
(this.channelPost && this.channelPost.from) ||
(this.editedChannelPost && this.editedChannelPost.from) ||
(this.shippingQuery && this.shippingQuery.from) ||
(this.preCheckoutQuery && this.preCheckoutQuery.from) ||
(this.chosenInlineResult && this.chosenInlineResult.from) ||
(this.myChatMember && this.myChatMember.from) ||
(this.chatMember && this.chatMember.from)
}
get inlineMessageId () {
return (this.callbackQuery && this.callbackQuery.inline_message_id) || (this.chosenInlineResult && this.chosenInlineResult.inline_message_id)
}
get passportData () {
return this.message && this.message.passport_data
}
get state () {
if (!this.contextState) {
this.contextState = {}
}
return this.contextState
}
set state (value) {
this.contextState = { ...value }
}
get webhookReply () {
return this.tg.webhookReply
}
set webhookReply (enable) {
this.tg.webhookReply = enable
}
assert (value, method) {
if (!value) {
throw new Error(`Telegraf: "${method}" isn't available for "${this.updateType}::${this.updateSubTypes}"`)
}
}
answerInlineQuery (...args) {
this.assert(this.inlineQuery, 'answerInlineQuery')
return this.telegram.answerInlineQuery(this.inlineQuery.id, ...args)
}
answerCbQuery (...args) {
this.assert(this.callbackQuery, 'answerCbQuery')
return this.telegram.answerCbQuery(this.callbackQuery.id, ...args)
}
answerGameQuery (...args) {
this.assert(this.callbackQuery, 'answerGameQuery')
return this.telegram.answerGameQuery(this.callbackQuery.id, ...args)
}
answerShippingQuery (...args) {
this.assert(this.shippingQuery, 'answerShippingQuery')
return this.telegram.answerShippingQuery(this.shippingQuery.id, ...args)
}
answerPreCheckoutQuery (...args) {
this.assert(this.preCheckoutQuery, 'answerPreCheckoutQuery')
return this.telegram.answerPreCheckoutQuery(this.preCheckoutQuery.id, ...args)
}
editMessageText (text, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageText')
return this.inlineMessageId
? this.telegram.editMessageText(
undefined,
undefined,
this.inlineMessageId,
text,
extra
)
: this.telegram.editMessageText(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
text,
extra
)
}
editMessageCaption (caption, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageCaption')
return this.inlineMessageId
? this.telegram.editMessageCaption(
undefined,
undefined,
this.inlineMessageId,
caption,
extra
)
: this.telegram.editMessageCaption(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
caption,
extra
)
}
editMessageMedia (media, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageMedia')
return this.inlineMessageId
? this.telegram.editMessageMedia(
undefined,
undefined,
this.inlineMessageId,
media,
extra
)
: this.telegram.editMessageMedia(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
media,
extra
)
}
editMessageReplyMarkup (markup) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageReplyMarkup')
return this.inlineMessageId
? this.telegram.editMessageReplyMarkup(
undefined,
undefined,
this.inlineMessageId,
markup
)
: this.telegram.editMessageReplyMarkup(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
markup
)
}
editMessageLiveLocation (latitude, longitude, extra) {
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageLiveLocation')
return this.inlineMessageId
? this.telegram.editMessageLiveLocation(
undefined,
undefined,
this.inlineMessageId,
latitude,
longitude,
extra
)
: this.telegram.editMessageLiveLocation(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
latitude,
longitude,
extra
)
}
stopMessageLiveLocation (markup) {
this.assert(this.callbackQuery || this.inlineMessageId, 'stopMessageLiveLocation')
return this.inlineMessageId
? this.telegram.stopMessageLiveLocation(
undefined,
undefined,
this.inlineMessageId,
markup
)
: this.telegram.stopMessageLiveLocation(
this.chat.id,
this.callbackQuery.message.message_id,
undefined,
markup
)
}
reply (text, args) {
this.assert(this.chat, 'reply')
const extra = this.options.parseMode
? { parse_mode: this.options.parseMode }
: { ...args }
return this.telegram.sendMessage(this.chat.id, text, extra)
}
getChat (...args) {
this.assert(this.chat, 'getChat')
return this.telegram.getChat(this.chat.id, ...args)
}
exportChatInviteLink (...args) {
this.assert(this.chat, 'exportChatInviteLink')
return this.telegram.exportChatInviteLink(this.chat.id, ...args)
}
banChatMember (...args) {
this.assert(this.chat, 'banChatMember')
return this.telegram.banChatMember(this.chat.id, ...args)
}
kickChatMember (...args) {
this.assert(this.chat, 'kickChatMember')
return this.telegram.kickChatMember(this.chat.id, ...args)
}
unbanChatMember (...args) {
this.assert(this.chat, 'unbanChatMember')
return this.telegram.unbanChatMember(this.chat.id, ...args)
}
restrictChatMember (...args) {
this.assert(this.chat, 'restrictChatMember')
return this.telegram.restrictChatMember(this.chat.id, ...args)
}
promoteChatMember (...args) {
this.assert(this.chat, 'promoteChatMember')
return this.telegram.promoteChatMember(this.chat.id, ...args)
}
setChatAdministratorCustomTitle (...args) {
this.assert(this.chat, 'setChatAdministratorCustomTitle')
return this.telegram.setChatAdministratorCustomTitle(this.chat.id, ...args)
}
banChatSenderChat (...args) {
this.assert(this.chat, 'banChatSenderChat')
return this.telegram.banChatSenderChat(this.chat.id, ...args)
}
unbanChatSenderChat (...args) {
this.assert(this.chat, 'unbanChatSenderChat')
return this.telegram.unbanChatSenderChat(this.chat.id, ...args)
}
setChatPhoto (...args) {
this.assert(this.chat, 'setChatPhoto')
return this.telegram.setChatPhoto(this.chat.id, ...args)
}
deleteChatPhoto (...args) {
this.assert(this.chat, 'deleteChatPhoto')
return this.telegram.deleteChatPhoto(this.chat.id, ...args)
}
setChatTitle (...args) {
this.assert(this.chat, 'setChatTitle')
return this.telegram.setChatTitle(this.chat.id, ...args)
}
setChatDescription (...args) {
this.assert(this.chat, 'setChatDescription')
return this.telegram.setChatDescription(this.chat.id, ...args)
}
pinChatMessage (...args) {
this.assert(this.chat, 'pinChatMessage')
return this.telegram.pinChatMessage(this.chat.id, ...args)
}
unpinChatMessage (...args) {
this.assert(this.chat, 'unpinChatMessage')
return this.telegram.unpinChatMessage(this.chat.id, ...args)
}
unpinAllChatMessages () {
this.assert(this.chat, 'unpinAllChatMessages')
return this.telegram.unpinAllChatMessages(this.chat.id)
}
leaveChat (...args) {
this.assert(this.chat, 'leaveChat')
return this.telegram.leaveChat(this.chat.id, ...args)
}
setChatPermissions (...args) {
this.assert(this.chat, 'setChatPermissions')
return this.telegram.setChatPermissions(this.chat.id, ...args)
}
getChatAdministrators (...args) {
this.assert(this.chat, 'getChatAdministrators')
return this.telegram.getChatAdministrators(this.chat.id, ...args)
}
getChatMember (...args) {
this.assert(this.chat, 'getChatMember')
return this.telegram.getChatMember(this.chat.id, ...args)
}
getChatMembersCount (...args) {
this.assert(this.chat, 'getChatMembersCount')
return this.telegram.getChatMemberCount(this.chat.id, ...args)
}
getChatMemberCount (...args) {
this.assert(this.chat, 'getChatMemberCount')
return this.telegram.getChatMemberCount(this.chat.id, ...args)
}
setPassportDataErrors (errors) {
this.assert(this.chat, 'setPassportDataErrors')
return this.telegram.setPassportDataErrors(this.from.id, errors)
}
replyWithPhoto (...args) {
this.assert(this.chat, 'replyWithPhoto')
return this.telegram.sendPhoto(this.chat.id, ...args)
}
replyWithMediaGroup (...args) {
this.assert(this.chat, 'replyWithMediaGroup')
return this.telegram.sendMediaGroup(this.chat.id, ...args)
}
replyWithAudio (...args) {
this.assert(this.chat, 'replyWithAudio')
return this.telegram.sendAudio(this.chat.id, ...args)
}
replyWithDice (...args) {
this.assert(this.chat, 'replyWithDice')
return this.telegram.sendDice(this.chat.id, ...args)
}
replyWithDocument (...args) {
this.assert(this.chat, 'replyWithDocument')
return this.telegram.sendDocument(this.chat.id, ...args)
}
replyWithSticker (...args) {
this.assert(this.chat, 'replyWithSticker')
return this.telegram.sendSticker(this.chat.id, ...args)
}
replyWithVideo (...args) {
this.assert(this.chat, 'replyWithVideo')
return this.telegram.sendVideo(this.chat.id, ...args)
}
replyWithAnimation (...args) {
this.assert(this.chat, 'replyWithAnimation')
return this.telegram.sendAnimation(this.chat.id, ...args)
}
replyWithVideoNote (...args) {
this.assert(this.chat, 'replyWithVideoNote')
return this.telegram.sendVideoNote(this.chat.id, ...args)
}
replyWithInvoice (...args) {
this.assert(this.chat, 'replyWithInvoice')
return this.telegram.sendInvoice(this.chat.id, ...args)
}
replyWithGame (...args) {
this.assert(this.chat, 'replyWithGame')
return this.telegram.sendGame(this.chat.id, ...args)
}
replyWithVoice (...args) {
this.assert(this.chat, 'replyWithVoice')
return this.telegram.sendVoice(this.chat.id, ...args)
}
replyWithPoll (...args) {
this.assert(this.chat, 'replyWithPoll')
return this.telegram.sendPoll(this.chat.id, ...args)
}
replyWithQuiz (...args) {
this.assert(this.chat, 'replyWithQuiz')
return this.telegram.sendQuiz(this.chat.id, ...args)
}
stopPoll (...args) {
this.assert(this.chat, 'stopPoll')
return this.telegram.stopPoll(this.chat.id, ...args)
}
replyWithChatAction (...args) {
this.assert(this.chat, 'replyWithChatAction')
return this.telegram.sendChatAction(this.chat.id, ...args)
}
replyWithLocation (...args) {
this.assert(this.chat, 'replyWithLocation')
return this.telegram.sendLocation(this.chat.id, ...args)
}
replyWithVenue (...args) {
this.assert(this.chat, 'replyWithVenue')
return this.telegram.sendVenue(this.chat.id, ...args)
}
replyWithContact (...args) {
this.assert(this.from, 'replyWithContact')
return this.telegram.sendContact(this.chat.id, ...args)
}
getStickerSet (setName) {
return this.telegram.getStickerSet(setName)
}
setChatStickerSet (setName) {
this.assert(this.chat, 'setChatStickerSet')
return this.telegram.setChatStickerSet(this.chat.id, setName)
}
deleteChatStickerSet () {
this.assert(this.chat, 'deleteChatStickerSet')
return this.telegram.deleteChatStickerSet(this.chat.id)
}
setStickerPositionInSet (sticker, position) {
return this.telegram.setStickerPositionInSet(sticker, position)
}
setStickerSetThumb (...args) {
return this.telegram.setStickerSetThumb(...args)
}
deleteStickerFromSet (sticker) {
return this.telegram.deleteStickerFromSet(sticker)
}
uploadStickerFile (...args) {
this.assert(this.from, 'uploadStickerFile')
return this.telegram.uploadStickerFile(this.from.id, ...args)
}
createNewStickerSet (...args) {
this.assert(this.from, 'createNewStickerSet')
return this.telegram.createNewStickerSet(this.from.id, ...args)
}
addStickerToSet (...args) {
this.assert(this.from, 'addStickerToSet')
return this.telegram.addStickerToSet(this.from.id, ...args)
}
getMyCommands (...args) {
return this.telegram.getMyCommands(...args)
}
setMyCommands (...args) {
return this.telegram.setMyCommands(...args)
}
deleteMyCommands (...args) {
return this.telegram.deleteMyCommands(...args)
}
replyWithMarkdown (markdown, extra) {
return this.reply(markdown, { parse_mode: 'Markdown', ...extra })
}
replyWithMarkdownV2 (markdown, extra) {
return this.reply(markdown, { parse_mode: 'MarkdownV2', ...extra })
}
replyWithHTML (html, extra) {
return this.reply(html, { parse_mode: 'HTML', ...extra })
}
deleteMessage (messageId) {
this.assert(this.chat, 'deleteMessage')
if (typeof messageId !== 'undefined') {
return this.telegram.deleteMessage(this.chat.id, messageId)
}
const message = this.message ||
this.editedMessage ||
this.channelPost ||
this.editedChannelPost ||
(this.callbackQuery && this.callbackQuery.message)
this.assert(message, 'deleteMessage')
return this.telegram.deleteMessage(this.chat.id, message.message_id)
}
forwardMessage (chatId, extra) {
this.assert(this.chat, 'forwardMessage')
const message = this.message ||
this.editedMessage ||
this.channelPost ||
this.editedChannelPost ||
(this.callbackQuery && this.callbackQuery.message)
this.assert(message, 'forwardMessage')
return this.telegram.forwardMessage(chatId, this.chat.id, message.message_id, extra)
}
copyMessage (chatId, extra) {
const message = this.message ||
this.editedMessage ||
this.channelPost ||
this.editedChannelPost ||
(this.callbackQuery && this.callbackQuery.message)
this.assert(message, 'copyMessage')
return this.telegram.copyMessage(chatId, message.chat.id, message.message_id, extra)
}
createChatInviteLink (...args) {
this.assert(this.chat, 'createChatInviteLink')
return this.telegram.createChatInviteLink(this.chat.id, ...args)
}
editChatInviteLink (...args) {
this.assert(this.chat, 'editChatInviteLink')
return this.telegram.editChatInviteLink(this.chat.id, ...args)
}
revokeChatInviteLink (...args) {
this.assert(this.chat, 'revokeChatInviteLink')
return this.telegram.revokeChatInviteLink(this.chat.id, ...args)
}
approveChatJoinRequest (...args) {
this.assert(this.chat, 'approveChatJoinRequest')
return this.telegram.approveChatJoinRequest(this.chat.id, ...args)
}
declineChatJoinRequest (...args) {
this.assert(this.chat, 'declineChatJoinRequest')
return this.telegram.declineChatJoinRequest(this.chat.id, ...args)
}
setChatMenuButton (...args) {
this.assert(this.chat, 'setChatMenuButton')
return this.telegram.setChatMenuButton(this.chat.id, ...args)
}
getChatMenuButton () {
this.assert(this.chat, 'getChatMenuButton')
return this.telegram.getChatMenuButton(this.chat.id)
}
setMyDefaultAdministratorRights (rights, forChannels) {
return this.telegram.setMyDefaultAdministratorRights(rights, forChannels)
}
getMyDefaultAdministratorRights (forChannels) {
return this.telegram.getMyDefaultAdministratorRights(forChannels)
}
}
module.exports = TelegrafContext

282
node_modules/telegraf/core/network/client.js generated vendored Normal file
View File

@@ -0,0 +1,282 @@
const debug = require('debug')('telegraf:client')
const crypto = require('crypto')
const fetch = require('node-fetch').default
const fs = require('fs')
const https = require('https')
const path = require('path')
const TelegramError = require('./error')
const MultipartStream = require('./multipart-stream')
const { isStream } = MultipartStream
const WEBHOOK_ALLOWLIST = [
'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',
webhookReply: false,
agent: new https.Agent({
keepAlive: true,
keepAliveMsecs: 10000
})
}
const WEBHOOK_REPLY_STUB = {
webhook: true,
details: 'https://core.telegram.org/bots/api#making-requests-when-getting-updates'
}
function safeJSONParse (text) {
try {
return JSON.parse(text)
} catch (err) {
debug('JSON parse failed', err)
}
}
function includesMedia (payload) {
return Object.keys(payload).some(
(key) => {
const value = payload[key]
if (Array.isArray(value)) {
return value.some(({ media }) => media && typeof media === 'object' && (media.source || media.url))
}
return (typeof value === 'object') && (
value.source ||
value.url ||
(typeof value.media === 'object' && (value.media.source || value.media.url))
)
}
)
}
function buildJSONConfig (payload) {
return Promise.resolve({
method: 'POST',
compress: true,
headers: { 'content-type': 'application/json', connection: 'keep-alive' },
body: JSON.stringify(payload)
})
}
const FORM_DATA_JSON_FIELDS = [
'results',
'reply_markup',
'mask_position',
'shipping_options',
'errors'
]
function buildFormDataConfig (payload, agent) {
for (const field of FORM_DATA_JSON_FIELDS) {
if (field in payload && typeof payload[field] !== 'string') {
payload[field] = JSON.stringify(payload[field])
}
}
const boundary = crypto.randomBytes(32).toString('hex')
const formData = new MultipartStream(boundary)
const tasks = Object.keys(payload).map((key) => attachFormValue(formData, key, payload[key], agent))
return Promise.all(tasks).then(() => {
return {
method: 'POST',
compress: true,
headers: { 'content-type': `multipart/form-data; boundary=${boundary}`, connection: 'keep-alive' },
body: formData
}
})
}
function attachFormValue (form, id, value, agent) {
if (!value) {
return Promise.resolve()
}
const valueType = typeof value
if (valueType === 'string' || valueType === 'boolean' || valueType === 'number') {
form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: `${value}`
})
return Promise.resolve()
}
if (id === 'thumb') {
const attachmentId = crypto.randomBytes(16).toString('hex')
return attachFormMedia(form, value, attachmentId, agent)
.then(() => form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: `attach://${attachmentId}`
}))
}
if (Array.isArray(value)) {
return Promise.all(
value.map((item) => {
if (typeof item.media !== 'object') {
return Promise.resolve(item)
}
const attachmentId = crypto.randomBytes(16).toString('hex')
return attachFormMedia(form, item.media, attachmentId, agent)
.then(() => ({ ...item, media: `attach://${attachmentId}` }))
})
).then((items) => form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: JSON.stringify(items)
}))
}
if (typeof value.media !== 'undefined' && typeof value.type !== 'undefined') {
const attachmentId = crypto.randomBytes(16).toString('hex')
return attachFormMedia(form, value.media, attachmentId, agent)
.then(() => form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"` },
body: JSON.stringify({
...value,
media: `attach://${attachmentId}`
})
}))
}
return attachFormMedia(form, value, id, agent)
}
function attachFormMedia (form, media, id, agent) {
let fileName = media.filename || `${id}.${DEFAULT_EXTENSIONS[id] || 'dat'}`
if (media.url) {
return fetch(media.url, { agent }).then((res) =>
form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"; filename="${fileName}"` },
body: res.body
})
)
}
if (media.source) {
if (fs.existsSync(media.source)) {
fileName = media.filename || path.basename(media.source)
media.source = fs.createReadStream(media.source)
}
if (isStream(media.source) || Buffer.isBuffer(media.source)) {
form.addPart({
headers: { 'content-disposition': `form-data; name="${id}"; filename="${fileName}"` },
body: media.source
})
}
}
return Promise.resolve()
}
function isKoaResponse (response) {
return typeof response.set === 'function' && typeof response.header === 'object'
}
function answerToWebhook (response, payload = {}, options) {
if (!includesMedia(payload)) {
if (isKoaResponse(response)) {
response.body = payload
return Promise.resolve(WEBHOOK_REPLY_STUB)
}
if (!response.headersSent) {
response.setHeader('content-type', 'application/json')
}
return new Promise((resolve) => {
if (response.end.length === 2) {
response.end(JSON.stringify(payload), 'utf-8')
return resolve(WEBHOOK_REPLY_STUB)
}
response.end(JSON.stringify(payload), 'utf-8', () => resolve(WEBHOOK_REPLY_STUB))
})
}
return buildFormDataConfig(payload, options.agent)
.then(({ headers, body }) => {
if (isKoaResponse(response)) {
Object.keys(headers).forEach(key => response.set(key, headers[key]))
response.body = body
return Promise.resolve(WEBHOOK_REPLY_STUB)
}
if (!response.headersSent) {
Object.keys(headers).forEach(key => response.setHeader(key, headers[key]))
}
return new Promise((resolve) => {
response.on('finish', () => resolve(WEBHOOK_REPLY_STUB))
body.pipe(response)
})
})
}
class ApiClient {
constructor (token, options, webhookResponse) {
this.token = token
this.options = {
...DEFAULT_OPTIONS,
...options
}
if (this.options.apiRoot.startsWith('http://')) {
this.options.agent = null
}
this.response = webhookResponse
}
set webhookReply (enable) {
this.options.webhookReply = enable
}
get webhookReply () {
return this.options.webhookReply
}
callApi (method, data = {}) {
const { token, options, response, responseEnd } = this
const payload = Object.keys(data)
.filter((key) => typeof data[key] !== 'undefined' && data[key] !== null)
.reduce((acc, key) => ({ ...acc, [key]: data[key] }), {})
if (options.webhookReply && response && !responseEnd && WEBHOOK_ALLOWLIST.includes(method)) {
debug('Call via webhook', method, payload)
this.responseEnd = true
return answerToWebhook(response, { method, ...payload }, options)
}
if (!token) {
throw new TelegramError({ error_code: 401, description: 'Bot Token is required' })
}
debug('HTTP call', method, payload)
const buildConfig = includesMedia(payload)
? buildFormDataConfig({ method, ...payload }, options.agent)
: buildJSONConfig(payload)
return buildConfig
.then((config) => {
const apiUrl = `${options.apiRoot}/bot${token}/${method}`
config.agent = options.agent
return fetch(apiUrl, config)
})
.then((res) => res.text())
.then((text) => {
return safeJSONParse(text) || {
error_code: 500,
description: 'Unsupported http response from Telegram',
response: text
}
})
.then((data) => {
if (!data.ok) {
debug('API call failed', data)
throw new TelegramError(data, { method, payload })
}
return data.result
})
}
}
module.exports = ApiClient

12
node_modules/telegraf/core/network/error.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
class TelegramError extends Error {
constructor (payload = {}, on) {
super(`${payload.error_code}: ${payload.description}`)
this.code = payload.error_code
this.response = payload
this.description = payload.description
this.parameters = payload.parameters || {}
this.on = on || {}
}
}
module.exports = TelegramError

37
node_modules/telegraf/core/network/multipart-stream.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
const stream = require('stream')
const { SandwichStream } = require('sandwich-stream')
const CRNL = '\r\n'
class MultipartStream extends SandwichStream {
constructor (boundary) {
super({
head: `--${boundary}${CRNL}`,
tail: `${CRNL}--${boundary}--`,
separator: `${CRNL}--${boundary}${CRNL}`
})
}
addPart (part) {
part = part || {}
const partStream = new stream.PassThrough()
if (part.headers) {
for (const key in part.headers) {
const header = part.headers[key]
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 stream && typeof stream === 'object' && typeof stream.pipe === 'function'
}
}
module.exports = MultipartStream

39
node_modules/telegraf/core/network/webhook.js generated vendored Normal file
View File

@@ -0,0 +1,39 @@
const debug = require('debug')('telegraf:webhook')
module.exports = function (hookPath, updateHandler, errorHandler) {
return (req, res, next) => {
debug('Incoming request', req.method, req.url)
if (req.method !== 'POST' || req.url !== hookPath) {
if (typeof next === 'function') {
return next()
}
res.statusCode = 403
return res.end()
}
let body = ''
req.on('data', (chunk) => {
body += chunk.toString()
})
req.on('end', () => {
let update = {}
try {
update = JSON.parse(body)
} catch (error) {
res.writeHead(415)
res.end()
return errorHandler(error)
}
updateHandler(update, res)
.then(() => {
if (!res.finished) {
res.end()
}
})
.catch((err) => {
debug('Webhook error', err)
res.writeHead(500)
res.end()
})
})
}
}

140
node_modules/telegraf/core/replicators.js generated vendored Normal file
View File

@@ -0,0 +1,140 @@
const { formatHTML } = require('../markup')
module.exports = {
copyMethods: {
audio: 'sendAudio',
contact: 'sendContact',
document: 'sendDocument',
location: 'sendLocation',
photo: 'sendPhoto',
sticker: 'sendSticker',
text: 'sendMessage',
venue: 'sendVenue',
video: 'sendVideo',
video_note: 'sendVideoNote',
animation: 'sendAnimation',
voice: 'sendVoice',
poll: 'sendPoll'
},
text: (message) => {
const entities = message.entities || []
return {
reply_markup: message.reply_markup,
parse_mode: entities.length > 0 ? 'HTML' : '',
text: formatHTML(message.text, entities)
}
},
contact: (message) => {
return {
reply_markup: message.reply_markup,
phone_number: message.contact.phone_number,
first_name: message.contact.first_name,
last_name: message.contact.last_name
}
},
location: (message) => {
return {
reply_markup: message.reply_markup,
latitude: message.location.latitude,
longitude: message.location.longitude
}
},
venue: (message) => {
return {
reply_markup: message.reply_markup,
latitude: message.venue.location.latitude,
longitude: message.venue.location.longitude,
title: message.venue.title,
address: message.venue.address,
foursquare_id: message.venue.foursquare_id
}
},
voice: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
voice: message.voice.file_id,
duration: message.voice.duration,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : ''
}
},
audio: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
audio: message.audio.file_id,
thumb: message.audio.thumb,
duration: message.audio.duration,
performer: message.audio.performer,
title: message.audio.title,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : ''
}
},
video: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
video: message.video.file_id,
thumb: message.video.thumb,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : '',
duration: message.video.duration,
width: message.video.width,
height: message.video.height,
supports_streaming: !!message.video.supports_streaming
}
},
document: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
document: message.document.file_id,
caption: formatHTML(message.caption, entities),
parse_mode: entities.length > 0 ? 'HTML' : ''
}
},
sticker: (message) => {
return {
reply_markup: message.reply_markup,
sticker: message.sticker.file_id
}
},
photo: (message) => {
const entities = message.caption_entities || []
return {
reply_markup: message.reply_markup,
photo: message.photo[message.photo.length - 1].file_id,
parse_mode: entities.length > 0 ? 'HTML' : '',
caption: formatHTML(message.caption, entities)
}
},
video_note: (message) => {
return {
reply_markup: message.reply_markup,
video_note: message.video_note.file_id,
thumb: message.video_note.thumb,
length: message.video_note.length,
duration: message.video_note.duration
}
},
animation: (message) => {
return {
reply_markup: message.reply_markup,
animation: message.animation.file_id,
thumb: message.animation.thumb,
duration: message.animation.duration
}
},
poll: (message) => {
return {
question: message.poll.question,
type: message.poll.type,
is_anonymous: message.poll.is_anonymous,
allows_multiple_answers: message.poll.allows_multiple_answers,
correct_option_id: message.poll.correct_option_id,
options: message.poll.options.map(({ text }) => text)
}
}
}

94
node_modules/telegraf/extra.js generated vendored Normal file
View File

@@ -0,0 +1,94 @@
const Markup = require('./markup')
class Extra {
constructor (opts) {
this.load(opts)
}
load (opts = {}) {
return Object.assign(this, opts)
}
inReplyTo (messageId) {
this.reply_to_message_id = messageId
return this
}
notifications (value = true) {
this.disable_notification = !value
return this
}
webPreview (value = true) {
this.disable_web_page_preview = !value
return this
}
markup (markup) {
if (typeof markup === 'function') {
markup = markup(new Markup())
}
this.reply_markup = { ...markup }
return this
}
HTML (value = true) {
this.parse_mode = value ? 'HTML' : undefined
return this
}
markdown (value = true) {
this.parse_mode = value ? 'Markdown' : undefined
return this
}
markdownV2 (value = true) {
this.parse_mode = value ? 'MarkdownV2' : undefined
return this
}
caption (caption = '') {
this.caption = caption
return this
}
static inReplyTo (messageId) {
return new Extra().inReplyTo(messageId)
}
static notifications (value) {
return new Extra().notifications(value)
}
static webPreview (value) {
return new Extra().webPreview(value)
}
static load (opts) {
return new Extra(opts)
}
static markup (markup) {
return new Extra().markup(markup)
}
static HTML (value) {
return new Extra().HTML(value)
}
static markdown (value) {
return new Extra().markdown(value)
}
static markdownV2 (value) {
return new Extra().markdownV2(value)
}
static caption (caption) {
return new Extra().caption(caption)
}
}
Extra.Markup = Markup
module.exports = Extra

306
node_modules/telegraf/markup.js generated vendored Normal file
View File

@@ -0,0 +1,306 @@
class Markup {
forceReply (value = true) {
this.force_reply = value
return this
}
removeKeyboard (value = true) {
this.remove_keyboard = value
return this
}
inputFieldPlaceholder (placeholder) {
this.input_field_placeholder = placeholder
return this
}
selective (value = true) {
this.selective = value
return this
}
extra (options) {
return {
reply_markup: { ...this },
...options
}
}
keyboard (buttons, options) {
const keyboard = buildKeyboard(buttons, { columns: 1, ...options })
if (keyboard && keyboard.length > 0) {
this.keyboard = keyboard
}
return this
}
resize (value = true) {
this.resize_keyboard = value
return this
}
oneTime (value = true) {
this.one_time_keyboard = value
return this
}
inlineKeyboard (buttons, options) {
const keyboard = buildKeyboard(buttons, { columns: buttons.length, ...options })
if (keyboard && keyboard.length > 0) {
this.inline_keyboard = keyboard
}
return this
}
button (text, hide) {
return Markup.button(text, hide)
}
contactRequestButton (text, hide) {
return Markup.contactRequestButton(text, hide)
}
locationRequestButton (text, hide) {
return Markup.locationRequestButton(text, hide)
}
pollRequestButton (text, type, hide) {
return Markup.pollRequestButton(text, type, hide)
}
urlButton (text, url, hide) {
return Markup.urlButton(text, url, hide)
}
callbackButton (text, data, hide) {
return Markup.callbackButton(text, data, hide)
}
switchToChatButton (text, value, hide) {
return Markup.switchToChatButton(text, value, hide)
}
switchToCurrentChatButton (text, value, hide) {
return Markup.switchToCurrentChatButton(text, value, hide)
}
gameButton (text, hide) {
return Markup.gameButton(text, hide)
}
payButton (text, hide) {
return Markup.payButton(text, hide)
}
loginButton (text, url, opts, hide) {
return Markup.loginButton(text, url, opts, hide)
}
static removeKeyboard (value) {
return new Markup().removeKeyboard(value)
}
static forceReply (value) {
return new Markup().forceReply(value)
}
static keyboard (buttons, options) {
return new Markup().keyboard(buttons, options)
}
static inlineKeyboard (buttons, options) {
return new Markup().inlineKeyboard(buttons, options)
}
static resize (value = true) {
return new Markup().resize(value)
}
static inputFieldPlaceholder (placeholder) {
return new Markup().inputFieldPlaceholder(placeholder)
}
static selective (value = true) {
return new Markup().selective(value)
}
static oneTime (value = true) {
return new Markup().oneTime(value)
}
static button (text, hide = false) {
return { text: text, hide: hide }
}
static contactRequestButton (text, hide = false) {
return { text: text, request_contact: true, hide: hide }
}
static locationRequestButton (text, hide = false) {
return { text: text, request_location: true, hide: hide }
}
static pollRequestButton (text, type, hide = false) {
return { text: text, request_poll: { type }, hide: hide }
}
static urlButton (text, url, hide = false) {
return { text: text, url: url, hide: hide }
}
static callbackButton (text, data, hide = false) {
return { text: text, callback_data: data, hide: hide }
}
static switchToChatButton (text, value, hide = false) {
return { text: text, switch_inline_query: value, hide: hide }
}
static switchToCurrentChatButton (text, value, hide = false) {
return { text: text, switch_inline_query_current_chat: value, hide: hide }
}
static gameButton (text, hide = false) {
return { text: text, callback_game: {}, hide: hide }
}
static payButton (text, hide = false) {
return { text: text, pay: true, hide: hide }
}
static loginButton (text, url, opts = {}, hide = false) {
return {
text: text,
login_url: { ...opts, url: url },
hide: hide
}
}
static formatHTML (text = '', entities = []) {
const available = [...entities]
const opened = []
const result = []
for (let offset = 0; offset < text.length; offset++) {
while (true) {
const index = available.findIndex((entity) => entity.offset === offset)
if (index === -1) {
break
}
const entity = available[index]
switch (entity.type) {
case 'bold':
result.push('<b>')
break
case 'italic':
result.push('<i>')
break
case 'code':
result.push('<code>')
break
case 'pre':
if (entity.language) {
result.push(`<pre><code class="language-${entity.language}">`)
} else {
result.push('<pre>')
}
break
case 'strikethrough':
result.push('<s>')
break
case 'underline':
result.push('<u>')
break
case 'text_mention':
result.push(`<a href="tg://user?id=${entity.user.id}">`)
break
case 'text_link':
result.push(`<a href="${entity.url}">`)
break
}
opened.unshift(entity)
available.splice(index, 1)
}
result.push(escapeHTML(text[offset]))
while (true) {
const index = opened.findIndex((entity) => entity.offset + entity.length - 1 === offset)
if (index === -1) {
break
}
const entity = opened[index]
switch (entity.type) {
case 'bold':
result.push('</b>')
break
case 'italic':
result.push('</i>')
break
case 'code':
result.push('</code>')
break
case 'pre':
if (entity.language) {
result.push('</code></pre>')
} else {
result.push('</pre>')
}
break
case 'strikethrough':
result.push('</s>')
break
case 'underline':
result.push('</u>')
break
case 'text_mention':
case 'text_link':
result.push('</a>')
break
}
opened.splice(index, 1)
}
}
return result.join('')
}
}
const escapedChars = {
'"': '&quot;',
'&': '&amp;',
'<': '&lt;',
'>': '&gt;'
}
function escapeHTML (string) {
const chars = [...string]
return chars.map(char => escapedChars[char] || char).join('')
}
function buildKeyboard (buttons, options) {
const result = []
if (!Array.isArray(buttons)) {
return result
}
if (buttons.find(Array.isArray)) {
return buttons.map(row => row.filter((button) => !button.hide))
}
const wrapFn = options.wrap
? 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
}
module.exports = Markup

20
node_modules/telegraf/node_modules/debug/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,20 @@
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

481
node_modules/telegraf/node_modules/debug/README.md generated vendored Normal file
View File

@@ -0,0 +1,481 @@
# debug
[![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
<img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png">
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Usage in child processes
Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
For example:
```javascript
worker = fork(WORKER_WRAP_PATH, [workerPath], {
stdio: [
/* stdin: */ 0,
/* stdout: */ 'pipe',
/* stderr: */ 'pipe',
'ipc',
],
env: Object.assign({}, process.env, {
DEBUG_COLORS: 1 // without this settings, colors won't be shown
}),
});
worker.stderr.pipe(process.stderr, { end: false });
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

64
node_modules/telegraf/node_modules/debug/package.json generated vendored Normal file
View File

@@ -0,0 +1,64 @@
{
"name": "debug",
"version": "4.4.3",
"repository": {
"type": "git",
"url": "git://github.com/debug-js/debug.git"
},
"description": "Lightweight debugging utility for Node.js and the browser",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"LICENSE",
"README.md"
],
"author": "Josh Junon (https://github.com/qix-)",
"contributors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"scripts": {
"lint": "xo",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:node": "mocha test.js test.node.js",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls"
},
"dependencies": {
"ms": "^2.1.3"
},
"devDependencies": {
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"sinon": "^14.0.0",
"xo": "^0.23.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"engines": {
"node": ">=6.0"
},
"xo": {
"rules": {
"import/extensions": "off"
}
}
}

272
node_modules/telegraf/node_modules/debug/src/browser.js generated vendored Normal file
View File

@@ -0,0 +1,272 @@
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
let m;
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
// eslint-disable-next-line no-return-assign
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};

292
node_modules/telegraf/node_modules/debug/src/common.js generated vendored Normal file
View File

@@ -0,0 +1,292 @@
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === 'string' ? namespaces : '')
.trim()
.replace(/\s+/g, ',')
.split(',')
.filter(Boolean);
for (const ns of split) {
if (ns[0] === '-') {
createDebug.skips.push(ns.slice(1));
} else {
createDebug.names.push(ns);
}
}
}
/**
* Checks if the given string matches a namespace template, honoring
* asterisks as wildcards.
*
* @param {String} search
* @param {String} template
* @return {Boolean}
*/
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) {
if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
// Match character or proceed with wildcard
if (template[templateIndex] === '*') {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++; // Skip the '*'
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
// Backtrack to the last '*' and try to match more characters
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else {
return false; // No match
}
}
// Handle trailing '*' in template
while (templateIndex < template.length && template[templateIndex] === '*') {
templateIndex++;
}
return templateIndex === template.length;
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names,
...createDebug.skips.map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
for (const skip of createDebug.skips) {
if (matchesTemplate(name, skip)) {
return false;
}
}
for (const ns of createDebug.names) {
if (matchesTemplate(name, ns)) {
return true;
}
}
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;

10
node_modules/telegraf/node_modules/debug/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}

263
node_modules/telegraf/node_modules/debug/src/node.js generated vendored Normal file
View File

@@ -0,0 +1,263 @@
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};

162
node_modules/telegraf/node_modules/ms/index.js generated vendored Normal file
View File

@@ -0,0 +1,162 @@
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function (val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}

21
node_modules/telegraf/node_modules/ms/license.md generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 Vercel, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

38
node_modules/telegraf/node_modules/ms/package.json generated vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "ms",
"version": "2.1.3",
"description": "Tiny millisecond conversion utility",
"repository": "vercel/ms",
"main": "./index",
"files": [
"index.js"
],
"scripts": {
"precommit": "lint-staged",
"lint": "eslint lib/* bin/*",
"test": "mocha tests.js"
},
"eslintConfig": {
"extends": "eslint:recommended",
"env": {
"node": true,
"es6": true
}
},
"lint-staged": {
"*.js": [
"npm run lint",
"prettier --single-quote --write",
"git add"
]
},
"license": "MIT",
"devDependencies": {
"eslint": "4.18.2",
"expect.js": "0.3.1",
"husky": "0.14.3",
"lint-staged": "5.0.0",
"mocha": "4.0.1",
"prettier": "2.0.5"
}
}

59
node_modules/telegraf/node_modules/ms/readme.md generated vendored Normal file
View File

@@ -0,0 +1,59 @@
# ms
![CI](https://github.com/vercel/ms/workflows/CI/badge.svg)
Use this package to easily convert various time formats to milliseconds.
## Examples
```js
ms('2 days') // 172800000
ms('1d') // 86400000
ms('10h') // 36000000
ms('2.5 hrs') // 9000000
ms('2h') // 7200000
ms('1m') // 60000
ms('5s') // 5000
ms('1y') // 31557600000
ms('100') // 100
ms('-3 days') // -259200000
ms('-1h') // -3600000
ms('-200') // -200
```
### Convert from Milliseconds
```js
ms(60000) // "1m"
ms(2 * 60000) // "2m"
ms(-3 * 60000) // "-3m"
ms(ms('10 hours')) // "10h"
```
### Time Format Written-Out
```js
ms(60000, { long: true }) // "1 minute"
ms(2 * 60000, { long: true }) // "2 minutes"
ms(-3 * 60000, { long: true }) // "-3 minutes"
ms(ms('10 hours'), { long: true }) // "10 hours"
```
## Features
- Works both in [Node.js](https://nodejs.org) and in the browser
- If a number is supplied to `ms`, a string with a unit is returned
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
## Related Packages
- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
As always, you can run the tests using: `npm test`

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2016 David Frank
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

634
node_modules/telegraf/node_modules/node-fetch/README.md generated vendored Normal file
View File

@@ -0,0 +1,634 @@
node-fetch
==========
[![npm version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![coverage status][codecov-image]][codecov-url]
[![install size][install-size-image]][install-size-url]
[![Discord][discord-image]][discord-url]
A light-weight module that brings `window.fetch` to Node.js
(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567))
[![Backers][opencollective-image]][opencollective-url]
<!-- TOC -->
- [Motivation](#motivation)
- [Features](#features)
- [Difference from client-side fetch](#difference-from-client-side-fetch)
- [Installation](#installation)
- [Loading and configuring the module](#loading-and-configuring-the-module)
- [Common Usage](#common-usage)
- [Plain text or HTML](#plain-text-or-html)
- [JSON](#json)
- [Simple Post](#simple-post)
- [Post with JSON](#post-with-json)
- [Post with form parameters](#post-with-form-parameters)
- [Handling exceptions](#handling-exceptions)
- [Handling client and server errors](#handling-client-and-server-errors)
- [Advanced Usage](#advanced-usage)
- [Streams](#streams)
- [Buffer](#buffer)
- [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data)
- [Extract Set-Cookie Header](#extract-set-cookie-header)
- [Post data using a file stream](#post-data-using-a-file-stream)
- [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart)
- [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal)
- [API](#api)
- [fetch(url[, options])](#fetchurl-options)
- [Options](#options)
- [Class: Request](#class-request)
- [Class: Response](#class-response)
- [Class: Headers](#class-headers)
- [Interface: Body](#interface-body)
- [Class: FetchError](#class-fetcherror)
- [License](#license)
- [Acknowledgement](#acknowledgement)
<!-- /TOC -->
## Motivation
Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime.
See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side).
## Features
- Stay consistent with `window.fetch` API.
- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences.
- Use native promise but allow substituting it with [insert your favorite promise library].
- Use native Node streams for body on both request and response.
- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically.
- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting.
## Difference from client-side fetch
- See [Known Differences](LIMITS.md) for details.
- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue.
- Pull requests are welcomed too!
## Installation
Current stable release (`2.x`)
```sh
$ npm install node-fetch
```
## Loading and configuring the module
We suggest you load the module via `require` until the stabilization of ES modules in node:
```js
const fetch = require('node-fetch');
```
If you are using a Promise library other than native, set it through `fetch.Promise`:
```js
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
```
## Common Usage
NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences.
#### Plain text or HTML
```js
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
```
#### JSON
```js
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(json => console.log(json));
```
#### Simple Post
```js
fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(res => res.json()) // expecting a json response
.then(json => console.log(json));
```
#### Post with JSON
```js
const body = { a: 1 };
fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
```
#### Post with form parameters
`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods.
NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such:
```js
const { URLSearchParams } = require('url');
const params = new URLSearchParams();
params.append('a', 1);
fetch('https://httpbin.org/post', { method: 'POST', body: params })
.then(res => res.json())
.then(json => console.log(json));
```
#### Handling exceptions
NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information.
Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details.
```js
fetch('https://domain.invalid/')
.catch(err => console.error(err));
```
#### Handling client and server errors
It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:
```js
function checkStatus(res) {
if (res.ok) { // res.status >= 200 && res.status < 300
return res;
} else {
throw MyCustomError(res.statusText);
}
}
fetch('https://httpbin.org/status/400')
.then(checkStatus)
.then(res => console.log('will not get here...'))
```
## Advanced Usage
#### Streams
The "Node.js way" is to use streams when possible:
```js
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => {
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
});
```
In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch
errors -- the longer a response runs, the more likely it is to encounter an error.
```js
const fetch = require('node-fetch');
const response = await fetch('https://httpbin.org/stream/3');
try {
for await (const chunk of response.body) {
console.dir(JSON.parse(chunk.toString()));
}
} catch (err) {
console.error(err.stack);
}
```
In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams
did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors
directly from the stream and wait on it response to fully close.
```js
const fetch = require('node-fetch');
const read = async body => {
let error;
body.on('error', err => {
error = err;
});
for await (const chunk of body) {
console.dir(JSON.parse(chunk.toString()));
}
return new Promise((resolve, reject) => {
body.on('close', () => {
error ? reject(error) : resolve();
});
});
};
try {
const response = await fetch('https://httpbin.org/stream/3');
await read(response.body);
} catch (err) {
console.error(err.stack);
}
```
#### Buffer
If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API)
```js
const fileType = require('file-type');
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => res.buffer())
.then(buffer => fileType(buffer))
.then(type => { /* ... */ });
```
#### Accessing Headers and other Meta data
```js
fetch('https://github.com/')
.then(res => {
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers.raw());
console.log(res.headers.get('content-type'));
});
```
#### Extract Set-Cookie Header
Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API.
```js
fetch(url).then(res => {
// returns an array of values, instead of a string of comma-separated values
console.log(res.headers.raw()['set-cookie']);
});
```
#### Post data using a file stream
```js
const { createReadStream } = require('fs');
const stream = createReadStream('input.txt');
fetch('https://httpbin.org/post', { method: 'POST', body: stream })
.then(res => res.json())
.then(json => console.log(json));
```
#### Post with form-data (detect multipart)
```js
const FormData = require('form-data');
const form = new FormData();
form.append('a', 1);
fetch('https://httpbin.org/post', { method: 'POST', body: form })
.then(res => res.json())
.then(json => console.log(json));
// OR, using custom headers
// NOTE: getHeaders() is non-standard API
const form = new FormData();
form.append('a', 1);
const options = {
method: 'POST',
body: form,
headers: form.getHeaders()
}
fetch('https://httpbin.org/post', options)
.then(res => res.json())
.then(json => console.log(json));
```
#### Request cancellation with AbortSignal
> NOTE: You may cancel streamed requests only on Node >= v8.0.0
You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller).
An example of timing out a request after 150ms could be achieved as the following:
```js
import AbortController from 'abort-controller';
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
150,
);
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(
data => {
useData(data)
},
err => {
if (err.name === 'AbortError') {
// request was aborted
}
},
)
.finally(() => {
clearTimeout(timeout);
});
```
See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples.
## API
### fetch(url[, options])
- `url` A string representing the URL for fetching
- `options` [Options](#fetch-options) for the HTTP(S) request
- Returns: <code>Promise&lt;[Response](#class-response)&gt;</code>
Perform an HTTP(S) fetch.
`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`.
<a id="fetch-options"></a>
### Options
The default values are shown after each option key.
```js
{
// These properties are part of the Fetch Standard
method: 'GET',
headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below)
body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect
signal: null, // pass an instance of AbortSignal to optionally abort requests
// The following properties are node-fetch extensions
follow: 20, // maximum redirect count. 0 to not follow redirect
timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
compress: true, // support gzip/deflate content encoding. false to disable
size: 0, // maximum response body size in bytes. 0 to disable
agent: null // http(s).Agent instance or function that returns an instance (see below)
}
```
##### Default Headers
If no values are set, the following request headers will be sent automatically:
Header | Value
------------------- | --------------------------------------------------------
`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_
`Accept` | `*/*`
`Content-Length` | _(automatically calculated, if possible)_
`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_
`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)`
Note: when `body` is a `Stream`, `Content-Length` is not set automatically.
##### Custom Agent
The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:
- Support self-signed certificate
- Use only IPv4 or IPv6
- Custom DNS Lookup
See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information.
If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample.
In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol.
```js
const httpAgent = new http.Agent({
keepAlive: true
});
const httpsAgent = new https.Agent({
keepAlive: true
});
const options = {
agent: function (_parsedURL) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
}
```
<a id="class-request"></a>
### Class: Request
An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface.
Due to the nature of Node.js, the following properties are not implemented at this moment:
- `type`
- `destination`
- `referrer`
- `referrerPolicy`
- `mode`
- `credentials`
- `cache`
- `integrity`
- `keepalive`
The following node-fetch extension properties are provided:
- `follow`
- `compress`
- `counter`
- `agent`
See [options](#fetch-options) for exact meaning of these extensions.
#### new Request(input[, options])
<small>*(spec-compliant)*</small>
- `input` A string representing a URL, or another `Request` (which will be cloned)
- `options` [Options][#fetch-options] for the HTTP(S) request
Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request).
In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object.
<a id="class-response"></a>
### Class: Response
An HTTP(S) response. This class implements the [Body](#iface-body) interface.
The following properties are not implemented in node-fetch at this moment:
- `Response.error()`
- `Response.redirect()`
- `type`
- `trailer`
#### new Response([body[, options]])
<small>*(spec-compliant)*</small>
- `body` A `String` or [`Readable` stream][node-readable]
- `options` A [`ResponseInit`][response-init] options dictionary
Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response).
Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly.
#### response.ok
<small>*(spec-compliant)*</small>
Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.
#### response.redirected
<small>*(spec-compliant)*</small>
Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.
<a id="class-headers"></a>
### Class: Headers
This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented.
#### new Headers([init])
<small>*(spec-compliant)*</small>
- `init` Optional argument to pre-fill the `Headers` object
Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object.
```js
// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
const meta = {
'Content-Type': 'text/xml',
'Breaking-Bad': '<3'
};
const headers = new Headers(meta);
// The above is equivalent to
const meta = [
[ 'Content-Type', 'text/xml' ],
[ 'Breaking-Bad', '<3' ]
];
const headers = new Headers(meta);
// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map();
meta.set('Content-Type', 'text/xml');
meta.set('Breaking-Bad', '<3');
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);
```
<a id="iface-body"></a>
### Interface: Body
`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes.
The following methods are not yet implemented in node-fetch at this moment:
- `formData()`
#### body.body
<small>*(deviation from spec)*</small>
* Node.js [`Readable` stream][node-readable]
Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable].
#### body.bodyUsed
<small>*(spec-compliant)*</small>
* `Boolean`
A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.
#### body.arrayBuffer()
#### body.blob()
#### body.json()
#### body.text()
<small>*(spec-compliant)*</small>
* Returns: <code>Promise</code>
Consume the body and return a promise that will resolve to one of these formats.
#### body.buffer()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise&lt;Buffer&gt;</code>
Consume the body and return a promise that will resolve to a Buffer.
#### body.textConverted()
<small>*(node-fetch extension)*</small>
* Returns: <code>Promise&lt;String&gt;</code>
Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible.
(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.)
<a id="class-fetcherror"></a>
### Class: FetchError
<small>*(node-fetch extension)*</small>
An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info.
<a id="class-aborterror"></a>
### Class: AbortError
<small>*(node-fetch extension)*</small>
An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info.
## Acknowledgement
Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference.
`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr).
## License
MIT
[npm-image]: https://flat.badgen.net/npm/v/node-fetch
[npm-url]: https://www.npmjs.com/package/node-fetch
[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch
[travis-url]: https://travis-ci.org/bitinn/node-fetch
[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master
[codecov-url]: https://codecov.io/gh/bitinn/node-fetch
[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch
[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch
[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square
[discord-url]: https://discord.gg/Zxbndcm
[opencollective-image]: https://opencollective.com/node-fetch/backers.svg
[opencollective-url]: https://opencollective.com/node-fetch
[whatwg-fetch]: https://fetch.spec.whatwg.org/
[response-init]: https://fetch.spec.whatwg.org/#responseinit
[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams
[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers
[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md
[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md
[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md

View File

@@ -0,0 +1,25 @@
"use strict";
// ref: https://github.com/tc39/proposal-global
var getGlobal = function () {
// the only reliable means to get the global object is
// `Function('return this')()`
// However, this causes CSP violations in Chrome apps.
if (typeof self !== 'undefined') { return self; }
if (typeof window !== 'undefined') { return window; }
if (typeof global !== 'undefined') { return global; }
throw new Error('unable to locate global object');
}
var globalObject = getGlobal();
module.exports = exports = globalObject.fetch;
// Needed for TypeScript and Webpack.
if (globalObject.fetch) {
exports.default = globalObject.fetch.bind(globalObject);
}
exports.Headers = globalObject.Headers;
exports.Request = globalObject.Request;
exports.Response = globalObject.Response;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,89 @@
{
"name": "node-fetch",
"version": "2.7.0",
"description": "A light-weight module that brings window.fetch to node.js",
"main": "lib/index.js",
"browser": "./browser.js",
"module": "lib/index.mjs",
"files": [
"lib/index.js",
"lib/index.mjs",
"lib/index.es.js",
"browser.js"
],
"engines": {
"node": "4.x || >=6.0.0"
},
"scripts": {
"build": "cross-env BABEL_ENV=rollup rollup -c",
"prepare": "npm run build",
"test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js",
"report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js",
"coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json"
},
"repository": {
"type": "git",
"url": "https://github.com/bitinn/node-fetch.git"
},
"keywords": [
"fetch",
"http",
"promise"
],
"author": "David Frank",
"license": "MIT",
"bugs": {
"url": "https://github.com/bitinn/node-fetch/issues"
},
"homepage": "https://github.com/bitinn/node-fetch",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
},
"devDependencies": {
"@ungap/url-search-params": "^0.1.2",
"abort-controller": "^1.1.0",
"abortcontroller-polyfill": "^1.3.0",
"babel-core": "^6.26.3",
"babel-plugin-istanbul": "^4.1.6",
"babel-plugin-transform-async-generator-functions": "^6.24.1",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "1.4.0",
"babel-register": "^6.16.3",
"chai": "^3.5.0",
"chai-as-promised": "^7.1.1",
"chai-iterator": "^1.1.1",
"chai-string": "~1.3.0",
"codecov": "3.3.0",
"cross-env": "^5.2.0",
"form-data": "^2.3.3",
"is-builtin-module": "^1.0.0",
"mocha": "^5.0.0",
"nyc": "11.9.0",
"parted": "^0.1.1",
"promise": "^8.0.3",
"resumer": "0.0.0",
"rollup": "^0.63.4",
"rollup-plugin-babel": "^3.0.7",
"string-to-arraybuffer": "^1.0.2",
"teeny-request": "3.7.0"
},
"release": {
"branches": [
"+([0-9]).x",
"main",
"next",
{
"name": "beta",
"prerelease": true
}
]
}
}

67
node_modules/telegraf/package.json generated vendored Normal file
View File

@@ -0,0 +1,67 @@
{
"name": "telegraf",
"version": "3.40.0",
"description": "Modern Telegram Bot Framework",
"license": "MIT",
"author": "Vitaly Domnikov <oss@vitaly.codes>",
"homepage": "https://github.com/telegraf/telegraf#readme",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/telegraf/telegraf.git"
},
"bugs": {
"url": "https://github.com/telegraf/telegraf/issues"
},
"main": "telegraf.js",
"files": [
"bin/*",
"core/**/*.js",
"scenes/**/*.js",
"typings/*.d.ts",
"*.js"
],
"bin": {
"telegraf": "bin/telegraf"
},
"scripts": {
"lint": "eslint .",
"test": "ava test/*",
"precommit": "npm run lint && npm run typecheck && npm test",
"typecheck": "tsc"
},
"type": "commonjs",
"engines": {
"node": ">=10"
},
"types": "./typings/index.d.ts",
"dependencies": {
"debug": "^4.0.1",
"minimist": "^1.2.0",
"module-alias": "^2.2.2",
"node-fetch": "^2.2.0",
"sandwich-stream": "^2.0.1",
"typegram": "^3.10.0"
},
"devDependencies": {
"@types/node": "^13.1.0",
"ava": "^3.0.0",
"eslint": "^6.2.2",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-ava": "^10.0.0",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-node": "^11.0.0",
"eslint-plugin-promise": "^4.0.0",
"eslint-plugin-standard": "^4.0.0",
"husky": "^4.2.0",
"prettier": "^2.0.5",
"typescript": "^3.0.1"
},
"keywords": [
"telegraf",
"telegram",
"telegram bot api",
"bot",
"botapi",
"bot framework"
]
}

64
node_modules/telegraf/readme.md generated vendored Normal file
View File

@@ -0,0 +1,64 @@
![Telegraf](docs/media/header.png)
[![Bot API Version](https://img.shields.io/badge/Bot%20API-v6.0-f36caf.svg?style=flat-square)](https://core.telegram.org/bots/api)
[![NPM Version](https://img.shields.io/npm/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf)
[![node](https://img.shields.io/node/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/telegraf)
[![Build Status](https://img.shields.io/travis/telegraf/telegraf.svg?branch=master&style=flat-square)](https://travis-ci.org/telegraf/telegraf)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square)](http://standardjs.com/)
[![Community Chat](https://img.shields.io/badge/Community-Chat-blueChat?style=flat-square&logo=telegram)](https://t.me/TelegrafJSChat)
## Introduction
Bots are special [Telegram](https://telegram.org) accounts designed to handle messages automatically. Users can interact with bots by sending them command messages in private or group chats. These accounts serve as an interface for code running somewhere on your server.
### Features
- Full [Telegram Bot API 6.0](https://core.telegram.org/bots/api) support
- [Telegram Payment Platform](https://telegram.org/blog/payments)
- [HTML5 Games](https://core.telegram.org/bots/api#games)
- [Inline mode](https://core.telegram.org/bots/api#inline-mode)
- Incredibly fast
- [Vercel](https://vercel.com)/[Firebase](https://firebase.google.com/products/functions/)/[Glitch](https://dashing-light.glitch.me)/[Heroku](https://devcenter.heroku.com/articles/getting-started-with-nodejs#introduction)/[AWS **λ**](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html)/Whatever ready
- `http/https/fastify/Connect.js/express.js` compatible webhooks
- Easy to extend
- `TypeScript` typings
### Installation
```bash
npm install telegraf
```
or using `yarn`:
```bash
yarn add telegraf
```
### Documentation
[Telegraf developer docs](http://telegraf.js.org)
### Examples
```js
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply('Welcome!'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply('👍'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
bot.launch()
```
```js
const { Telegraf } = require('telegraf')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.command('oldschool', (ctx) => ctx.reply('Hello'))
bot.command('modern', ({ reply }) => reply('Yo'))
bot.command('hipster', Telegraf.reply('λ'))
bot.launch()
```
There's some cool [examples too](docs/examples/).

43
node_modules/telegraf/router.js generated vendored Normal file
View File

@@ -0,0 +1,43 @@
const { compose, lazy, passThru } = require('./composer')
class Router {
constructor (routeFn, handlers = new Map()) {
if (!routeFn) {
throw new Error('Missing routing function')
}
this.routeFn = routeFn
this.handlers = handlers
this.otherwiseHandler = passThru()
}
on (route, ...fns) {
if (fns.length === 0) {
throw new TypeError('At least one handler must be provided')
}
this.handlers.set(route, compose(fns))
return this
}
otherwise (...fns) {
if (fns.length === 0) {
throw new TypeError('At least one otherwise handler must be provided')
}
this.otherwiseHandler = compose(fns)
return this
}
middleware () {
return lazy((ctx) => {
return Promise.resolve(this.routeFn(ctx)).then((result) => {
if (!result || !result.route || !this.handlers.has(result.route)) {
return this.otherwiseHandler
}
Object.assign(ctx, result.context)
Object.assign(ctx.state, result.state)
return this.handlers.get(result.route)
})
})
}
}
module.exports = Router

46
node_modules/telegraf/scenes/base.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
const Composer = require('../composer')
const { compose } = Composer
class BaseScene extends Composer {
constructor (id, options) {
const opts = {
handlers: [],
enterHandlers: [],
leaveHandlers: [],
...options
}
super(...opts.handlers)
this.id = id
this.options = opts
this.enterHandler = compose(opts.enterHandlers)
this.leaveHandler = compose(opts.leaveHandlers)
}
set ttl (value) {
this.options.ttl = value
}
get ttl () {
return this.options.ttl
}
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
}
}
module.exports = BaseScene

79
node_modules/telegraf/scenes/context.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
const debug = require('debug')('telegraf:scenes:context')
const { safePassThru } = require('../composer')
const noop = () => Promise.resolve()
const now = () => Math.floor(Date.now() / 1000)
class SceneContext {
constructor (ctx, scenes, options) {
this.ctx = ctx
this.scenes = scenes
this.options = options
}
get session () {
const sessionName = this.options.sessionName
let session = this.ctx[sessionName].__scenes || {}
if (session.expires < now()) {
session = {}
}
this.ctx[sessionName].__scenes = session
return session
}
get state () {
this.session.state = this.session.state || {}
return this.session.state
}
set state (value) {
this.session.state = { ...value }
}
get current () {
const sceneId = this.session.current || this.options.default
return (sceneId && this.scenes.has(sceneId)) ? this.scenes.get(sceneId) : null
}
reset () {
const sessionName = this.options.sessionName
delete this.ctx[sessionName].__scenes
}
enter (sceneId, initialState, silent) {
if (!sceneId || !this.scenes.has(sceneId)) {
throw new Error(`Can't find scene: ${sceneId}`)
}
const leave = silent ? noop() : this.leave()
return leave.then(() => {
debug('Enter scene', sceneId, initialState, silent)
this.session.current = sceneId
this.state = initialState
const ttl = this.current.ttl || this.options.ttl
if (ttl) {
this.session.expires = now() + ttl
}
if (silent) {
return Promise.resolve()
}
const handler = typeof this.current.enterMiddleware === 'function'
? this.current.enterMiddleware()
: this.current.middleware()
return handler(this.ctx, noop)
})
}
reenter () {
return this.enter(this.session.current, this.state)
}
leave () {
debug('Leave scene')
const handler = this.current && this.current.leaveMiddleware
? this.current.leaveMiddleware()
: safePassThru()
return handler(this.ctx, noop).then(() => this.reset())
}
}
module.exports = SceneContext

28
node_modules/telegraf/scenes/wizard/context.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
class WizardContext {
constructor (ctx, steps) {
this.ctx = ctx
this.steps = steps
this.state = ctx.scene.state
this.cursor = ctx.scene.session.cursor || 0
}
get step () {
return this.cursor >= 0 && this.steps[this.cursor]
}
selectStep (index) {
this.cursor = index
this.ctx.scene.session.cursor = index
return this
}
next () {
return this.selectStep(this.cursor + 1)
}
back () {
return this.selectStep(this.cursor - 1)
}
}
module.exports = WizardContext

51
node_modules/telegraf/scenes/wizard/index.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
const Composer = require('../../composer')
const WizardContext = require('./context')
const { compose, unwrap } = Composer
class WizardScene extends Composer {
constructor (id, options, ...steps) {
super()
this.id = id
this.options = typeof options === 'function'
? { steps: [options, ...steps], leaveHandlers: [] }
: { steps: steps, leaveHandlers: [], ...options }
this.leaveHandler = compose(this.options.leaveHandlers)
}
set ttl (value) {
this.options.ttl = value
}
get ttl () {
return this.options.ttl
}
leave (...fns) {
this.leaveHandler = compose([this.leaveHandler, ...fns])
return this
}
leaveMiddleware () {
return this.leaveHandler
}
middleware () {
return compose([
(ctx, next) => {
const wizard = new WizardContext(ctx, this.options.steps)
ctx.wizard = wizard
return next()
},
super.middleware(),
(ctx, next) => {
if (!ctx.wizard.step) {
ctx.wizard.selectStep(0)
return ctx.scene.leave()
}
return unwrap(ctx.wizard.step)(ctx, next)
}
])
}
}
module.exports = WizardScene

33
node_modules/telegraf/session.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
module.exports = function (opts) {
const options = {
property: 'session',
store: new Map(),
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`,
...opts
}
const ttlMs = options.ttl && options.ttl * 1000
return (ctx, next) => {
const key = options.getSessionKey(ctx)
if (!key) {
return next(ctx)
}
const now = Date.now()
return Promise.resolve(options.store.get(key))
.then((state) => state || { session: {} })
.then(({ session, expires }) => {
if (expires && expires < now) {
session = {}
}
Object.defineProperty(ctx, options.property, {
get: function () { return session },
set: function (newValue) { session = { ...newValue } }
})
return next(ctx).then(() => options.store.set(key, {
session,
expires: ttlMs ? now + ttlMs : null
}))
})
}
}

51
node_modules/telegraf/stage.js generated vendored Normal file
View File

@@ -0,0 +1,51 @@
const SceneContext = require('./scenes/context')
const Composer = require('./composer')
const { compose, optional, lazy, safePassThru } = Composer
class Stage extends Composer {
constructor (scenes = [], options) {
super()
this.options = {
sessionName: 'session',
...options
}
this.scenes = new Map()
scenes.forEach((scene) => this.register(scene))
}
register (...scenes) {
scenes.forEach((scene) => {
if (!scene || !scene.id || typeof scene.middleware !== 'function') {
throw new Error('telegraf: Unsupported scene')
}
this.scenes.set(scene.id, scene)
})
return this
}
middleware () {
const handler = compose([
(ctx, next) => {
ctx.scene = new SceneContext(ctx, this.scenes, this.options)
return next()
},
super.middleware(),
lazy((ctx) => ctx.scene.current || safePassThru())
])
return optional((ctx) => ctx[this.options.sessionName], 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)
}
}
module.exports = Stage

221
node_modules/telegraf/telegraf.js generated vendored Normal file
View File

@@ -0,0 +1,221 @@
const debug = require('debug')('telegraf:core')
const Telegram = require('./telegram')
const Extra = require('./extra')
const Composer = require('./composer')
const Markup = require('./markup')
const session = require('./session')
const Router = require('./router')
const Stage = require('./stage')
const BaseScene = require('./scenes/base')
const Context = require('./context')
const generateCallback = require('./core/network/webhook')
const crypto = require('crypto')
const { URL } = require('url')
const DEFAULT_OPTIONS = {
retryAfter: 1,
handlerTimeout: 0,
contextType: Context
}
const noop = () => { }
class Telegraf extends Composer {
constructor (token, options) {
super()
this.options = {
...DEFAULT_OPTIONS,
...options
}
this.token = token
this.handleError = (err) => {
console.error()
console.error((err.stack || err.toString()).replace(/^/gm, ' '))
console.error()
throw err
}
this.context = {}
this.polling = {
offset: 0,
started: false
}
}
set token (token) {
this.telegram = new Telegram(token, this.telegram
? this.telegram.options
: this.options.telegram
)
}
get token () {
return this.telegram.token
}
set webhookReply (webhookReply) {
this.telegram.webhookReply = webhookReply
}
get webhookReply () {
return this.telegram.webhookReply
}/* eslint brace-style: 0 */
catch (handler) {
this.handleError = handler
return this
}
webhookCallback (path = '/') {
return generateCallback(path, (update, res) => this.handleUpdate(update, res), debug)
}
startPolling (timeout = 30, limit = 100, allowedUpdates, stopCallback = noop) {
this.polling.timeout = timeout
this.polling.limit = limit
this.polling.allowedUpdates = allowedUpdates
? Array.isArray(allowedUpdates) ? allowedUpdates : [`${allowedUpdates}`]
: null
this.polling.stopCallback = stopCallback
if (!this.polling.started) {
this.polling.started = true
this.fetchUpdates()
}
return this
}
startWebhook (hookPath, tlsOptions, port, host, cb) {
const webhookCb = this.webhookCallback(hookPath)
const callback = cb && typeof cb === 'function'
? (req, res) => webhookCb(req, res, () => cb(req, res))
: webhookCb
this.webhookServer = tlsOptions
? require('https').createServer(tlsOptions, callback)
: require('http').createServer(callback)
this.webhookServer.listen(port, host, () => {
debug('Webhook listening on port: %s', port)
})
return this
}
launch (config = {}) {
debug('Connecting to Telegram')
return this.telegram.getMe()
.then((botInfo) => {
debug(`Launching @${botInfo.username}`)
this.options.username = botInfo.username
this.context.botInfo = botInfo
if (!config.webhook) {
const { timeout, limit, allowedUpdates, stopCallback } = config.polling || {}
return this.telegram.deleteWebhook()
.then(() => this.startPolling(timeout, limit, allowedUpdates, stopCallback))
.then(() => debug('Bot started with long-polling'))
}
if (typeof config.webhook.domain !== 'string' && typeof config.webhook.hookPath !== 'string') {
throw new Error('Webhook domain or webhook path is required')
}
let domain = config.webhook.domain || ''
if (domain.startsWith('https://') || domain.startsWith('http://')) {
domain = new URL(domain).host
}
const hookPath = config.webhook.hookPath || `/telegraf/${crypto.randomBytes(32).toString('hex')}`
const { port, host, tlsOptions, cb } = config.webhook
this.startWebhook(hookPath, tlsOptions, port, host, cb)
if (!domain) {
debug('Bot started with webhook')
return
}
return this.telegram
.setWebhook(`https://${domain}${hookPath}`)
.then(() => debug(`Bot started with webhook @ https://${domain}`))
})
.catch((err) => {
console.error('Launch failed')
console.error(err.stack || err.toString())
})
}
stop (cb = noop) {
debug('Stopping bot...')
return new Promise((resolve) => {
const done = () => resolve() & cb()
if (this.webhookServer) {
return this.webhookServer.close(done)
} else if (!this.polling.started) {
return done()
}
this.polling.stopCallback = done
this.polling.started = false
})
}
handleUpdates (updates) {
if (!Array.isArray(updates)) {
return Promise.reject(new Error('Updates must be an array'))
}
const processAll = Promise.all(updates.map((update) => this.handleUpdate(update)))
if (this.options.handlerTimeout === 0) {
return processAll
}
return Promise.race([
processAll,
new Promise((resolve) => setTimeout(resolve, this.options.handlerTimeout))
])
}
handleUpdate (update, webhookResponse) {
debug('Processing update', update.update_id)
const tg = new Telegram(this.token, this.telegram.options, webhookResponse)
const TelegrafContext = this.options.contextType
const ctx = new TelegrafContext(update, tg, this.options)
Object.assign(ctx, this.context)
return this.middleware()(ctx).catch((err) => this.handleError(err, ctx))
}
fetchUpdates () {
if (!this.polling.started) {
this.polling.stopCallback && this.polling.stopCallback()
return
}
const { timeout, limit, offset, allowedUpdates } = this.polling
this.telegram.getUpdates(timeout, limit, offset, allowedUpdates)
.catch((err) => {
if (err.code === 401 || err.code === 409) {
throw err
}
const wait = (err.parameters && err.parameters.retry_after) || this.options.retryAfter
console.error(`Failed to fetch updates. Waiting: ${wait}s`, err.message)
return new Promise((resolve) => setTimeout(resolve, wait * 1000, []))
})
.then((updates) => this.polling.started
? this.handleUpdates(updates).then(() => updates)
: []
)
.catch((err) => {
console.error('Failed to process updates.', err)
this.polling.started = false
this.polling.offset = 0
this.polling.stopCallback && this.polling.stopCallback()
return []
})
.then((updates) => {
if (updates.length > 0) {
this.polling.offset = updates[updates.length - 1].update_id + 1
}
this.fetchUpdates()
})
}
}
module.exports = Object.assign(Telegraf, {
Context,
Composer,
default: Telegraf,
Extra,
Markup,
Router,
Telegraf,
Telegram,
Stage,
BaseScene,
session
})

533
node_modules/telegraf/telegram.js generated vendored Normal file
View File

@@ -0,0 +1,533 @@
const replicators = require('./core/replicators')
const ApiClient = require('./core/network/client')
class Telegram extends ApiClient {
getMe () {
return this.callApi('getMe')
}
getFile (fileId) {
return this.callApi('getFile', { file_id: fileId })
}
getFileLink (fileId) {
return Promise.resolve(fileId)
.then((fileId) => {
if (fileId && fileId.file_path) {
return fileId
}
const id = fileId && fileId.file_id ? fileId.file_id : fileId
return this.getFile(id)
})
.then((file) => `${this.options.apiRoot}/file/bot${this.token}/${file.file_path}`)
}
getUpdates (timeout, limit, offset, allowedUpdates) {
const url = `getUpdates?offset=${offset}&limit=${limit}&timeout=${timeout}`
return this.callApi(url, {
allowed_updates: allowedUpdates
})
}
getWebhookInfo () {
return this.callApi('getWebhookInfo')
}
getGameHighScores (userId, inlineMessageId, chatId, messageId) {
return this.callApi('getGameHighScores', {
user_id: userId,
inline_message_id: inlineMessageId,
chat_id: chatId,
message_id: messageId
})
}
setGameScore (userId, score, inlineMessageId, chatId, messageId, editMessage = true, force) {
return this.callApi('setGameScore', {
force,
score,
user_id: userId,
inline_message_id: inlineMessageId,
chat_id: chatId,
message_id: messageId,
disable_edit_message: !editMessage
})
}
setWebhook (url, extra) {
return this.callApi('setWebhook', { url, ...extra })
}
deleteWebhook (extra) {
return this.callApi('deleteWebhook', extra)
}
sendMessage (chatId, text, extra) {
return this.callApi('sendMessage', { chat_id: chatId, text, ...extra })
}
forwardMessage (chatId, fromChatId, messageId, extra) {
return this.callApi('forwardMessage', {
chat_id: chatId,
from_chat_id: fromChatId,
message_id: messageId,
...extra
})
}
sendChatAction (chatId, action) {
return this.callApi('sendChatAction', { chat_id: chatId, action })
}
getUserProfilePhotos (userId, offset, limit) {
return this.callApi('getUserProfilePhotos', { user_id: userId, offset, limit })
}
sendLocation (chatId, latitude, longitude, extra) {
return this.callApi('sendLocation', { chat_id: chatId, latitude, longitude, ...extra })
}
sendVenue (chatId, latitude, longitude, title, address, extra) {
return this.callApi('sendVenue', {
latitude,
longitude,
title,
address,
chat_id: chatId,
...extra
})
}
sendInvoice (chatId, invoice, extra) {
return this.callApi('sendInvoice', { chat_id: chatId, ...invoice, ...extra })
}
sendContact (chatId, phoneNumber, firstName, extra) {
return this.callApi('sendContact', { chat_id: chatId, phone_number: phoneNumber, first_name: firstName, ...extra })
}
sendPhoto (chatId, photo, extra) {
return this.callApi('sendPhoto', { chat_id: chatId, photo, ...extra })
}
sendDice (chatId, extra) {
return this.callApi('sendDice', { chat_id: chatId, ...extra })
}
sendDocument (chatId, document, extra) {
return this.callApi('sendDocument', { chat_id: chatId, document, ...extra })
}
sendAudio (chatId, audio, extra) {
return this.callApi('sendAudio', { chat_id: chatId, audio, ...extra })
}
sendSticker (chatId, sticker, extra) {
return this.callApi('sendSticker', { chat_id: chatId, sticker, ...extra })
}
sendVideo (chatId, video, extra) {
return this.callApi('sendVideo', { chat_id: chatId, video, ...extra })
}
sendAnimation (chatId, animation, extra) {
return this.callApi('sendAnimation', { chat_id: chatId, animation, ...extra })
}
sendVideoNote (chatId, videoNote, extra) {
return this.callApi('sendVideoNote', { chat_id: chatId, video_note: videoNote, ...extra })
}
sendVoice (chatId, voice, extra) {
return this.callApi('sendVoice', { chat_id: chatId, voice, ...extra })
}
sendGame (chatId, gameName, extra) {
return this.callApi('sendGame', { chat_id: chatId, game_short_name: gameName, ...extra })
}
sendMediaGroup (chatId, media, extra) {
return this.callApi('sendMediaGroup', { chat_id: chatId, media, ...extra })
}
sendPoll (chatId, question, options, extra) {
return this.callApi('sendPoll', { chat_id: chatId, type: 'regular', question, options, ...extra })
}
sendQuiz (chatId, question, options, extra) {
return this.callApi('sendPoll', { chat_id: chatId, type: 'quiz', question, options, ...extra })
}
stopPoll (chatId, messageId, extra) {
return this.callApi('stopPoll', { chat_id: chatId, message_id: messageId, ...extra })
}
getChat (chatId) {
return this.callApi('getChat', { chat_id: chatId })
}
getChatAdministrators (chatId) {
return this.callApi('getChatAdministrators', { chat_id: chatId })
}
getChatMember (chatId, userId) {
return this.callApi('getChatMember', { chat_id: chatId, user_id: userId })
}
getChatMembersCount (chatId) {
return this.callApi('getChatMemberCount', { chat_id: chatId })
}
getChatMemberCount (chatId) {
return this.callApi('getChatMemberCount', { chat_id: chatId })
}
answerInlineQuery (inlineQueryId, results, extra) {
return this.callApi('answerInlineQuery', { inline_query_id: inlineQueryId, results, ...extra })
}
setChatPermissions (chatId, permissions) {
return this.callApi('setChatPermissions', { chat_id: chatId, permissions })
}
banChatMember (chatId, userId, extra) {
return this.callApi('banChatMember', { chat_id: chatId, user_id: userId, ...extra })
}
kickChatMember (chatId, userId, untilDate) {
return this.callApi('banChatMember', { chat_id: chatId, user_id: userId, until_date: untilDate })
}
promoteChatMember (chatId, userId, extra) {
return this.callApi('promoteChatMember', { chat_id: chatId, user_id: userId, ...extra })
}
restrictChatMember (chatId, userId, extra) {
return this.callApi('restrictChatMember', { chat_id: chatId, user_id: userId, ...extra })
}
setChatAdministratorCustomTitle (chatId, userId, title) {
return this.callApi('setChatAdministratorCustomTitle', { chat_id: chatId, user_id: userId, custom_title: title })
}
banChatSenderChat (chatId, senderChatId) {
return this.callApi('banChatSenderChat', { chat_id: chatId, sender_chat_id: senderChatId })
}
unbanChatSenderChat (chatId, senderChatId) {
return this.callApi('unbanChatSenderChat', { chat_id: chatId, sender_chat_id: senderChatId })
}
exportChatInviteLink (chatId) {
return this.callApi('exportChatInviteLink', { chat_id: chatId })
}
setChatPhoto (chatId, photo) {
return this.callApi('setChatPhoto', { chat_id: chatId, photo })
}
deleteChatPhoto (chatId) {
return this.callApi('deleteChatPhoto', { chat_id: chatId })
}
setChatTitle (chatId, title) {
return this.callApi('setChatTitle', { chat_id: chatId, title })
}
setChatDescription (chatId, description) {
return this.callApi('setChatDescription', { chat_id: chatId, description })
}
pinChatMessage (chatId, messageId, extra) {
return this.callApi('pinChatMessage', { chat_id: chatId, message_id: messageId, ...extra })
}
unpinChatMessage (chatId, extra) {
return this.callApi('unpinChatMessage', { chat_id: chatId, ...extra })
}
unpinAllChatMessages (chatId) {
return this.callApi('unpinAllChatMessages', { chat_id: chatId })
}
leaveChat (chatId) {
return this.callApi('leaveChat', { chat_id: chatId })
}
unbanChatMember (chatId, userId, extra) {
return this.callApi('unbanChatMember', { chat_id: chatId, user_id: userId, ...extra })
}
answerCbQuery (callbackQueryId, text, showAlert, extra) {
return this.callApi('answerCallbackQuery', {
text,
show_alert: showAlert,
callback_query_id: callbackQueryId,
...extra
})
}
answerGameQuery (callbackQueryId, url) {
return this.callApi('answerCallbackQuery', {
url,
callback_query_id: callbackQueryId
})
}
answerShippingQuery (shippingQueryId, ok, shippingOptions, errorMessage) {
return this.callApi('answerShippingQuery', {
ok,
shipping_query_id: shippingQueryId,
shipping_options: shippingOptions,
error_message: errorMessage
})
}
answerPreCheckoutQuery (preCheckoutQueryId, ok, errorMessage) {
return this.callApi('answerPreCheckoutQuery', {
ok,
pre_checkout_query_id: preCheckoutQueryId,
error_message: errorMessage
})
}
editMessageText (chatId, messageId, inlineMessageId, text, extra) {
return this.callApi('editMessageText', {
text,
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
...extra
})
}
editMessageCaption (chatId, messageId, inlineMessageId, caption, extra = {}) {
return this.callApi('editMessageCaption', {
caption,
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
...extra.parse_mode && { parse_mode: extra.parse_mode },
...extra.caption_entities && { caption_entities: extra.caption_entities },
reply_markup: extra.parse_mode || extra.reply_markup ? extra.reply_markup : extra
})
}
editMessageMedia (chatId, messageId, inlineMessageId, media, extra = {}) {
return this.callApi('editMessageMedia', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
media: {
...media,
parse_mode: extra.parse_mode,
caption: extra.caption,
caption_entities: extra.caption_entities
},
reply_markup: extra.reply_markup ? extra.reply_markup : extra
})
}
editMessageReplyMarkup (chatId, messageId, inlineMessageId, markup) {
return this.callApi('editMessageReplyMarkup', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
reply_markup: markup
})
}
editMessageLiveLocation (chatId, messageId, inlineMessageId, latitude, longitude, extra) {
return this.callApi('editMessageLiveLocation', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
latitude,
longitude,
...extra
})
}
stopMessageLiveLocation (chatId, messageId, inlineMessageId, markup) {
return this.callApi('stopMessageLiveLocation', {
chat_id: chatId,
message_id: messageId,
inline_message_id: inlineMessageId,
reply_markup: markup
})
}
deleteMessage (chatId, messageId) {
return this.callApi('deleteMessage', {
chat_id: chatId,
message_id: messageId
})
}
setChatStickerSet (chatId, setName) {
return this.callApi('setChatStickerSet', {
chat_id: chatId,
sticker_set_name: setName
})
}
deleteChatStickerSet (chatId) {
return this.callApi('deleteChatStickerSet', { chat_id: chatId })
}
getStickerSet (name) {
return this.callApi('getStickerSet', { name })
}
uploadStickerFile (ownerId, stickerFile) {
return this.callApi('uploadStickerFile', {
user_id: ownerId,
png_sticker: stickerFile
})
}
createNewStickerSet (ownerId, name, title, stickerData) {
return this.callApi('createNewStickerSet', {
name,
title,
user_id: ownerId,
...stickerData
})
}
addStickerToSet (ownerId, name, stickerData, isMasks) {
return this.callApi('addStickerToSet', {
name,
user_id: ownerId,
is_masks: isMasks,
...stickerData
})
}
setStickerPositionInSet (sticker, position) {
return this.callApi('setStickerPositionInSet', {
sticker,
position
})
}
setStickerSetThumb (name, userId, thumb) {
return this.callApi('setStickerSetThumb', { name, user_id: userId, thumb })
}
deleteStickerFromSet (sticker) {
return this.callApi('deleteStickerFromSet', { sticker })
}
getMyCommands (extra) {
return this.callApi('getMyCommands', extra)
}
setMyCommands (commands, extra) {
return this.callApi('setMyCommands', { commands, ...extra })
}
deleteMyCommands (extra) {
return this.callApi('deleteMyCommands', extra)
}
setPassportDataErrors (userId, errors) {
return this.callApi('setPassportDataErrors', {
user_id: userId,
errors: errors
})
}
sendCopy (chatId, message, extra) {
if (!message) {
throw new Error('Message is required')
}
if (message.chat && message.chat.id && message.message_id) {
return this.copyMessage(chatId, message.chat.id, message.message_id, extra)
}
const type = Object.keys(replicators.copyMethods).find((type) => message[type])
if (!type) {
throw new Error('Unsupported message type')
}
const opts = {
chat_id: chatId,
...replicators[type](message),
...extra
}
return this.callApi(replicators.copyMethods[type], opts)
}
copyMessage (chatId, fromChatId, messageId, extra) {
return this.callApi('copyMessage', {
chat_id: chatId,
from_chat_id: fromChatId,
message_id: messageId,
...extra
})
}
createChatInviteLink (chatId, name, extra) {
return this.callApi('createChatInviteLink', {
chat_id: chatId,
name: name,
...extra
})
}
editChatInviteLink (chatId, inviteLink, extra) {
return this.callApi('editChatInviteLink', {
chat_id: chatId,
invite_link: inviteLink,
...extra
})
}
revokeChatInviteLink (chatId, inviteLink) {
return this.callApi('revokeChatInviteLink', {
chat_id: chatId,
invite_link: inviteLink
})
}
approveChatJoinRequest (chatId, userId) {
return this.callApi('approveChatJoinRequest', {
chat_id: chatId,
user_id: userId
})
}
declineChatJoinRequest (chatId, userId) {
return this.callApi('declineChatJoinRequest', {
chat_id: chatId,
user_id: userId
})
}
setChatMenuButton (chatId, menuButton) {
return this.callApi('setChatMenuButton', {
chat_id: chatId,
menu_button: menuButton
})
}
getChatMenuButton (chatId) {
return this.callApi('getChatMenuButton', {
chat_id: chatId
})
}
setMyDefaultAdministratorRights (rights, forChannels) {
return this.callApi('setMyDefaultAdministratorRights', {
rights: rights,
for_channels: forChannels
})
}
getMyDefaultAdministratorRights (forChannels) {
return this.callApi('getMyDefaultAdministratorRights', {
for_channels: forChannels
})
}
}
module.exports = Telegram

462
node_modules/telegraf/typings/composer.d.ts generated vendored Normal file
View File

@@ -0,0 +1,462 @@
/** @format */
import * as tt from './telegram-types.d'
import { TelegrafContext } from './context'
type MaybeArray<T> = T | T[]
type MaybePromise<T> = T | Promise<T>
type NormalizedTrigger<TContext> = (value: string, ctx: TContext) => RegExpExecArray | null
type HearsTriggers<TContext> = MaybeArray<string | RegExp | NormalizedTrigger<TContext>>
type Predicate<TContext> = (ctx: TContext) => MaybePromise<boolean>
type BranchPredicate<TContext> = boolean | Predicate<TContext>
export interface MiddlewareFn<TContext extends TelegrafContext> {
/*
next's parameter is in a contravariant position, and thus, trying to type it
prevents assigning `MiddlewareFn<ContextMessageUpdate>`
to `MiddlewareFn<CustomContext>`.
Middleware passing the parameter should be a separate type instead.
*/
(ctx: TContext, next: () => Promise<void>): void | Promise<unknown>
}
export interface MiddlewareObj<TContext extends TelegrafContext> {
middleware(): MiddlewareFn<TContext>
}
export type Middleware<TContext extends TelegrafContext> =
| MiddlewareFn<TContext>
| MiddlewareObj<TContext>
export declare class Composer<TContext extends TelegrafContext>
implements MiddlewareObj<TContext> {
constructor(...middlewares: ReadonlyArray<Middleware<TContext>>)
/**
* Registers a middleware.
*/
use(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Registers middleware for provided update type.
*/
on(
updateTypes: MaybeArray<tt.UpdateType | tt.MessageSubTypes>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling text messages.
*/
hears(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling specified commands.
*/
command(
command: string | string[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling callbackQuery data with regular expressions
*/
action(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling inlineQuery data with regular expressions
*/
inlineQuery(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling callback_data actions with game query.
*/
gameQuery(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Generates drop middleware.
*/
drop<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>
): this
/**
* Generates filter middleware.
*/
filter<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>
): this
/**
* Registers middleware for handling entities
*/
entity<TContext extends TelegrafContext>(
predicate: MaybeArray<tt.MessageEntityType> | ((entity: tt.MessageEntity, entityText: string, ctx: TContext) => MaybePromise<boolean>),
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching emails.
*/
email<TContext extends TelegrafContext>(
email: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching phones.
*/
phone<TContext extends TelegrafContext>(
number: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching urls.
*/
url<TContext extends TelegrafContext>(
url: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching text links.
*/
textLink<TContext extends TelegrafContext>(
link: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching text mentions.
*/
textMention<TContext extends TelegrafContext>(
mention: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching mentions.
*/
mention<TContext extends TelegrafContext>(
mention: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching hashtags.
*/
hashtag<TContext extends TelegrafContext>(
hashtag: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling messages with matching cashtags.
*/
cashtag<TContext extends TelegrafContext>(
cashtag: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): this
/**
* Registers middleware for handling /start command.
*/
start(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Registers middleware for handling /help command.
*/
help(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Registers middleware for handling /ыуеештпы command.
*/
settings(...middlewares: ReadonlyArray<Middleware<TContext>>): this
/**
* Return the middleware created by this Composer
*/
middleware(): MiddlewareFn<TContext>
static reply(
text: string,
extra?: tt.ExtraSendMessage
): MiddlewareFn<TelegrafContext>
static catchAll<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static catch<TContext extends TelegrafContext>(
errorHandler: (error: Error, ctx: TContext) => void,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware that runs in the background.
*/
static fork<TContext extends TelegrafContext>(
middleware: Middleware<TContext>
): MiddlewareFn<TContext>
/**
* Generates tap middleware.
*/
static tap<TContext extends TelegrafContext>(
middleware: Middleware<TContext>
): MiddlewareFn<TContext>
/**
* Generates pass thru middleware.
*/
static passThru(): MiddlewareFn<TelegrafContext>
/**
* Generates safe version of pass thru middleware.
*/
static safePassThru(): MiddlewareFn<TelegrafContext>
static lazy<TContext extends TelegrafContext>(
factoryFn: (ctx: TContext) => MaybePromise<Middleware<TContext>>
): MiddlewareFn<TContext>
static log(logFn?: (s: string) => void): MiddlewareFn<TelegrafContext>
/**
* @param predicate function that returns boolean or Promise<boolean>
* @param trueMiddleware middleware to run if the predicate returns true
* @param falseMiddleware middleware to run if the predicate returns false
*/
static branch<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>,
trueMiddleware: Middleware<TContext>,
falseMiddleware: Middleware<TContext>
): MiddlewareFn<TContext>
/**
* Generates optional middleware.
* @param predicate function that returns boolean or Promise<boolean>
* @param middlewares middleware to run if the predicate returns true
*/
static optional<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates filter middleware.
*/
static filter<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>
): MiddlewareFn<TContext>
/**
* Generates drop middleware.
*/
static drop<TContext extends TelegrafContext>(
predicate: BranchPredicate<TContext>
): Middleware<TContext>
static dispatch<
C extends TelegrafContext,
Handlers extends Record<string | number | symbol, Middleware<C>>
>(
routeFn: (ctx: C) => MaybePromise<keyof Handlers>,
handlers: Handlers
): Middleware<C>
/**
* Generates middleware for handling provided update types.
*/
static mount<TContext extends TelegrafContext>(
updateType: tt.UpdateType | tt.UpdateType[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static entity<TContext extends TelegrafContext>(
predicate: MaybeArray<tt.MessageEntityType> | ((entity: tt.MessageEntity, entityText: string, ctx: TContext) => MaybePromise<boolean>),
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static entityText<TContext extends TelegrafContext>(
entityType: tt.MessageEntityType,
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching emails.
*/
static email<TContext extends TelegrafContext>(
email: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching phones.
*/
static phone<TContext extends TelegrafContext>(
number: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching urls.
*/
static url<TContext extends TelegrafContext>(
url: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching text links.
*/
static textLink<TContext extends TelegrafContext>(
link: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching text mentions.
*/
static textMention<TContext extends TelegrafContext>(
mention: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching mentions.
*/
static mention<TContext extends TelegrafContext>(
mention: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching hashtags.
*/
static hashtag<TContext extends TelegrafContext>(
hashtag: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching cashtags.
*/
static cashtag<TContext extends TelegrafContext>(
cashtag: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static match<TContext extends TelegrafContext>(
triggers: NormalizedTrigger<TContext>[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling matching text messages.
*/
static hears<TContext extends TelegrafContext>(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with matching commands.
*/
static command<TContext extends TelegrafContext>(
command: string | string[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling messages with commands.
*/
static command<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling matching callback queries.
*/
static action<TContext extends TelegrafContext>(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware for handling matching inline queries.
*/
static inlineQuery<TContext extends TelegrafContext>(
triggers: HearsTriggers<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static acl<TContext extends TelegrafContext>(
status: number | number[] | BranchPredicate<TContext>,
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static memberStatus<TContext extends TelegrafContext>(
status: tt.ChatMemberStatus | tt.ChatMemberStatus[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static admin<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static creator<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware running only in given chat types.
*/
static chatType<TContext extends TelegrafContext>(
type: tt.ChatType | tt.ChatType[],
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware running only in private chats.
*/
static privateChat<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
/**
* Generates middleware running only in groups and supergroups.
*/
static groupChat<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static gameQuery<TContext extends TelegrafContext>(
...middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
static unwrap<TContext extends TelegrafContext>(
middleware: Middleware<TContext>
): MiddlewareFn<TContext>
/**
* Compose middlewares returning a fully valid middleware comprised of all those which are passed.
*/
static compose<TContext extends TelegrafContext>(
middlewares: ReadonlyArray<Middleware<TContext>>
): MiddlewareFn<TContext>
}

855
node_modules/telegraf/typings/context.d.ts generated vendored Normal file
View File

@@ -0,0 +1,855 @@
/** @format */
import * as tt from './telegram-types'
import { Telegram } from './telegram'
export declare class TelegrafContext {
tg: Telegram
update: tt.Update
updateType: tt.UpdateType
updateSubTypes: tt.MessageSubTypes[]
botInfo?: tt.User
match?: RegExpExecArray | null
me?: string
telegram: Telegram
message?: tt.Message
editedMessage?: tt.Message
inlineQuery?: tt.InlineQuery
shippingQuery?: tt.ShippingQuery
preCheckoutQuery?: tt.PreCheckoutQuery
chosenInlineResult?: tt.ChosenInlineResult
channelPost?: tt.Message
editedChannelPost?: tt.Message
callbackQuery?: tt.CallbackQuery
poll?: tt.Poll
pollAnswer?: tt.PollAnswer
chat?: tt.Chat
from?: tt.User
inlineMessageId?: string
passportData?: tt.PassportData
state: object
webhookReply: boolean
constructor(
update: tt.Update,
telegram: Telegram,
options?: {
username?: string,
channelMode?: boolean
}
)
/**
* Use this method to add a new sticker to a set created by the bot
* @param ownerId User identifier of sticker set owner
* @param name Sticker set name
* @param stickerData Sticker object
* @param isMasks https://github.com/telegraf/telegraf/blob/87882c42f6c2496576fdb57ca622690205c3e35e/lib/telegram.js#L304
* @returns Returns True on success.
*/
addStickerToSet(
ownerId: number,
name: string,
stickerData: tt.StickerData,
isMasks: boolean
): Promise<boolean>
/**
* Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set
* @param ownerId User identifier of created sticker set owner
* @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 characters.
* @param title Sticker set title, 1-64 characters
* @param stickerData Sticker object
* @returns Returns True on success.
*/
createNewStickerSet(
ownerId: number,
name: string,
title: string,
stickerData: tt.StickerData
): Promise<boolean>
/**
* Use this method to delete a sticker from a set created by the bot.
* @param sticker File identifier of the sticker
* @returns Returns True on success
*/
deleteStickerFromSet(sticker: string): Promise<boolean>
/**
* Use this method to export an invite link to a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* @returns exported invite link as String on success.
*/
exportChatInviteLink(): Promise<string>
/**
* Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.)
* @returns a Chat object on success.
*/
getChat(): Promise<tt.Chat>
/**
* Use this method to get a list of administrators in a chat.
* @returns On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
*/
getChatAdministrators(): Promise<Array<tt.ChatMember>>
/**
* Use this method to get information about a member of a chat.
* @param userId Unique identifier of the target user
* @returns a ChatMember object on success
*/
getChatMember(userId: number): Promise<tt.ChatMember>
/**
* @deprecated in favor of `getChatMemberCount`
* @returns Number on success
*/
getChatMembersCount(): Promise<number>
/**
* Use this method to get the number of members in a chat
* @returns Number on success
*/
getChatMemberCount(): Promise<number>
/**
* Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user. Returns True on success.
* @param userId Unique identifier of the target user
* @param extra Additional params for restrict chat member
* @returns True on success
*/
restrictChatMember(
userId: number,
extra?: tt.ExtraRestrictChatMember
): Promise<boolean>
/**
* Use this method to get a sticker set
* @param setName Name of the sticker set
* @returns On success, a StickerSet object is returned.
*/
getStickerSet(setName: string): Promise<tt.StickerSet>
/**
* Use this method to set a new group sticker set for a supergroup.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method
* @param setName Name of the sticker set to be set as the group sticker set
* @returns True on success.
*/
setChatStickerSet(
setName: string
): Promise<boolean>
/**
* Use this method to delete a group sticker set from a supergroup.
* The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* Use the field can_set_sticker_set optionally returned in getChat requests to check if the bot can use this method
* @returns True on success.
*/
deleteChatStickerSet(): Promise<boolean>
/**
* Use this method for your bot to leave a group, supergroup or channel
* @returns True on success
*/
leaveChat(): Promise<boolean>
/**
* Use this method to set default chat permissions for all members.
* The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights.
* @param permissions New default chat permissions
* @returns True on success
*/
setChatPermissions(
permissions: tt.ChatPermissions
): Promise<boolean>
/**
* Use this method to pin a message in a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param messageId Identifier of a message to pin
* @param extra Pass `{ disable_notification: true }`, if it is not necessary to send a notification to all group members about the new pinned message
* @returns True on success
*/
pinChatMessage(
messageId: number,
extra?: { disable_notification?: boolean }
): Promise<boolean>
/**
* Use this method to unpin a message in a group, a supergroup, or a channel.
* @returns True on success
* @param extra Extra params
*/
unpinChatMessage(extra?: tt.ExtraUnpinMessage): Promise<boolean>
/**
* Use this method to clear the list of pinned messages in a chat
* @returns True on success
*/
unpinAllChatMessages(): Promise<boolean>
/**
* Use this method to reply on messages in the same chat.
* @param text Text of the message to be sent
* @param extra SendMessage additional params
* @returns sent Message if Success
*/
reply(text: string, extra?: tt.ExtraSendMessage): Promise<tt.Message>
/**
* Use this method to send audio files to the same chat, if you want Telegram clients to display them in the music player.
* Your audio must be in the .mp3 format.
* Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
* @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data
* @param extra Audio extra parameters
* @returns On success, the sent Message is returned.
*/
replyWithAudio(
audio: tt.InputFile,
extra?: tt.ExtraAudio
): Promise<tt.MessageAudio>
/**
* Use this method when you need to tell the user that something is happening on the bot's side.
* The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status).
* Choose one, depending on what the user is about to receive:
* - typing for text messages,
* - upload_photo for photos,
* - record_video or upload_video for videos,
* - record_audio or upload_audio for audio files,
* - upload_document for general files,
* - find_location for location data,
* - record_video_note or upload_video_note for video notes.
* @param action Type of action to broadcast.
* @returns True on success
*/
replyWithChatAction(action: tt.ChatAction): Promise<boolean>
/**
* Use this method to send general files. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
* @param document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params for send document
* @returns a Message on success
*/
replyWithDocument(
document: tt.InputFile,
extra?: tt.ExtraDocument
): Promise<tt.MessageDocument>
/**
* Use this method to send a game
* @param gameShortName Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather.
* @param extra Additional params for send game
* @returns a Message on success
*/
replyWithGame(
gameShortName: string,
extra?: tt.ExtraGame
): Promise<tt.MessageGame>
/**
* The Bot API supports basic formatting for messages
* @param html You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages.
* @param extra Additional params to send message
* @returns a Message on success
*/
replyWithHTML(html: string, extra?: tt.ExtraSendMessage): Promise<tt.Message>
/**
* Use this method to send invoices
* @param invoice Object with new invoice params
* @param extra Additional params for send invoice
* @returns a Message on success
*/
replyWithInvoice(
invoice: tt.NewInvoiceParameters,
extra?: tt.ExtraInvoice
): Promise<tt.MessageInvoice>
/**
* Use this method to send point on the map
* @param latitude Latitude of location
* @param longitude Longitude of location
* @param extra Additional params for send location
* @returns a Message on success
*/
replyWithLocation(
latitude: number,
longitude: number,
extra?: tt.ExtraLocation
): Promise<tt.MessageLocation>
/**
* Use this method to send information about a venue
* @param latitude Latitude of location
* @param longitude Longitude of location
* @param title Name of the venue
* @param address Address of the venue
* @param extra Additional params for sendVenue
* @returns a Message on success
*/
replyWithVenue(
latitude: number,
longitude: number,
title: string,
address: string,
extra?: tt.ExtraVenue
): Promise<tt.MessageVenue>
/**
* Use this method to send phone contacts
* @param phoneNumber Contact's phone number
* @param firstName Contact's first name
* @param extra Additional params for sendContact
* @returns a Message on success
*/
replyWithContact(
phoneNumber: string,
firstName: string,
extra?: tt.ExtraContact
): Promise<tt.MessageContact>
/**
* The Bot API supports basic formatting for messages
* @param markdown You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages.
* @param extra Additional params to send message
* @returns a Message on success
*/
replyWithMarkdown(
markdown: string,
extra?: tt.ExtraSendMessage
): Promise<tt.Message>
/**
* The Bot API supports basic formatting for messages
* @param markdown You can use bold and italic text, as well as inline links and pre-formatted code in your bots' messages.
* @param extra Additional params to send message
* @returns a Message on success
*/
replyWithMarkdownV2(
markdown: string,
extra?: tt.ExtraSendMessage
): Promise<tt.Message>
/**
* Use this method to send photos
* @param photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data
* @param extra Additional params to send photo
* @returns a Message on success
*/
replyWithPhoto(
photo: tt.InputFile,
extra?: tt.ExtraPhoto
): Promise<tt.MessagePhoto>
/**
* Use this method to send a group of photos or videos as an album
* @param media A JSON-serialized array describing photos and videos to be sent, must include 210 items
* @param extra Additional params to send media group
* @returns On success, an array of the sent Messages is returned
*/
replyWithMediaGroup(
media: tt.MessageMedia[],
extra?: tt.ExtraMediaGroup
): Promise<Array<tt.Message>>
/**
* Use this method to send a native poll.
* @param question Poll question, 1-255 characters
* @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each
* @param extra Additional params to send poll
* @returns On success, the sent Message is returned.
*/
replyWithPoll(
question: string,
options: string[],
extra: tt.ExtraPoll
): Promise<tt.MessagePoll>
/**
* Use this method to send a native quiz.
* @param question Poll question, 1-255 characters
* @param options A JSON-serialized list of answer options, 2-10 strings 1-100 characters each
* @param extra Additional params to send quiz
* @returns On success, the sent Message is returned.
*/
replyWithQuiz(
question: string,
options: string[],
extra: tt.ExtraQuiz
): Promise<tt.MessagePoll>
/**
* Use this method to send a native quiz.
* @param messageId Identifier of the original message with the poll
* @param extra Additional params to stop poll
* @returns On success, the stopped Poll with the final results is returned.
*/
stopPoll(messageId: number, extra: tt.ExtraStopPoll): Promise<tt.Poll>
/**
* Use this method to send .webp stickers
* @param sticker Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .webp file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params to send sticker
* @returns a Message on success
*/
replyWithSticker(
sticker: tt.InputFile,
extra?: tt.ExtraSticker
): Promise<tt.MessageSticker>
/**
* Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document)
* Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
* @param video video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data
* @param extra Additional params to send video
* @returns a Message on success
*/
replyWithVideo(
video: tt.InputFile,
extra?: tt.ExtraVideo
): Promise<tt.MessageVideo>
/**
* Use this method to send .gif animations
* @param animation Animation to send. Pass a file_id as String to send a GIF that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a GIF from the Internet, or upload a new GIF using multipart/form-data
* @param extra Additional params for sendAnimation
* @returns a Message on success
*/
replyWithAnimation(
animation: tt.InputFile,
extra?: tt.ExtraAnimation
): Promise<tt.MessageAnimation>
/**
* Use this method to send .gif animations
* @param videoNote video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. Sending video notes by a URL is currently unsupported
* @param extra Additional params for sendVideoNote
* @returns a Message on success
*/
replyWithVideoNote(
videoNote: tt.InputFileVideoNote,
extra?: tt.ExtraAnimation
): Promise<tt.MessageVideoNote>
/**
* Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
* @param voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data
* @param extra Additional params to send voice
* @returns a Message on success
*/
replyWithVoice(
voice: tt.InputFile,
extra?: tt.ExtraVoice
): Promise<tt.MessageVoice>
/**
* Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned. (Yes, we're aware of the “proper” singular of die. But it's awkward, and we decided to help it change. One dice at a time!)
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param extra Additional params to send dice
* @returns a Message on success
*/
replyWithDice(extra?: tt.ExtraDice): Promise<tt.MessageDice>
/**
* Use this method to send copy of exists message.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param extra Additional params to send modified copy of message
* @returns the MessageId of the sent message on success
*/
copyMessage(
chatId: number | string,
extra?: tt.ExtraCopyMessage
): Promise<tt.MessageId>
// ------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------ //
// ------------------------------------------------------------------------------------------ //
/**
* Use this method to send answers to an inline query.
* No more than 50 results per query are allowed.
* @returns On success, True is returned.
* @param results Array of results for the inline query
* @param extra Extra optional parameters
*/
answerInlineQuery(
results: tt.InlineQueryResult[],
extra?: tt.ExtraAnswerInlineQuery
): Promise<boolean>
answerCbQuery(
text?: string,
showAlert?: boolean,
extra?: object
): Promise<boolean>
/**
* Use this method to send answers to game query.
* @param url Notification text
*/
answerGameQuery(url: string): Promise<boolean>
/**
* If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned.
* @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible)
* @param shippingOptions Required if ok is True. A JSON-serialized array of available shipping options.
* @param errorMessage Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.
*/
answerShippingQuery(
ok: boolean,
shippingOptions: tt.ShippingOption[],
errorMessage: string
): Promise<boolean>
/**
* Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
* @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems.
* @param errorMessage Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.
*/
answerPreCheckoutQuery(ok: boolean, errorMessage?: string): Promise<boolean>
/**
* Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
* @returns On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param text New text of the message
* @param extra Extra params
*/
editMessageText(
text: string,
extra?: tt.ExtraEditMessage
): Promise<tt.Message | boolean>
/**
* Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
* On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param caption New caption of the message
* @param extra Extra params
*/
editMessageCaption(
caption?: string,
extra?: tt.ExtraEditCaption
): Promise<tt.Message | boolean>
/**
* Use this method to edit animation, audio, document, photo, or video messages.
* @returns On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
* @param media New media of message
* @param extra Extra params
*/
editMessageMedia(
media: tt.MessageMedia,
extra?: tt.ExtraEditMessageMedia
): Promise<tt.Message | boolean>
/**
* Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
* @returns On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
* @param markup Markup of inline keyboard
*/
editMessageReplyMarkup(
markup?: tt.InlineKeyboardMarkup
): Promise<tt.Message | boolean>
/**
* Use this method to edit live location messages
* @returns On success, if the edited message was sent by the bot, the edited message is returned, otherwise True is returned.
* @param latitude New latitude
* @param longitude New longitude
* @param extra Extra params
*/
editMessageLiveLocation(
latitude: number,
longitude: number,
extra?: tt.ExtraEditLocation
): Promise<tt.MessageLocation | boolean>
/**
* Use this method to stop updating a live location message before live_period expires.
* @param extra Extra params
* @returns On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned.
*/
stopMessageLiveLocation(
extra?: tt.ExtraStopLiveLocation
): Promise<tt.MessageLocation | boolean>
/**
* Use this method to ban a user in a group, a supergroup or a channel.
* @param userId Unique identifier of the target user
* @param extra Extra params
* @returns True on success
*/
banChatMember(
userId: number,
extra?: tt.ExtraBan
): Promise<boolean>
/**
* @deprecated in favor of `banChatMember`
* @param userId Unique identifier of the target user
* @param untilDate Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever
* @returns True on success
*/
kickChatMember(userId: number, untilDate?: number): Promise<boolean>
/**
* Use this method to unban a user from a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param userId Unique identifier of the target user
* @param extra Extra params
* @returns True on success
*/
unbanChatMember(userId: number, extra?: tt.ExtraUnban): Promise<boolean>
/**
* Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.
* @param userId Unique identifier of the target user
* @param extra Extra parameters for promoteChatMember
* @returns True on success
*/
promoteChatMember(
userId: number,
extra: tt.ExtraPromoteChatMember
): Promise<boolean>
/**
* Use this method to set a custom title for an administrator in a supergroup promoted by the bot
* @param userId Unique identifier of the target user
* @param title New custom title for the administrator; 0-16 characters, emoji are not allowed
* @returns True on success
*/
setChatAdministratorCustomTitle(
userId: number,
title: string
): Promise<boolean>
/**
* Use this method to ban a channel chat in a supergroup or a channel
* @param senderChatId Unique identifier of the target sender chat
* @returns True on success
*/
banChatSenderChat(
senderChatId: number,
): Promise<boolean>
/**
* Use this method to unban a previously banned channel chat in a supergroup or channel
* @param senderChatId Unique identifier of the target sender chat
* @returns True on success
*/
unbanChatSenderChat(
senderChatId: number,
): Promise<boolean>
/**
* Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param photo New chat photo
* @returns True on success.
*/
setChatPhoto(photo: tt.InputFile): Promise<boolean>
/**
* Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights.
* @returns True on success
*/
deleteChatPhoto(): Promise<boolean>
/**
* Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param title New chat title, 1-255 characters
* @returns True on success
*/
setChatTitle(title: string): Promise<boolean>
/**
* Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights
* @param description New chat description, 0-255 characters
* @returns True on success
*/
setChatDescription(description: string): Promise<boolean>
/**
* Use this method to delete a message, including service messages, with the following limitations:
* - A message can only be deleted if it was sent less than 48 hours ago.
* - Bots can delete outgoing messages in groups and supergroups.
* - Bots granted can_post_messages permissions can delete outgoing messages in channels.
* - If the bot is an administrator of a group, it can delete any message there.
* - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there.
* @returns Returns True on success.
*/
deleteMessage(messageId?: number): Promise<boolean>
/**
* Use this method to forward exists message.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param extra Pass `{ disable_notification: true }`, if it is not necessary to send a notification for forwarded message
* @returns On success, the sent Message is returned.
*/
forwardMessage(
chatId: number | string,
extra?: { disable_notification?: boolean }
): Promise<tt.Message>
/**
* Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times)
* https://core.telegram.org/bots/api#sending-files
* @param ownerId User identifier of sticker file owner
* @param stickerFile Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px.
* @returns Returns the uploaded File on success
*/
uploadStickerFile(
ownerId: number,
stickerFile: tt.InputFile
): Promise<tt.File>
/**
* Use this method to move a sticker in a set created by the bot to a specific position
* @param sticker File identifier of the sticker
* @param position New sticker position in the set, zero-based
* @returns Returns True on success.
*/
setStickerPositionInSet(sticker: string, position: number): Promise<boolean>
/**
* Use this method to set the thumbnail of a sticker set.
* Animated thumbnails can be set for animated sticker sets only
* @param name Sticker set name
* @param userId User identifier of the sticker set owner
* @param thumb New thumbnail. See [documentation](https://core.telegram.org/bots/api#setstickersetthumb)
* @returns True on success.
*/
setStickerSetThumb(
name: string,
userId: number,
thumb: tt.InputFile,
): Promise<boolean>
/**
* Informs a user that some of the Telegram Passport elements they provided contains errors.
* The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change).
*
* Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason.
* For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc.
* Supply some details in the error message to make sure the user knows how to correct the issues.
* @param errors An array describing the errors
* @returns True on success.
*/
setPassportDataErrors(
errors: tt.PassportElementError[]
): Promise<boolean>
/**
* Use this method to get the current list of the bot's commands for the given scope and user language.
* @param extra Extra parameters for getMyCommands
* @returns Array of BotCommand on success.
*/
getMyCommands(
extra?: tt.ExtraGetMyCommands
): Promise<tt.BotCommand[]>
/**
* Use this method to change the list of the bot's commands.
* @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
* @param extra Extra parameters for setMyCommands
* @returns True on success
*/
setMyCommands(
commands: tt.BotCommand[],
extra?: tt.ExtraSetMyCommands
): Promise<boolean>
/**
* Use this method to delete the list of the bot's commands for the given scope and user language.
* After deletion, higher level commands will be shown to affected users.
* @param extra Extra parameters for deleteMyCommands
* @returns True on success
*/
deleteMyCommands(
extra?: tt.ExtraDeleteMyCommands
): Promise<boolean>
/**
* Use this method to create an additional invite link for a chat.
* @param extra Extra parameters for createChatInviteLink
* @returns the new invite link as ChatInviteLink object
*/
createChatInviteLink(
extra?: tt.ExtraCreateChatIviteLink
): Promise<tt.ChatInviteLink>
/**
* Use this method to edit a non-primary invite link created by the bot.
* @param inviteLink The invite link to edit
* @param extra Extra parameters for editChatInviteLink
* @returns the edited invite link as a ChatInviteLink object
*/
editChatInviteLink(
inviteLink: string,
extra?: tt.ExtraEditChatIviteLink
): Promise<tt.ChatInviteLink>
/**
* Use this method to revoke an invite link created by the bot.
* @param inviteLink The invite link to revoke
* @returns the revoked invite link as a ChatInviteLink object
*/
revokeChatInviteLink(
inviteLink: string
): Promise<tt.ChatInviteLink>
/**
* Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param userId Unique identifier of the target user
*/
approveChatJoinRequest(
chatId: number | string,
userId: number,
): Promise<boolean>
/**
* Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
* @param chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param userId Unique identifier of the target user
*/
declineChatJoinRequest(
chatId: number | string,
userId: number,
): Promise<boolean>
/**
* Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
* @param menuButton A JSON-serialized object for the bot's new menu button. Defaults to MenuButtonDefault
*/
setChatMenuButton(
menuButton?: tt.MenuButton
): Promise<boolean>
/**
* Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
*/
getChatMenuButton(): Promise<tt.MenuButton>
/**
* Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels.
* These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
* @param rights A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared.
* @param forChannels Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.
*/
setMyDefaultAdministratorRights(
rights?: tt.ChatAdministratorRights,
forChannels?: boolean
): Promise<boolean>
/**
* Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
* @param forChannels Pass True to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.
*/
getMyDefaultAdministratorRights(
forChannels?: boolean
): Promise<tt.ChatAdministratorRights>
}

42
node_modules/telegraf/typings/extra.d.ts generated vendored Normal file
View File

@@ -0,0 +1,42 @@
/** @format */
import { Markup } from './markup';
import * as tt from './telegram-types.d'
export declare class Extra {
constructor(opts: tt.Extra)
load<T extends tt.Extra>(opts: T): Extra & T | this
inReplyTo(messageId: string | number): Extra & tt.ExtraReplyMessage | this
notifications(value?: boolean): Extra & tt.ExtraDisableNotifications | this
webPreview(value?: boolean): Extra & tt.ExtraDisableWebPagePreview | this
markup<T extends tt.KeyboardMarkupBundle>(markup: ((m: Markup<tt.KeyboardMarkupBundle>) => T) | T): Extra & tt.ExtraReply<T> | this
HTML(value?: boolean): Extra & tt.ExtraFormatting | this
markdown(value?: boolean): Extra & tt.ExtraFormatting | this
markdownV2(value?: boolean): Extra & tt.ExtraFormatting | this
caption(caption: string): Extra & tt.ExtraCaption | this
static load<T extends tt.Extra>(opts: T): Extra & T
static inReplyTo(messageId: string | number): Extra & tt.ExtraReplyMessage
static notifications(value?: boolean): Extra & tt.ExtraDisableNotifications
static webPreview(value?: boolean): Extra & tt.ExtraDisableWebPagePreview
static markup<T extends tt.KeyboardMarkupBundle>(markup: ((m: Markup<tt.KeyboardMarkupBundle>) => T) | T): Extra & tt.ExtraReply<T>
static HTML(value?: boolean): Extra & tt.ExtraFormatting
static markdown(value?: boolean): Extra & tt.ExtraFormatting
static caption(caption: string): Extra & tt.ExtraCaption
}

11
node_modules/telegraf/typings/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/** @format */
export { BaseScene, Stage } from './stage'
export { Composer, Middleware } from './composer'
export { Extra } from './extra'
export { Markup } from './markup'
export { Router } from './router'
export { session } from './session'
export { Telegraf, Telegraf as default } from './telegraf'
export { TelegrafContext as Context } from './context'
export { Telegram } from './telegram'

215
node_modules/telegraf/typings/markup.d.ts generated vendored Normal file
View File

@@ -0,0 +1,215 @@
/** @format */
import { Extra } from './extra'
import * as tt from './telegram-types.d'
export interface Button {
text: string
/**
* Keyboard builder sugar
*/
hide?: boolean
}
export interface ContactRequestButton extends Button {
request_contact: boolean
}
export interface LocationRequestButton extends Button {
request_location: boolean
}
type PollType = 'poll' | 'quiz'
export interface PollRequestButton extends Button {
request_poll: { type?: PollType }
}
export type KeyboardButton =
| Button
| ContactRequestButton
| LocationRequestButton
| PollRequestButton
| string
export interface UrlButton extends Button {
url: string
}
export interface CallbackButton extends Button {
callback_data: string
}
export interface SwitchToChatButton extends Button {
switch_inline_query: string
}
export interface SwitchToCurrentChatButton extends Button {
switch_inline_query_current_chat: string
}
export interface GameButton extends Button {
callback_game: tt.CallbackGame
}
export interface PayButton extends Button {
pay: boolean
}
export interface LoginUrl {
url: string
forward_text?: string
bot_username?: string
request_write_access?: boolean
}
export interface LoginButton extends Button {
login_url: LoginUrl
}
export type InlineKeyboardButton =
| UrlButton
| CallbackButton
| SwitchToChatButton
| SwitchToCurrentChatButton
| GameButton
| PayButton
| LoginButton
export interface KeyboardOptions<TBtn> {
columns?: number
wrap?(btn: TBtn, index: number, currentRow: TBtn[]): boolean
}
export declare class Markup<T extends tt.KeyboardMarkupBundle> {
forceReply(value?: boolean): Markup<tt.ForceReply> & tt.ForceReply
removeKeyboard(value?: boolean): Markup<tt.ReplyKeyboardRemove> & tt.ReplyKeyboardRemove
inputFieldPlaceholder<T extends tt.ReplyKeyboardMarkup | tt.ForceReply>(this: Markup<T> & T, placeholder: string): this
selective<T extends tt.ReplyMarkupBundle>(this: Markup<T> & T, value?: boolean): this
extra<T extends tt.KeyboardMarkupBundle>(this: Markup<T> & T, options?: tt.Extra): tt.ExtraReply<T> & Extra
keyboard(
buttons: KeyboardButton[] | KeyboardButton[][],
options?: KeyboardOptions<KeyboardButton>
): Markup<tt.ReplyKeyboardMarkup> & tt.ReplyKeyboardMarkup
resize<T extends tt.ReplyKeyboardMarkup>(this: Markup<T> & T, value?: boolean): this
oneTime<T extends tt.ReplyKeyboardMarkup>(this: Markup<T> & T, value?: boolean): this
inlineKeyboard(
buttons: InlineKeyboardButton[] | InlineKeyboardButton[][],
options?: KeyboardOptions<InlineKeyboardButton>
): Markup<tt.InlineKeyboardMarkup> & tt.InlineKeyboardMarkup
button(text: string, hide?: boolean): Button
contactRequestButton(text: string, hide?: boolean): ContactRequestButton
locationRequestButton(text: string, hide?: boolean): LocationRequestButton
urlButton(text: string, url: string, hide?: boolean): UrlButton
callbackButton(text: string, data: string, hide?: boolean): CallbackButton
switchToChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToChatButton
switchToCurrentChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToCurrentChatButton
gameButton(text: string, hide?: boolean): GameButton
payButton(text: string, hide?: boolean): PayButton
loginButton(
text: string,
url: string,
opts: Omit<LoginUrl, 'url'>,
hide?: boolean
): LoginButton
static removeKeyboard(value?: string): Markup<tt.ReplyKeyboardRemove> & tt.ReplyKeyboardRemove
static forceReply(value?: boolean): Markup<tt.ForceReply> & tt.ForceReply
static keyboard(
buttons: KeyboardButton[] | KeyboardButton[][],
options?: KeyboardOptions<KeyboardButton>
): Markup<tt.ReplyKeyboardMarkup> & tt.ReplyKeyboardMarkup
static inlineKeyboard(
buttons: InlineKeyboardButton[] | InlineKeyboardButton[][],
options?: KeyboardOptions<InlineKeyboardButton>
): Markup<tt.InlineKeyboardMarkup> & tt.InlineKeyboardMarkup
static resize(value?: boolean): Markup<tt.ReplyKeyboardMarkup>
static inputFieldPlaceholder(placeholder: string): Markup<tt.ReplyKeyboardMarkup | tt.ForceReply>
static selective(value?: boolean): Markup<tt.ReplyMarkupBundle>
static oneTime(value?: boolean): Markup<tt.ReplyKeyboardMarkup>
static button(text: string, hide?: boolean): Button
static contactRequestButton(
text: string,
hide?: boolean
): ContactRequestButton
static locationRequestButton(
text: string,
hide?: boolean
): LocationRequestButton
static pollRequestButton(
text: string,
type: PollType,
hide?: boolean
): PollRequestButton
static urlButton(text: string, url: string, hide?: boolean): UrlButton
static callbackButton(
text: string,
data: string,
hide?: boolean
): CallbackButton
static switchToChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToChatButton
static switchToCurrentChatButton(
text: string,
value: string,
hide?: boolean
): SwitchToCurrentChatButton
static gameButton(text: string, hide?: boolean): GameButton
static payButton(text: string, hide?: boolean): PayButton
static loginButton(
text: string,
url: string,
opts: Omit<LoginUrl, 'url'>,
hide?: boolean
): LoginButton
static formatHTML(text: string, entities: Array<tt.MessageEntity>): string
}

37
node_modules/telegraf/typings/router.d.ts generated vendored Normal file
View File

@@ -0,0 +1,37 @@
/** @format */
import { MiddlewareObj, Middleware, MiddlewareFn } from './composer'
import { TelegrafContext } from './context'
type TRoute = string
type MaybePromise<T> = T | Promise<T>
export type RouteFn<TContext extends TelegrafContext> = (
ctx: TContext
) => MaybePromise<{
route?: TRoute
} | null>
type HandlersMap<TContext extends TelegrafContext> = Map<
TRoute,
Middleware<TContext>
>
declare class Router<TContext extends TelegrafContext>
implements MiddlewareObj<TContext> {
routeFn: RouteFn<TContext>
handlers: HandlersMap<TContext>
otherwiseHandler: Middleware<TContext>
constructor(routeFn: RouteFn<TContext>, handlers?: HandlersMap<TContext>)
on(
route: TRoute,
fn: Middleware<TContext>,
...fns: Middleware<TContext>[]
): this
otherwise(fn: Middleware<TContext>, ...fns: Middleware<TContext>[]): this
middleware(): MiddlewareFn<TContext>
}

11
node_modules/telegraf/typings/session.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
/** @format */
import { TelegrafContext } from './context'
import { Middleware } from './composer'
export declare function session<TContext extends TelegrafContext>(opts?: {
property?: string
store?: Map<string, any>
getSessionKey?: (ctx: TContext) => string
ttl?: number
}): Middleware<TContext>

100
node_modules/telegraf/typings/stage.d.ts generated vendored Normal file
View File

@@ -0,0 +1,100 @@
/** @format */
import { TelegrafContext } from './context'
import { Middleware, Composer, MiddlewareFn } from './composer'
export interface SceneContextOptions {
sessionName: string
default?: string
ttl?: number
}
export interface SceneContext<TContext extends SceneContextMessageUpdate> {
ctx: TContext
scenes: Map<string, Scene<TContext>>
options: SceneContextOptions
readonly session: {
state?: object
current?: string
expires?: number
}
state: object
readonly current: BaseScene<TContext> | null
reset: () => void
enter: (
sceneId: string,
initialState?: object,
silent?: boolean
) => Promise<any>
reenter: () => Promise<any>
leave: () => Promise<any>
}
export interface SceneContextMessageUpdate extends TelegrafContext {
scene: SceneContext<this>
}
export interface BaseSceneOptions<TContext extends SceneContextMessageUpdate> {
handlers: Middleware<TContext>[]
enterHandlers: Middleware<TContext>[]
leaveHandlers: Middleware<TContext>[]
ttl?: number
}
export class BaseScene<
TContext extends SceneContextMessageUpdate
> extends Composer<TContext> {
constructor(id: string, options?: Partial<BaseSceneOptions<TContext>>)
id: string
options: BaseSceneOptions<TContext>
enterHandler: Middleware<TContext>
leaveHandler: Middleware<TContext>
ttl?: number
enter: (...fns: Middleware<TContext>[]) => this
leave: (...fns: Middleware<TContext>[]) => this
enterMiddleware: () => Middleware<TContext>
leaveMiddleware: () => Middleware<TContext>
}
export type Scene<TContext extends SceneContextMessageUpdate> = BaseScene<
TContext
>
export type StageOptions = SceneContextOptions
export class Stage<TContext extends SceneContextMessageUpdate> extends Composer<
TContext
> {
constructor(scenes: Scene<TContext>[], options?: Partial<StageOptions>)
register: (...scenes: Scene<TContext>[]) => this
middleware: () => MiddlewareFn<TContext>
static enter: (
sceneId: string,
initialState?: object,
silent?: boolean
) => Middleware<SceneContextMessageUpdate>
static reenter: () => Middleware<SceneContextMessageUpdate>
static leave: () => Middleware<SceneContextMessageUpdate>
}

221
node_modules/telegraf/typings/telegraf.d.ts generated vendored Normal file
View File

@@ -0,0 +1,221 @@
/** @format */
/// <reference types="node" />
import { IncomingMessage, ServerResponse } from 'http'
import { TlsOptions } from 'tls'
import * as tt from './telegram-types.d'
import { TelegrafContext } from './context'
import { Composer } from './composer'
import { Telegram, TelegramOptions } from './telegram'
export interface TelegrafOptions extends TOptions {
/**
* Parse mode
*/
parseMode?: tt.ParseMode
/**
* Telegram options
*/
telegram?: TelegramOptions
/**
* Custom context
*/
contextType?: TelegrafContext
/**
* Autoset after launch by botInfo method
*/
username?: never
}
export interface LaunchPollingOptions {
/**
* Poll timeout in seconds
*/
timeout?: number
/**
* Limits the number of updates to be retrieved
*/
limit?: number
/**
* List the types of updates you want your bot to receive
*/
allowedUpdates?: tt.UpdateType[] | tt.UpdateType | null
/**
* Polling stop callback
*/
stopCallback?: () => void | null
}
export interface LaunchWebhookOptions {
/**
* Public domain for webhook. If domain is not specified, hookPath should contain a domain name as well (not only path component).
*/
domain?: string
/**
* Webhook url path; will be automatically generated if not specified
*/
hookPath?: string
/**
* The port to listen on for Telegram calls. If port is omitted or is 0, the operating system will assign an arbitrary unused port.
*/
port?: number
/**
* The host to listen on for Telegram calls. If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.
*/
host?: string
/**
* TLS server options. Pass null (or omit) to use http.
*/
tlsOptions?: TlsOptions | null
/**
* A callback function suitable for the http[s].createServer() method to handle a request.
*/
cb?: (req: IncomingMessage, res: ServerResponse) => void
}
export declare class Telegraf<
TContext extends TelegrafContext
> extends Composer<TContext> {
/**
* Use this property to get/set bot token
*/
token: string
/**
* Use this property to control reply via webhook feature.
*/
webhookReply: boolean
/**
* Use this property to get telegram instance
*/
telegram: Telegram
/**
* Use this property to extend context and support your custom interface
*/
context: TContext
/**
* Telegraf options
*/
options: TOptions
/**
* Initialize new Telegraf app.
* @param token Bot token
* @param options options
* @example
* new Telegraf(token, options)
*/
constructor(token: string, options?: TelegrafOptions)
/**
* Launch bot in long-polling or webhook mode.
*
* @param options [See reference to get more]{@link https://telegraf.js.org/#/?id=launch}
*/
launch(options?: {
polling?: LaunchPollingOptions
webhook?: LaunchWebhookOptions
}): Promise<void>
/**
* Start poll updates.
* @param timeout Poll timeout in seconds
* @param limit Limits the number of updates to be retrieved
* @param allowedUpdates List the types of updates you want your bot to receive
* @param stopCallback Polling stop callback
*/
startPolling(
timeout?: number,
limit?: number,
allowedUpdates?: tt.UpdateType[] | tt.UpdateType | null,
stopCallback?: () => void | null
): Telegraf<TContext>
/**
* Start listening @ https://host:port/hookPath for Telegram calls.
* @param hookPath Webhook url path (see Telegraf.setWebhook)
* @param tlsOptions TLS server options. Pass null to use http
* @param port Port number
* @param host Hostname
* @param cb A callback function suitable for the http[s].createServer() method to handle a request.
*/
startWebhook(
hookPath: string,
tlsOptions?: TlsOptions | null,
port?: number,
host?: string,
cb?: (req: IncomingMessage, res: ServerResponse) => void
): Telegraf<TContext>
/**
* Stop Webhook and polling
*/
stop(cb?: () => void): Promise<void>
/**
* Return a callback function suitable for the http[s].createServer() method to handle a request.
* You may also use this callback function to mount your telegraf app in a Koa/Connect/Express app.
* @param hookPath Webhook url path (see Telegraf.setWebhook)
*/
webhookCallback(
hookPath: string
): (req: IncomingMessage, res: ServerResponse) => void
handleUpdates(updates: tt.Update[]): Promise<unknown[]>
/**
* Handle raw Telegram update. In case you use centralized webhook server, queue, etc.
*/
handleUpdate(
update: tt.Update,
webhookResponse?: ServerResponse
): Promise<unknown>
private fetchUpdates(): void
catch(logFn?: Function): void
}
export interface TOptions {
/**
* Telegram options
*/
telegram?: TelegramOptions
/**
* Bot username
*/
username?: string
/**
* Handle `channel_post` updates as messages
*/
channelMode?: boolean
/**
* Delay (in seconds) before making a follow-up request to get updates
*/
retryAfter?: number
/**
* Maximum amount of time (in microseconds) for which middlewares execution can pause updates fetching
*/
handlerTimeout?: number
}

1087
node_modules/telegraf/typings/telegram-types.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

1119
node_modules/telegraf/typings/telegram.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff