telegraf-ts
Advanced tools
Comparing version 3.36.4 to 3.88.2
module.exports = { | ||
root: true, | ||
extends: ["@frontendmonster"], | ||
parserOptions: { | ||
project: "./tsconfig.json", | ||
project: "./tsconfig.eslint.json", | ||
}, | ||
@@ -6,0 +7,0 @@ rules: { |
504
composer.js
@@ -1,408 +0,484 @@ | ||
const Context = require('./context') | ||
const Context = require('./context'); | ||
class Composer { | ||
constructor (...fns) { | ||
this.handler = Composer.compose(fns) | ||
constructor(...fns) { | ||
this.handler = Composer.compose(fns); | ||
} | ||
use (...fns) { | ||
this.handler = Composer.compose([this.handler, ...fns]) | ||
return this | ||
use(...fns) { | ||
this.handler = Composer.compose([this.handler, ...fns]); | ||
return this; | ||
} | ||
on (updateTypes, ...fns) { | ||
return this.use(Composer.mount(updateTypes, ...fns)) | ||
on(updateTypes, ...fns) { | ||
return this.use(Composer.mount(updateTypes, ...fns)); | ||
} | ||
hears (triggers, ...fns) { | ||
return this.use(Composer.hears(triggers, ...fns)) | ||
hears(triggers, ...fns) { | ||
return this.use(Composer.hears(triggers, ...fns)); | ||
} | ||
command (commands, ...fns) { | ||
return this.use(Composer.command(commands, ...fns)) | ||
command(commands, ...fns) { | ||
return this.use(Composer.command(commands, ...fns)); | ||
} | ||
action (triggers, ...fns) { | ||
return this.use(Composer.action(triggers, ...fns)) | ||
action(triggers, ...fns) { | ||
return this.use(Composer.action(triggers, ...fns)); | ||
} | ||
inlineQuery (triggers, ...fns) { | ||
return this.use(Composer.inlineQuery(triggers, ...fns)) | ||
inlineQuery(triggers, ...fns) { | ||
return this.use(Composer.inlineQuery(triggers, ...fns)); | ||
} | ||
gameQuery (...fns) { | ||
return this.use(Composer.gameQuery(...fns)) | ||
gameQuery(...fns) { | ||
return this.use(Composer.gameQuery(...fns)); | ||
} | ||
drop (predicate) { | ||
return this.use(Composer.drop(predicate)) | ||
drop(predicate) { | ||
return this.use(Composer.drop(predicate)); | ||
} | ||
filter (predicate) { | ||
return this.use(Composer.filter(predicate)) | ||
filter(predicate) { | ||
return this.use(Composer.filter(predicate)); | ||
} | ||
entity (...args) { | ||
return this.use(Composer.entity(...args)) | ||
entity(...args) { | ||
return this.use(Composer.entity(...args)); | ||
} | ||
email (...args) { | ||
return this.use(Composer.email(...args)) | ||
email(...args) { | ||
return this.use(Composer.email(...args)); | ||
} | ||
url (...args) { | ||
return this.use(Composer.url(...args)) | ||
url(...args) { | ||
return this.use(Composer.url(...args)); | ||
} | ||
textLink (...args) { | ||
return this.use(Composer.textLink(...args)) | ||
textLink(...args) { | ||
return this.use(Composer.textLink(...args)); | ||
} | ||
textMention (...args) { | ||
return this.use(Composer.textMention(...args)) | ||
textMention(...args) { | ||
return this.use(Composer.textMention(...args)); | ||
} | ||
mention (...args) { | ||
return this.use(Composer.mention(...args)) | ||
mention(...args) { | ||
return this.use(Composer.mention(...args)); | ||
} | ||
phone (...args) { | ||
return this.use(Composer.phone(...args)) | ||
phone(...args) { | ||
return this.use(Composer.phone(...args)); | ||
} | ||
hashtag (...args) { | ||
return this.use(Composer.hashtag(...args)) | ||
hashtag(...args) { | ||
return this.use(Composer.hashtag(...args)); | ||
} | ||
cashtag (...args) { | ||
return this.use(Composer.cashtag(...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) | ||
start(...fns) { | ||
return this.command( | ||
'start', | ||
Composer.tap(ctx => { | ||
ctx.startPayload = ctx.message.text.substring(7); | ||
}), | ||
...fns, | ||
); | ||
} | ||
help (...fns) { | ||
return this.command('help', ...fns) | ||
help(...fns) { | ||
return this.command('help', ...fns); | ||
} | ||
settings (...fns) { | ||
return this.command('settings', ...fns) | ||
settings(...fns) { | ||
return this.command('settings', ...fns); | ||
} | ||
middleware () { | ||
return this.handler | ||
middleware() { | ||
return this.handler; | ||
} | ||
static reply (...args) { | ||
return (ctx) => ctx.reply(...args) | ||
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 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 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) | ||
static fork(middleware) { | ||
const handler = Composer.unwrap(middleware); | ||
return (ctx, next) => { | ||
setImmediate(handler, ctx, Composer.safePassThru()) | ||
return next(ctx) | ||
} | ||
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 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 passThru() { | ||
return (ctx, next) => next(ctx); | ||
} | ||
static safePassThru () { | ||
return (ctx, next) => typeof next === 'function' ? next(ctx) : Promise.resolve() | ||
static safePassThru() { | ||
return (ctx, next) => | ||
typeof next === 'function' ? next(ctx) : Promise.resolve(); | ||
} | ||
static lazy (factoryFn) { | ||
static lazy(factoryFn) { | ||
if (typeof factoryFn !== 'function') { | ||
throw new Error('Argument must be a function') | ||
throw new Error('Argument must be a function'); | ||
} | ||
return (ctx, next) => Promise.resolve(factoryFn(ctx)) | ||
.then((middleware) => Composer.unwrap(middleware)(ctx, next)) | ||
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 log(logFn = console.log) { | ||
return Composer.fork(ctx => logFn(JSON.stringify(ctx.update, null, 2))); | ||
} | ||
static branch (predicate, trueMiddleware, falseMiddleware) { | ||
static branch(predicate, trueMiddleware, falseMiddleware) { | ||
if (typeof predicate !== 'function') { | ||
return predicate ? trueMiddleware : falseMiddleware | ||
return predicate ? trueMiddleware : falseMiddleware; | ||
} | ||
return Composer.lazy((ctx) => Promise.resolve(predicate(ctx)) | ||
.then((value) => value ? 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 optional(predicate, ...fns) { | ||
return Composer.branch( | ||
predicate, | ||
Composer.compose(fns), | ||
Composer.safePassThru(), | ||
); | ||
} | ||
static filter (predicate) { | ||
return Composer.branch(predicate, Composer.safePassThru(), () => { }) | ||
static filter(predicate) { | ||
return Composer.branch(predicate, Composer.safePassThru(), () => {}); | ||
} | ||
static drop (predicate) { | ||
return Composer.branch(predicate, () => { }, Composer.safePassThru()) | ||
static drop(predicate) { | ||
return Composer.branch(predicate, () => {}, Composer.safePassThru()); | ||
} | ||
static dispatch (routeFn, handlers) { | ||
static dispatch(routeFn, handlers) { | ||
return typeof routeFn === 'function' | ||
? Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value])) | ||
: handlers[routeFn] | ||
? 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 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) { | ||
static entity(predicate, ...fns) { | ||
if (typeof predicate !== 'function') { | ||
const entityTypes = normalizeTextArguments(predicate) | ||
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns) | ||
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) | ||
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) { | ||
static entityText(entityType, predicate, ...fns) { | ||
if (fns.length === 0) { | ||
return Array.isArray(predicate) | ||
? Composer.entity(entityType, ...predicate) | ||
: Composer.entity(entityType, predicate) | ||
: Composer.entity(entityType, predicate); | ||
} | ||
const triggers = normalizeTriggers(predicate) | ||
const triggers = normalizeTriggers(predicate); | ||
return Composer.entity(({ type }, value, ctx) => { | ||
if (type !== entityType) { | ||
return false | ||
return false; | ||
} | ||
for (const trigger of triggers) { | ||
ctx.match = trigger(value, ctx) | ||
ctx.match = trigger(value, ctx); | ||
if (ctx.match) { | ||
return true | ||
return true; | ||
} | ||
} | ||
}, ...fns) | ||
}, ...fns); | ||
} | ||
static email (email, ...fns) { | ||
return Composer.entityText('email', email, ...fns) | ||
static email(email, ...fns) { | ||
return Composer.entityText('email', email, ...fns); | ||
} | ||
static phone (number, ...fns) { | ||
return Composer.entityText('phone_number', number, ...fns) | ||
static phone(number, ...fns) { | ||
return Composer.entityText('phone_number', number, ...fns); | ||
} | ||
static url (url, ...fns) { | ||
return Composer.entityText('url', url, ...fns) | ||
static url(url, ...fns) { | ||
return Composer.entityText('url', url, ...fns); | ||
} | ||
static textLink (link, ...fns) { | ||
return Composer.entityText('text_link', link, ...fns) | ||
static textLink(link, ...fns) { | ||
return Composer.entityText('text_link', link, ...fns); | ||
} | ||
static textMention (mention, ...fns) { | ||
return Composer.entityText('text_mention', mention, ...fns) | ||
static textMention(mention, ...fns) { | ||
return Composer.entityText('text_mention', mention, ...fns); | ||
} | ||
static mention (mention, ...fns) { | ||
return Composer.entityText('mention', normalizeTextArguments(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 hashtag(hashtag, ...fns) { | ||
return Composer.entityText( | ||
'hashtag', | ||
normalizeTextArguments(hashtag, '#'), | ||
...fns, | ||
); | ||
} | ||
static cashtag (cashtag, ...fns) { | ||
return Composer.entityText('cashtag', normalizeTextArguments(cashtag, '$'), ...fns) | ||
static cashtag(cashtag, ...fns) { | ||
return Composer.entityText( | ||
'cashtag', | ||
normalizeTextArguments(cashtag, '$'), | ||
...fns, | ||
); | ||
} | ||
static match (triggers, ...fns) { | ||
return Composer.optional((ctx) => { | ||
const text = ( | ||
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) | ||
) | ||
(ctx.inlineQuery && ctx.inlineQuery.query); | ||
for (const trigger of triggers) { | ||
ctx.match = trigger(text, ctx) | ||
ctx.match = trigger(text, ctx); | ||
if (ctx.match) { | ||
return true | ||
return true; | ||
} | ||
} | ||
}, ...fns) | ||
}, ...fns); | ||
} | ||
static hears (triggers, ...fns) { | ||
return Composer.mount('text', Composer.match(normalizeTriggers(triggers), ...fns)) | ||
static hears(triggers, ...fns) { | ||
return Composer.mount( | ||
'text', | ||
Composer.match(normalizeTriggers(triggers), ...fns), | ||
); | ||
} | ||
static command (command, ...fns) { | ||
static command(command, ...fns) { | ||
if (fns.length === 0) { | ||
return Composer.entity(['bot_command'], command) | ||
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) | ||
})) | ||
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 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 inlineQuery(triggers, ...fns) { | ||
return Composer.mount( | ||
'inline_query', | ||
Composer.match(normalizeTriggers(triggers), ...fns), | ||
); | ||
} | ||
static acl (userId, ...fns) { | ||
static acl(userId, ...fns) { | ||
if (typeof userId === 'function') { | ||
return Composer.optional(userId, ...fns) | ||
return Composer.optional(userId, ...fns); | ||
} | ||
const allowed = Array.isArray(userId) ? userId : [userId] | ||
return Composer.optional((ctx) => !ctx.from || allowed.includes(ctx.from.id), ...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 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 admin(...fns) { | ||
return Composer.memberStatus(['administrator', 'creator'], ...fns); | ||
} | ||
static creator (...fns) { | ||
return Composer.memberStatus('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 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 privateChat(...fns) { | ||
return Composer.chatType('private', ...fns); | ||
} | ||
static groupChat (...fns) { | ||
return Composer.chatType(['group', 'supergroup'], ...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 gameQuery(...fns) { | ||
return Composer.mount( | ||
'callback_query', | ||
Composer.optional(ctx => ctx.callbackQuery.game_short_name, ...fns), | ||
); | ||
} | ||
static unwrap (handler) { | ||
static unwrap(handler) { | ||
if (!handler) { | ||
throw new Error('Handler is undefined') | ||
throw new Error('Handler is undefined'); | ||
} | ||
return typeof handler.middleware === 'function' | ||
? handler.middleware() | ||
: handler | ||
: handler; | ||
} | ||
static compose (middlewares) { | ||
static compose(middlewares) { | ||
if (!Array.isArray(middlewares)) { | ||
throw new Error('Middlewares must be an array') | ||
throw new Error('Middlewares must be an array'); | ||
} | ||
if (middlewares.length === 0) { | ||
return Composer.safePassThru() | ||
return Composer.safePassThru(); | ||
} | ||
if (middlewares.length === 1) { | ||
return Composer.unwrap(middlewares[0]) | ||
return Composer.unwrap(middlewares[0]); | ||
} | ||
return (ctx, next) => { | ||
let index = -1 | ||
return execute(0, ctx) | ||
function execute (i, context) { | ||
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')) | ||
return Promise.reject( | ||
new Error('next(ctx) called with invalid context'), | ||
); | ||
} | ||
if (i <= index) { | ||
return Promise.reject(new Error('next() called multiple times')) | ||
return Promise.reject(new Error('next() called multiple times')); | ||
} | ||
index = i | ||
const handler = middlewares[i] ? Composer.unwrap(middlewares[i]) : next | ||
index = i; | ||
const handler = middlewares[i] ? Composer.unwrap(middlewares[i]) : next; | ||
if (!handler) { | ||
return Promise.resolve() | ||
return Promise.resolve(); | ||
} | ||
try { | ||
return Promise.resolve( | ||
handler(context, (ctx = context) => execute(i + 1, ctx)) | ||
) | ||
handler(context, (ctx = context) => execute(i + 1, ctx)), | ||
); | ||
} catch (err) { | ||
return Promise.reject(err) | ||
return Promise.reject(err); | ||
} | ||
} | ||
} | ||
}; | ||
} | ||
} | ||
function normalizeTriggers (triggers) { | ||
function normalizeTriggers(triggers) { | ||
if (!Array.isArray(triggers)) { | ||
triggers = [triggers] | ||
triggers = [triggers]; | ||
} | ||
return triggers.map((trigger) => { | ||
return triggers.map(trigger => { | ||
if (!trigger) { | ||
throw new Error('Invalid trigger') | ||
throw new Error('Invalid trigger'); | ||
} | ||
if (typeof trigger === 'function') { | ||
return trigger | ||
return trigger; | ||
} | ||
if (trigger instanceof RegExp) { | ||
return (value) => { | ||
trigger.lastIndex = 0 | ||
return trigger.exec(value || '') | ||
} | ||
return value => { | ||
trigger.lastIndex = 0; | ||
return trigger.exec(value || ''); | ||
}; | ||
} | ||
return (value) => trigger === value ? value : null | ||
}) | ||
return value => (trigger === value ? value : null); | ||
}); | ||
} | ||
function normalizeTextArguments (argument, prefix) { | ||
const args = Array.isArray(argument) ? argument : [argument] | ||
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) | ||
.map(arg => | ||
prefix && typeof arg === 'string' && !arg.startsWith(prefix) | ||
? `${prefix}${arg}` | ||
: arg, | ||
); | ||
} | ||
module.exports = Composer | ||
module.exports = Composer; |
633
context.js
@@ -12,4 +12,4 @@ const UpdateTypes = [ | ||
'poll', | ||
'poll_answer' | ||
] | ||
'poll_answer', | ||
]; | ||
@@ -38,2 +38,3 @@ const MessageSubTypes = [ | ||
'game', | ||
'dice', | ||
'document', | ||
@@ -47,15 +48,15 @@ 'delete_chat_photo', | ||
'poll', | ||
'forward_date' | ||
] | ||
'forward_date', | ||
]; | ||
const MessageSubTypesMapping = { | ||
forward_date: 'forward' | ||
} | ||
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) | ||
constructor(update, telegram, options) { | ||
this.tg = telegram; | ||
this.update = update; | ||
this.options = options; | ||
this.updateType = UpdateTypes.find(key => key in this.update); | ||
if ( | ||
@@ -66,65 +67,65 @@ this.updateType === 'message' || | ||
this.updateSubTypes = MessageSubTypes.filter( | ||
key => key in this.update[this.updateType] | ||
).map(type => MessageSubTypesMapping[type] || type) | ||
key => key in this.update[this.updateType], | ||
).map(type => MessageSubTypesMapping[type] || type); | ||
} else { | ||
this.updateSubTypes = [] | ||
this.updateSubTypes = []; | ||
} | ||
Object.getOwnPropertyNames(TelegrafContext.prototype) | ||
.filter(key => key !== 'constructor' && typeof this[key] === 'function') | ||
.forEach(key => (this[key] = this[key].bind(this))) | ||
.forEach(key => (this[key] = this[key].bind(this))); | ||
} | ||
get me () { | ||
return this.options && this.options.username | ||
get me() { | ||
return this.options && this.options.username; | ||
} | ||
get telegram () { | ||
return this.tg | ||
get telegram() { | ||
return this.tg; | ||
} | ||
get message () { | ||
return this.update.message | ||
get message() { | ||
return this.update.message; | ||
} | ||
get editedMessage () { | ||
return this.update.edited_message | ||
get editedMessage() { | ||
return this.update.edited_message; | ||
} | ||
get inlineQuery () { | ||
return this.update.inline_query | ||
get inlineQuery() { | ||
return this.update.inline_query; | ||
} | ||
get shippingQuery () { | ||
return this.update.shipping_query | ||
get shippingQuery() { | ||
return this.update.shipping_query; | ||
} | ||
get preCheckoutQuery () { | ||
return this.update.pre_checkout_query | ||
get preCheckoutQuery() { | ||
return this.update.pre_checkout_query; | ||
} | ||
get chosenInlineResult () { | ||
return this.update.chosen_inline_result | ||
get chosenInlineResult() { | ||
return this.update.chosen_inline_result; | ||
} | ||
get channelPost () { | ||
return this.update.channel_post | ||
get channelPost() { | ||
return this.update.channel_post; | ||
} | ||
get editedChannelPost () { | ||
return this.update.edited_channel_post | ||
get editedChannelPost() { | ||
return this.update.edited_channel_post; | ||
} | ||
get callbackQuery () { | ||
return this.update.callback_query | ||
get callbackQuery() { | ||
return this.update.callback_query; | ||
} | ||
get poll () { | ||
return this.update.poll | ||
get poll() { | ||
return this.update.poll; | ||
} | ||
get pollAnswer () { | ||
return this.update.poll_answer | ||
get pollAnswer() { | ||
return this.update.poll_answer; | ||
} | ||
get chat () { | ||
get chat() { | ||
return ( | ||
@@ -138,6 +139,6 @@ (this.message && this.message.chat) || | ||
(this.editedChannelPost && this.editedChannelPost.chat) | ||
) | ||
); | ||
} | ||
get from () { | ||
get from() { | ||
return ( | ||
@@ -153,215 +154,220 @@ (this.message && this.message.from) || | ||
(this.chosenInlineResult && this.chosenInlineResult.from) | ||
) | ||
); | ||
} | ||
get inlineMessageId () { | ||
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 passportData() { | ||
return this.message && this.message.passport_data; | ||
} | ||
get state () { | ||
get state() { | ||
if (!this.contextState) { | ||
this.contextState = {} | ||
this.contextState = {}; | ||
} | ||
return this.contextState | ||
return this.contextState; | ||
} | ||
set state (value) { | ||
this.contextState = { ...value } | ||
set state(value) { | ||
this.contextState = { ...value }; | ||
} | ||
get webhookReply () { | ||
return this.tg.webhookReply | ||
get webhookReply() { | ||
return this.tg.webhookReply; | ||
} | ||
set webhookReply (enable) { | ||
this.tg.webhookReply = enable | ||
set webhookReply(enable) { | ||
this.tg.webhookReply = enable; | ||
} | ||
assert (value, method) { | ||
assert(value, method) { | ||
if (!value) { | ||
throw new Error( | ||
`Telegraf: "${method}" isn't available for "${this.updateType}::${this.updateSubTypes}"` | ||
) | ||
`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) | ||
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) | ||
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) | ||
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) | ||
answerShippingQuery(...args) { | ||
this.assert(this.shippingQuery, 'answerShippingQuery'); | ||
return this.telegram.answerShippingQuery(this.shippingQuery.id, ...args); | ||
} | ||
answerPreCheckoutQuery (...args) { | ||
this.assert(this.preCheckoutQuery, 'answerPreCheckoutQuery') | ||
answerPreCheckoutQuery(...args) { | ||
this.assert(this.preCheckoutQuery, 'answerPreCheckoutQuery'); | ||
return this.telegram.answerPreCheckoutQuery( | ||
this.preCheckoutQuery.id, | ||
...args | ||
) | ||
...args, | ||
); | ||
} | ||
editMessageText (text, extra) { | ||
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageText') | ||
editMessageText(text, extra) { | ||
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageText'); | ||
return this.inlineMessageId | ||
? this.telegram.editMessageText( | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
text, | ||
extra | ||
) | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
text, | ||
extra, | ||
) | ||
: this.telegram.editMessageText( | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
text, | ||
extra | ||
) | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
text, | ||
extra, | ||
); | ||
} | ||
editMessageCaption (caption, extra) { | ||
editMessageCaption(caption, extra) { | ||
this.assert( | ||
this.callbackQuery || this.inlineMessageId, | ||
'editMessageCaption' | ||
) | ||
'editMessageCaption', | ||
); | ||
return this.inlineMessageId | ||
? this.telegram.editMessageCaption( | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
caption, | ||
extra | ||
) | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
caption, | ||
extra, | ||
) | ||
: this.telegram.editMessageCaption( | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
caption, | ||
extra | ||
) | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
caption, | ||
extra, | ||
); | ||
} | ||
editMessageMedia (media, extra) { | ||
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageMedia') | ||
editMessageMedia(media, extra) { | ||
this.assert(this.callbackQuery || this.inlineMessageId, 'editMessageMedia'); | ||
return this.inlineMessageId | ||
? this.telegram.editMessageMedia( | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
media, | ||
extra | ||
) | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
media, | ||
extra, | ||
) | ||
: this.telegram.editMessageMedia( | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
media, | ||
extra | ||
) | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
media, | ||
extra, | ||
); | ||
} | ||
editMessageReplyMarkup (markup) { | ||
editMessageReplyMarkup(markup) { | ||
this.assert( | ||
this.callbackQuery || this.inlineMessageId, | ||
'editMessageReplyMarkup' | ||
) | ||
'editMessageReplyMarkup', | ||
); | ||
return this.inlineMessageId | ||
? this.telegram.editMessageReplyMarkup( | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
markup | ||
) | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
markup, | ||
) | ||
: this.telegram.editMessageReplyMarkup( | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
markup | ||
) | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
markup, | ||
); | ||
} | ||
editMessageLiveLocation (latitude, longitude, markup) { | ||
editMessageLiveLocation(latitude, longitude, markup) { | ||
this.assert( | ||
this.callbackQuery || this.inlineMessageId, | ||
'editMessageLiveLocation' | ||
) | ||
'editMessageLiveLocation', | ||
); | ||
return this.inlineMessageId | ||
? this.telegram.editMessageLiveLocation( | ||
latitude, | ||
longitude, | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
markup | ||
) | ||
latitude, | ||
longitude, | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
markup, | ||
) | ||
: this.telegram.editMessageLiveLocation( | ||
latitude, | ||
longitude, | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
markup | ||
) | ||
latitude, | ||
longitude, | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
markup, | ||
); | ||
} | ||
stopMessageLiveLocation (markup) { | ||
stopMessageLiveLocation(markup) { | ||
this.assert( | ||
this.callbackQuery || this.inlineMessageId, | ||
'stopMessageLiveLocation' | ||
) | ||
'stopMessageLiveLocation', | ||
); | ||
return this.inlineMessageId | ||
? this.telegram.stopMessageLiveLocation( | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
markup | ||
) | ||
undefined, | ||
undefined, | ||
this.inlineMessageId, | ||
markup, | ||
) | ||
: this.telegram.stopMessageLiveLocation( | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
markup | ||
) | ||
this.chat.id, | ||
this.callbackQuery.message.message_id, | ||
undefined, | ||
markup, | ||
); | ||
} | ||
reply (...args) { | ||
this.assert(this.chat, 'reply') | ||
return this.telegram.sendMessage(this.chat.id, ...args) | ||
reply(...args) { | ||
this.assert(this.chat, 'reply'); | ||
return this.telegram.sendMessage(this.chat.id, ...args); | ||
} | ||
getChat (...args) { | ||
this.assert(this.chat, 'getChat') | ||
return this.telegram.getChat(this.chat.id, ...args) | ||
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) | ||
exportChatInviteLink(...args) { | ||
this.assert(this.chat, 'exportChatInviteLink'); | ||
return this.telegram.exportChatInviteLink(this.chat.id, ...args); | ||
} | ||
kickChatMember (...args) { | ||
this.assert(this.chat, 'kickChatMember') | ||
return this.telegram.kickChatMember(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) { | ||
@@ -372,92 +378,97 @@ this.assert(this.chat, 'restrictChatMember') | ||
promoteChatMember (...args) { | ||
this.assert(this.chat, 'promoteChatMember') | ||
return this.telegram.promoteChatMember(this.chat.id, ...args) | ||
promoteChatMember(...args) { | ||
this.assert(this.chat, 'promoteChatMember'); | ||
return this.telegram.promoteChatMember(this.chat.id, ...args); | ||
} | ||
unbanChatMember (...args) { | ||
this.assert(this.chat, 'unbanChatMember') | ||
return this.telegram.unbanChatMember(this.chat.id, ...args) | ||
unbanChatMember(...args) { | ||
this.assert(this.chat, 'unbanChatMember'); | ||
return this.telegram.unbanChatMember(this.chat.id, ...args); | ||
} | ||
setChatAdministratorCustomTitle (...args) { | ||
this.assert(this.chat, 'setChatAdministratorCustomTitle') | ||
return this.telegram.setChatAdministratorCustomTitle(this.chat.id, ...args) | ||
setChatAdministratorCustomTitle(...args) { | ||
this.assert(this.chat, 'setChatAdministratorCustomTitle'); | ||
return this.telegram.setChatAdministratorCustomTitle(this.chat.id, ...args); | ||
} | ||
setChatPhoto (...args) { | ||
this.assert(this.chat, 'setChatPhoto') | ||
return this.telegram.setChatPhoto(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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
unpinChatMessage(...args) { | ||
this.assert(this.chat, 'unpinChatMessage'); | ||
return this.telegram.unpinChatMessage(this.chat.id, ...args); | ||
} | ||
leaveChat (...args) { | ||
this.assert(this.chat, 'leaveChat') | ||
return this.telegram.leaveChat(this.chat.id, ...args) | ||
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) | ||
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) | ||
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) | ||
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.getChatMembersCount(this.chat.id, ...args) | ||
getChatMembersCount(...args) { | ||
this.assert(this.chat, 'getChatMembersCount'); | ||
return this.telegram.getChatMembersCount(this.chat.id, ...args); | ||
} | ||
setPassportDataErrors (errors) { | ||
this.assert(this.chat, 'setPassportDataErrors') | ||
return this.telegram.setPassportDataErrors(this.from.id, errors) | ||
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) | ||
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) | ||
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) | ||
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) { | ||
@@ -468,90 +479,94 @@ this.assert(this.chat, 'replyWithDocument') | ||
replyWithSticker (...args) { | ||
this.assert(this.chat, 'replyWithSticker') | ||
return this.telegram.sendSticker(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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
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) | ||
replyWithContact(...args) { | ||
this.assert(this.from, 'replyWithContact'); | ||
return this.telegram.sendContact(this.chat.id, ...args); | ||
} | ||
getStickerSet (setName) { | ||
return this.telegram.getStickerSet(setName) | ||
getStickerSet(setName) { | ||
return this.telegram.getStickerSet(setName); | ||
} | ||
setChatStickerSet (setName) { | ||
this.assert(this.chat, 'setChatStickerSet') | ||
return this.telegram.setChatStickerSet(this.chat.id, 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) | ||
deleteChatStickerSet() { | ||
this.assert(this.chat, 'deleteChatStickerSet'); | ||
return this.telegram.deleteChatStickerSet(this.chat.id); | ||
} | ||
setStickerPositionInSet (sticker, position) { | ||
return this.telegram.setStickerPositionInSet(sticker, position) | ||
setStickerPositionInSet(sticker, position) { | ||
return this.telegram.setStickerPositionInSet(sticker, position); | ||
} | ||
setStickerSetThumb (...args) { | ||
return this.telegram.setStickerSetThumb(...args) | ||
} | ||
deleteStickerFromSet (sticker) { | ||
@@ -561,17 +576,25 @@ return this.telegram.deleteStickerFromSet(sticker) | ||
uploadStickerFile (...args) { | ||
this.assert(this.from, 'uploadStickerFile') | ||
return this.telegram.uploadStickerFile(this.from.id, ...args) | ||
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) | ||
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) | ||
addStickerToSet(...args) { | ||
this.assert(this.from, 'addStickerToSet'); | ||
return this.telegram.addStickerToSet(this.from.id, ...args); | ||
} | ||
getMyCommands () { | ||
return this.telegram.getMyCommands() | ||
} | ||
setMyCommands (...args) { | ||
return this.telegram.setMyCommands(...args) | ||
} | ||
replyWithMarkdown (markdown, extra) { | ||
@@ -581,2 +604,6 @@ return this.reply(markdown, { parse_mode: 'Markdown', ...extra }) | ||
replyWithMarkdownV2 (markdown, extra) { | ||
return this.reply(markdown, { parse_mode: 'MarkdownV2', ...extra }) | ||
} | ||
replyWithHTML (html, extra) { | ||
@@ -586,6 +613,6 @@ return this.reply(html, { parse_mode: 'HTML', ...extra }) | ||
deleteMessage (messageId) { | ||
this.assert(this.chat, 'deleteMessage') | ||
deleteMessage(messageId) { | ||
this.assert(this.chat, 'deleteMessage'); | ||
if (typeof messageId !== 'undefined') { | ||
return this.telegram.deleteMessage(this.chat.id, messageId) | ||
return this.telegram.deleteMessage(this.chat.id, messageId); | ||
} | ||
@@ -597,9 +624,9 @@ const message = | ||
this.editedChannelPost || | ||
(this.callbackQuery && this.callbackQuery.message) | ||
this.assert(message, 'deleteMessage') | ||
return this.telegram.deleteMessage(this.chat.id, message.message_id) | ||
(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') | ||
forwardMessage(chatId, extra) { | ||
this.assert(this.chat, 'forwardMessage'); | ||
const message = | ||
@@ -610,4 +637,4 @@ this.message || | ||
this.editedChannelPost || | ||
(this.callbackQuery && this.callbackQuery.message) | ||
this.assert(message, 'forwardMessage') | ||
(this.callbackQuery && this.callbackQuery.message); | ||
this.assert(message, 'forwardMessage'); | ||
return this.telegram.forwardMessage( | ||
@@ -617,7 +644,7 @@ chatId, | ||
message.message_id, | ||
extra | ||
) | ||
extra, | ||
); | ||
} | ||
} | ||
module.exports = TelegrafContext | ||
module.exports = TelegrafContext; |
90
extra.js
@@ -1,85 +0,85 @@ | ||
const Markup = require('./markup') | ||
const Markup = require('./markup'); | ||
class Extra { | ||
constructor (opts) { | ||
this.load(opts) | ||
constructor(opts) { | ||
this.load(opts); | ||
} | ||
load (opts = {}) { | ||
return Object.assign(this, opts) | ||
load(opts = {}) { | ||
return Object.assign(this, opts); | ||
} | ||
inReplyTo (messageId) { | ||
this.reply_to_message_id = messageId | ||
return this | ||
inReplyTo(messageId) { | ||
this.reply_to_message_id = messageId; | ||
return this; | ||
} | ||
notifications (value = true) { | ||
this.disable_notification = !value | ||
return this | ||
notifications(value = true) { | ||
this.disable_notification = !value; | ||
return this; | ||
} | ||
webPreview (value = true) { | ||
this.disable_web_page_preview = !value | ||
return this | ||
webPreview(value = true) { | ||
this.disable_web_page_preview = !value; | ||
return this; | ||
} | ||
markup (markup) { | ||
markup(markup) { | ||
if (typeof markup === 'function') { | ||
markup = markup(new Markup()) | ||
markup = markup(new Markup()); | ||
} | ||
this.reply_markup = { ...markup } | ||
return this | ||
this.reply_markup = { ...markup }; | ||
return this; | ||
} | ||
HTML (value = true) { | ||
this.parse_mode = value ? 'HTML' : undefined | ||
return this | ||
HTML(value = true) { | ||
this.parse_mode = value ? 'HTML' : undefined; | ||
return this; | ||
} | ||
markdown (value = true) { | ||
this.parse_mode = value ? 'Markdown' : undefined | ||
return this | ||
markdown(value = true) { | ||
this.parse_mode = value ? 'Markdown' : undefined; | ||
return this; | ||
} | ||
caption (caption = '') { | ||
this.caption = caption | ||
return this | ||
caption(caption = '') { | ||
this.caption = caption; | ||
return this; | ||
} | ||
static inReplyTo (messageId) { | ||
return new Extra().inReplyTo(messageId) | ||
static inReplyTo(messageId) { | ||
return new Extra().inReplyTo(messageId); | ||
} | ||
static notifications (value) { | ||
return new Extra().notifications(value) | ||
static notifications(value) { | ||
return new Extra().notifications(value); | ||
} | ||
static webPreview (value) { | ||
return new Extra().webPreview(value) | ||
static webPreview(value) { | ||
return new Extra().webPreview(value); | ||
} | ||
static load (opts) { | ||
return new Extra(opts) | ||
static load(opts) { | ||
return new Extra(opts); | ||
} | ||
static markup (markup) { | ||
return new Extra().markup(markup) | ||
static markup(markup) { | ||
return new Extra().markup(markup); | ||
} | ||
static HTML (value) { | ||
return new Extra().HTML(value) | ||
static HTML(value) { | ||
return new Extra().HTML(value); | ||
} | ||
static markdown (value) { | ||
return new Extra().markdown(value) | ||
static markdown(value) { | ||
return new Extra().markdown(value); | ||
} | ||
static caption (caption) { | ||
return new Extra().caption(caption) | ||
static caption(caption) { | ||
return new Extra().caption(caption); | ||
} | ||
} | ||
Extra.Markup = Markup | ||
Extra.Markup = Markup; | ||
module.exports = Extra | ||
module.exports = Extra; |
297
markup.js
class Markup { | ||
forceReply (value = true) { | ||
this.force_reply = value | ||
return this | ||
forceReply(value = true) { | ||
this.force_reply = value; | ||
return this; | ||
} | ||
removeKeyboard (value = true) { | ||
this.remove_keyboard = value | ||
return this | ||
removeKeyboard(value = true) { | ||
this.remove_keyboard = value; | ||
return this; | ||
} | ||
selective (value = true) { | ||
this.selective = value | ||
return this | ||
selective(value = true) { | ||
this.selective = value; | ||
return this; | ||
} | ||
extra (options) { | ||
extra(options) { | ||
return { | ||
reply_markup: { ...this }, | ||
...options | ||
} | ||
...options, | ||
}; | ||
} | ||
keyboard (buttons, options) { | ||
const keyboard = buildKeyboard(buttons, { columns: 1, ...options }) | ||
keyboard(buttons, options) { | ||
const keyboard = buildKeyboard(buttons, { columns: 1, ...options }); | ||
if (keyboard && keyboard.length > 0) { | ||
this.keyboard = keyboard | ||
this.keyboard = keyboard; | ||
} | ||
return this | ||
return this; | ||
} | ||
resize (value = true) { | ||
this.resize_keyboard = value | ||
return this | ||
resize(value = true) { | ||
this.resize_keyboard = value; | ||
return this; | ||
} | ||
oneTime (value = true) { | ||
this.one_time_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 }) | ||
inlineKeyboard(buttons, options) { | ||
const keyboard = buildKeyboard(buttons, { | ||
columns: buttons.length, | ||
...options, | ||
}); | ||
if (keyboard && keyboard.length > 0) { | ||
this.inline_keyboard = keyboard | ||
this.inline_keyboard = keyboard; | ||
} | ||
return this | ||
return this; | ||
} | ||
button (text, hide) { | ||
return Markup.button(text, hide) | ||
button(text, hide) { | ||
return Markup.button(text, hide); | ||
} | ||
contactRequestButton (text, hide) { | ||
return Markup.contactRequestButton(text, hide) | ||
contactRequestButton(text, hide) { | ||
return Markup.contactRequestButton(text, hide); | ||
} | ||
locationRequestButton (text, hide) { | ||
return Markup.locationRequestButton(text, hide) | ||
locationRequestButton(text, hide) { | ||
return Markup.locationRequestButton(text, hide); | ||
} | ||
urlButton (text, url, hide) { | ||
return Markup.urlButton(text, url, hide) | ||
urlButton(text, url, hide) { | ||
return Markup.urlButton(text, url, hide); | ||
} | ||
callbackButton (text, data, hide) { | ||
return Markup.callbackButton(text, data, hide) | ||
callbackButton(text, data, hide) { | ||
return Markup.callbackButton(text, data, hide); | ||
} | ||
switchToChatButton (text, value, hide) { | ||
return Markup.switchToChatButton(text, value, hide) | ||
switchToChatButton(text, value, hide) { | ||
return Markup.switchToChatButton(text, value, hide); | ||
} | ||
switchToCurrentChatButton (text, value, hide) { | ||
return Markup.switchToCurrentChatButton(text, value, hide) | ||
switchToCurrentChatButton(text, value, hide) { | ||
return Markup.switchToCurrentChatButton(text, value, hide); | ||
} | ||
gameButton (text, hide) { | ||
return Markup.gameButton(text, hide) | ||
gameButton(text, hide) { | ||
return Markup.gameButton(text, hide); | ||
} | ||
payButton (text, hide) { | ||
return Markup.payButton(text, hide) | ||
payButton(text, hide) { | ||
return Markup.payButton(text, hide); | ||
} | ||
loginButton (text, url, opts, hide) { | ||
return Markup.loginButton(text, url, opts, hide) | ||
loginButton(text, url, opts, hide) { | ||
return Markup.loginButton(text, url, opts, hide); | ||
} | ||
static removeKeyboard (value) { | ||
return new Markup().removeKeyboard(value) | ||
static removeKeyboard(value) { | ||
return new Markup().removeKeyboard(value); | ||
} | ||
static forceReply (value) { | ||
return new Markup().forceReply(value) | ||
static forceReply(value) { | ||
return new Markup().forceReply(value); | ||
} | ||
static keyboard (buttons, options) { | ||
return new Markup().keyboard(buttons, options) | ||
static keyboard(buttons, options) { | ||
return new Markup().keyboard(buttons, options); | ||
} | ||
static inlineKeyboard (buttons, options) { | ||
return new Markup().inlineKeyboard(buttons, options) | ||
static inlineKeyboard(buttons, options) { | ||
return new Markup().inlineKeyboard(buttons, options); | ||
} | ||
static resize (value = true) { | ||
return new Markup().resize(value) | ||
static resize(value = true) { | ||
return new Markup().resize(value); | ||
} | ||
static selective (value = true) { | ||
return new Markup().selective(value) | ||
static selective(value = true) { | ||
return new Markup().selective(value); | ||
} | ||
static oneTime (value = true) { | ||
return new Markup().oneTime(value) | ||
static oneTime(value = true) { | ||
return new Markup().oneTime(value); | ||
} | ||
static button (text, hide = false) { | ||
return { text: text, hide: hide } | ||
static button(text, hide = false) { | ||
return { text: text, hide: hide }; | ||
} | ||
static contactRequestButton (text, hide = false) { | ||
return { text: text, request_contact: true, 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 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 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 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 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 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 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 gameButton(text, hide = false) { | ||
return { text: text, callback_game: {}, hide: hide }; | ||
} | ||
static payButton (text, hide = false) { | ||
return { text: text, pay: true, hide: hide } | ||
static payButton(text, hide = false) { | ||
return { text: text, pay: true, hide: hide }; | ||
} | ||
static loginButton (text, url, opts = {}, hide = false) { | ||
static loginButton(text, url, opts = {}, hide = false) { | ||
return { | ||
text: text, | ||
login_url: { ...opts, url: url }, | ||
hide: hide | ||
} | ||
hide: hide, | ||
}; | ||
} | ||
static formatHTML (text = '', entities = []) { | ||
const chars = [...text] | ||
const available = [...entities] | ||
const opened = [] | ||
const result = [] | ||
static formatHTML(text = '', entities = []) { | ||
const chars = [...text]; | ||
const available = [...entities]; | ||
const opened = []; | ||
const result = []; | ||
for (let offset = 0; offset < chars.length; offset++) { | ||
while (true) { | ||
const index = available.findIndex((entity) => entity.offset === offset) | ||
const index = available.findIndex(entity => entity.offset === offset); | ||
if (index === -1) { | ||
break | ||
break; | ||
} | ||
const entity = available[index] | ||
const entity = available[index]; | ||
switch (entity.type) { | ||
case 'bold': | ||
result.push('<b>') | ||
break | ||
result.push('<b>'); | ||
break; | ||
case 'italic': | ||
result.push('<i>') | ||
break | ||
result.push('<i>'); | ||
break; | ||
case 'code': | ||
result.push('<code>') | ||
break | ||
result.push('<code>'); | ||
break; | ||
case 'pre': | ||
result.push('<pre>') | ||
if (entity.language) { | ||
result.push(`<pre><code class="language-${entity.language}">`) | ||
} else { | ||
result.push('<pre>') | ||
} | ||
break | ||
case 'strikethrough': | ||
result.push('<s>') | ||
break | ||
result.push('<s>'); | ||
break; | ||
case 'underline': | ||
result.push('<u>') | ||
break | ||
result.push('<u>'); | ||
break; | ||
case 'text_mention': | ||
result.push(`<a href="tg://user?id=${entity.user.id}">`) | ||
break | ||
result.push(`<a href="tg://user?id=${entity.user.id}">`); | ||
break; | ||
case 'text_link': | ||
result.push(`<a href="${entity.url}">`) | ||
break | ||
result.push(`<a href="${entity.url}">`); | ||
break; | ||
} | ||
opened.unshift(entity) | ||
available.splice(index, 1) | ||
opened.unshift(entity); | ||
available.splice(index, 1); | ||
} | ||
result.push(chars[offset]) | ||
result.push(chars[offset]); | ||
while (true) { | ||
const index = opened.findIndex((entity) => entity.offset + entity.length - 1 === offset) | ||
const index = opened.findIndex( | ||
entity => entity.offset + entity.length - 1 === offset, | ||
); | ||
if (index === -1) { | ||
break | ||
break; | ||
} | ||
const entity = opened[index] | ||
const entity = opened[index]; | ||
switch (entity.type) { | ||
case 'bold': | ||
result.push('</b>') | ||
break | ||
result.push('</b>'); | ||
break; | ||
case 'italic': | ||
result.push('</i>') | ||
break | ||
result.push('</i>'); | ||
break; | ||
case 'code': | ||
result.push('</code>') | ||
break | ||
result.push('</code>'); | ||
break; | ||
case 'pre': | ||
result.push('</pre>') | ||
if (entity.language) { | ||
result.push('</code></pre>') | ||
} else { | ||
result.push('</pre>') | ||
} | ||
break | ||
case 'strikethrough': | ||
result.push('</s>') | ||
break | ||
result.push('</s>'); | ||
break; | ||
case 'underline': | ||
result.push('</u>') | ||
break | ||
result.push('</u>'); | ||
break; | ||
case 'text_mention': | ||
case 'text_link': | ||
result.push('</a>') | ||
break | ||
result.push('</a>'); | ||
break; | ||
} | ||
opened.splice(index, 1) | ||
opened.splice(index, 1); | ||
} | ||
} | ||
return result.join('') | ||
return result.join(''); | ||
} | ||
} | ||
function buildKeyboard (buttons, options) { | ||
const result = [] | ||
function buildKeyboard(buttons, options) { | ||
const result = []; | ||
if (!Array.isArray(buttons)) { | ||
return result | ||
return result; | ||
} | ||
if (buttons.find(Array.isArray)) { | ||
return buttons.map(row => row.filter((button) => !button.hide)) | ||
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)) { | ||
: (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 = [] | ||
result.push(currentRow); | ||
currentRow = []; | ||
} | ||
currentRow.push(btn) | ||
index++ | ||
currentRow.push(btn); | ||
index++; | ||
} | ||
if (currentRow.length > 0) { | ||
result.push(currentRow) | ||
result.push(currentRow); | ||
} | ||
return result | ||
return result; | ||
} | ||
module.exports = Markup | ||
module.exports = Markup; |
{ | ||
"name": "telegraf-ts", | ||
"version": "3.36.4", | ||
"version": "3.88.2", | ||
"description": "Well-Typed fork of telegraf", | ||
@@ -38,17 +38,18 @@ "license": "MIT", | ||
"dependencies": { | ||
"debug": "^4.0.1", | ||
"minimist": "^1.2.0", | ||
"module-alias": "^2.2.2", | ||
"node-fetch": "^2.2.0", | ||
"sandwich-stream": "^2.0.1" | ||
"debug": "4.0.1", | ||
"minimist": "1.2.0", | ||
"module-alias": "2.2.2", | ||
"node-fetch": "2.2.0", | ||
"sandwich-stream": "2.0.1" | ||
}, | ||
"devDependencies": { | ||
"@frontendmonster/eslint-config": "3.2.7", | ||
"@types/node": "^13.1.0", | ||
"ava": "^3.0.0", | ||
"eslint": "^6.2.2", | ||
"husky": "^4.2.0", | ||
"np": "6.2.0", | ||
"prettier": "2.0.2", | ||
"typescript": "^3.0.1" | ||
"@babel/core": "7.9.6", | ||
"@frontendmonster/eslint-config": "3.2.14", | ||
"@types/node": "13.13.5", | ||
"ava": "3.0.0", | ||
"eslint": "6.2.2", | ||
"husky": "4.2.5", | ||
"np": "6.2.3", | ||
"prettier": "2.0.5", | ||
"typescript": "3.0.1" | ||
}, | ||
@@ -55,0 +56,0 @@ "keywords": [ |
![Telegraf](docs/header.png) | ||
[![Bot API Version](https://img.shields.io/badge/Bot%20API-v4.6-f36caf.svg?style=flat-square)](https://core.telegram.org/bots/api) | ||
[![Bot API Version](https://img.shields.io/badge/Bot%20API-v4.8-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) | ||
@@ -7,2 +7,3 @@ [![node](https://img.shields.io/node/v/telegraf.svg?style=flat-square)](https://www.npmjs.com/package/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) | ||
@@ -17,3 +18,3 @@ ## Introduction | ||
- Full [Telegram Bot API 4.6](https://core.telegram.org/bots/api) support | ||
- Full [Telegram Bot API 4.8](https://core.telegram.org/bots/api) support | ||
- [Telegram Payment Platform](https://telegram.org/blog/payments) | ||
@@ -45,3 +46,3 @@ - [HTML5 Games](https://core.telegram.org/bots/api#games) | ||
```js | ||
const Telegraf = require('telegraf') | ||
const { Telegraf } = require('telegraf') | ||
@@ -57,3 +58,3 @@ const bot = new Telegraf(process.env.BOT_TOKEN) | ||
```js | ||
const Telegraf = require('telegraf') | ||
const { Telegraf } = require('telegraf') | ||
@@ -60,0 +61,0 @@ const bot = new Telegraf(process.env.BOT_TOKEN) |
@@ -1,43 +0,43 @@ | ||
const { compose, lazy, passThru } = require('./composer') | ||
const { compose, lazy, passThru } = require('./composer'); | ||
class Router { | ||
constructor (routeFn, handlers = new Map()) { | ||
constructor(routeFn, handlers = new Map()) { | ||
if (!routeFn) { | ||
throw new Error('Missing routing function') | ||
throw new Error('Missing routing function'); | ||
} | ||
this.routeFn = routeFn | ||
this.handlers = handlers | ||
this.otherwiseHandler = passThru() | ||
this.routeFn = routeFn; | ||
this.handlers = handlers; | ||
this.otherwiseHandler = passThru(); | ||
} | ||
on (route, ...fns) { | ||
on(route, ...fns) { | ||
if (fns.length === 0) { | ||
throw new TypeError('At least one handler must be provided') | ||
throw new TypeError('At least one handler must be provided'); | ||
} | ||
this.handlers.set(route, compose(fns)) | ||
return this | ||
this.handlers.set(route, compose(fns)); | ||
return this; | ||
} | ||
otherwise (...fns) { | ||
otherwise(...fns) { | ||
if (fns.length === 0) { | ||
throw new TypeError('At least one otherwise handler must be provided') | ||
throw new TypeError('At least one otherwise handler must be provided'); | ||
} | ||
this.otherwiseHandler = compose(fns) | ||
return this | ||
this.otherwiseHandler = compose(fns); | ||
return this; | ||
} | ||
middleware () { | ||
return lazy((ctx) => { | ||
return Promise.resolve(this.routeFn(ctx)).then((result) => { | ||
middleware() { | ||
return lazy(ctx => { | ||
return Promise.resolve(this.routeFn(ctx)).then(result => { | ||
if (!result || !result.route || !this.handlers.has(result.route)) { | ||
return this.otherwiseHandler | ||
return this.otherwiseHandler; | ||
} | ||
Object.assign(ctx, result.context) | ||
Object.assign(ctx.state, result.state) | ||
return this.handlers.get(result.route) | ||
}) | ||
}) | ||
Object.assign(ctx, result.context); | ||
Object.assign(ctx.state, result.state); | ||
return this.handlers.get(result.route); | ||
}); | ||
}); | ||
} | ||
} | ||
module.exports = Router | ||
module.exports = Router; |
@@ -5,3 +5,3 @@ const debug = require('debug')('telegraf:scenes:context') | ||
const noop = () => Promise.resolve() | ||
const now = () => Math.floor(new Date().getTime() / 1000) | ||
const now = () => Math.floor(Date.now() / 1000) | ||
@@ -8,0 +8,0 @@ class SceneContext { |
@@ -5,30 +5,37 @@ module.exports = function (opts) { | ||
store: new Map(), | ||
getSessionKey: (ctx) => ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`, | ||
...opts | ||
} | ||
getSessionKey: ctx => | ||
ctx.from && ctx.chat && `${ctx.from.id}:${ctx.chat.id}`, | ||
...opts, | ||
}; | ||
const ttlMs = options.ttl && options.ttl * 1000 | ||
const ttlMs = options.ttl && options.ttl * 1000; | ||
return (ctx, next) => { | ||
const key = options.getSessionKey(ctx) | ||
const key = options.getSessionKey(ctx); | ||
if (!key) { | ||
return next(ctx) | ||
return next(ctx); | ||
} | ||
const now = new Date().getTime() | ||
const now = Date.now() | ||
return Promise.resolve(options.store.get(key)) | ||
.then((state) => state || { session: {} }) | ||
.then(state => state || { session: {} }) | ||
.then(({ session, expires }) => { | ||
if (expires && expires < now) { | ||
session = {} | ||
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 | ||
})) | ||
}) | ||
} | ||
} | ||
get: function () { | ||
return session; | ||
}, | ||
set: function (newValue) { | ||
session = { ...newValue }; | ||
}, | ||
}); | ||
return next(ctx).then(() => | ||
options.store.set(key, { | ||
session, | ||
expires: ttlMs ? now + ttlMs : null, | ||
}), | ||
); | ||
}); | ||
}; | ||
}; |
56
stage.js
@@ -1,51 +0,51 @@ | ||
const SceneContext = require('./scenes/context') | ||
const Composer = require('./composer') | ||
const { compose, optional, lazy, safePassThru } = Composer | ||
const SceneContext = require('./scenes/context'); | ||
const Composer = require('./composer'); | ||
const { compose, optional, lazy, safePassThru } = Composer; | ||
class Stage extends Composer { | ||
constructor (scenes = [], options) { | ||
super() | ||
constructor(scenes = [], options) { | ||
super(); | ||
this.options = { | ||
sessionName: 'session', | ||
...options | ||
} | ||
this.scenes = new Map() | ||
scenes.forEach((scene) => this.register(scene)) | ||
...options, | ||
}; | ||
this.scenes = new Map(); | ||
scenes.forEach(scene => this.register(scene)); | ||
} | ||
register (...scenes) { | ||
scenes.forEach((scene) => { | ||
register(...scenes) { | ||
scenes.forEach(scene => { | ||
if (!scene || !scene.id || typeof scene.middleware !== 'function') { | ||
throw new Error('telegraf: Unsupported scene') | ||
throw new Error('telegraf: Unsupported scene'); | ||
} | ||
this.scenes.set(scene.id, scene) | ||
}) | ||
return this | ||
this.scenes.set(scene.id, scene); | ||
}); | ||
return this; | ||
} | ||
middleware () { | ||
middleware() { | ||
const handler = compose([ | ||
(ctx, next) => { | ||
ctx.scene = new SceneContext(ctx, this.scenes, this.options) | ||
return 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) | ||
lazy(ctx => ctx.scene.current || safePassThru()), | ||
]); | ||
return optional(ctx => ctx[this.options.sessionName], handler); | ||
} | ||
static enter (...args) { | ||
return (ctx) => ctx.scene.enter(...args) | ||
static enter(...args) { | ||
return ctx => ctx.scene.enter(...args); | ||
} | ||
static reenter (...args) { | ||
return (ctx) => ctx.scene.reenter(...args) | ||
static reenter(...args) { | ||
return ctx => ctx.scene.reenter(...args); | ||
} | ||
static leave (...args) { | ||
return (ctx) => ctx.scene.leave(...args) | ||
static leave(...args) { | ||
return ctx => ctx.scene.leave(...args); | ||
} | ||
} | ||
module.exports = Stage | ||
module.exports = Stage; |
312
telegraf.js
@@ -1,14 +0,14 @@ | ||
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 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'); | ||
@@ -18,190 +18,216 @@ const DEFAULT_OPTIONS = { | ||
handlerTimeout: 0, | ||
contextType: Context | ||
} | ||
contextType: Context, | ||
}; | ||
const noop = () => { } | ||
const noop = () => {}; | ||
class Telegraf extends Composer { | ||
constructor (token, options) { | ||
super() | ||
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 = {} | ||
...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 | ||
} | ||
started: false, | ||
}; | ||
} | ||
set token (token) { | ||
this.telegram = new Telegram(token, this.telegram | ||
? this.telegram.options | ||
: this.options.telegram | ||
) | ||
set token(token) { | ||
this.telegram = new Telegram( | ||
token, | ||
this.telegram ? this.telegram.options : this.options.telegram, | ||
); | ||
} | ||
get token () { | ||
return this.telegram.token | ||
get token() { | ||
return this.telegram.token; | ||
} | ||
set webhookReply (webhookReply) { | ||
this.telegram.webhookReply = webhookReply | ||
set webhookReply(webhookReply) { | ||
this.telegram.webhookReply = webhookReply; | ||
} | ||
get webhookReply () { | ||
return this.telegram.webhookReply | ||
}/* eslint brace-style: 0 */ | ||
get webhookReply() { | ||
return this.telegram.webhookReply; | ||
} | ||
catch (handler) { | ||
this.handleError = handler | ||
return this | ||
catch(handler) { | ||
this.handleError = handler; | ||
return this; | ||
} | ||
webhookCallback (path = '/') { | ||
return generateCallback(path, (update, res) => this.handleUpdate(update, res), debug) | ||
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 | ||
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 | ||
? Array.isArray(allowedUpdates) | ||
? allowedUpdates | ||
: [`${allowedUpdates}`] | ||
: null; | ||
this.polling.stopCallback = stopCallback; | ||
if (!this.polling.started) { | ||
this.polling.started = true | ||
this.fetchUpdates() | ||
this.polling.started = true; | ||
this.fetchUpdates(); | ||
} | ||
return this | ||
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 | ||
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) | ||
: require('http').createServer(callback); | ||
this.webhookServer.listen(port, host, () => { | ||
debug('Webhook listening on port: %s', port) | ||
}) | ||
return this | ||
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 | ||
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')) | ||
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') | ||
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 || '' | ||
let domain = config.webhook.domain || ''; | ||
if (domain.startsWith('https://') || domain.startsWith('http://')) { | ||
domain = new URL(domain).host | ||
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) | ||
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 | ||
debug('Bot started with webhook'); | ||
return; | ||
} | ||
return this.telegram | ||
.setWebhook(`https://${domain}${hookPath}`) | ||
.then(() => debug(`Bot started with webhook @ https://${domain}`)) | ||
.then(() => debug(`Bot started with webhook @ https://${domain}`)); | ||
}) | ||
.catch((err) => { | ||
console.error('Launch failed') | ||
console.error(err.stack || err.toString()) | ||
}) | ||
.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() | ||
stop(cb = noop) { | ||
debug('Stopping bot...'); | ||
return new Promise(resolve => { | ||
const done = () => resolve() & cb(); | ||
if (this.webhookServer) { | ||
return this.webhookServer.close(done) | ||
return this.webhookServer.close(done); | ||
} else if (!this.polling.started) { | ||
return done() | ||
return done(); | ||
} | ||
this.polling.stopCallback = done | ||
this.polling.started = false | ||
}) | ||
this.polling.stopCallback = done; | ||
this.polling.started = false; | ||
}); | ||
} | ||
handleUpdates (updates) { | ||
handleUpdates(updates) { | ||
if (!Array.isArray(updates)) { | ||
return Promise.reject(new Error('Updates must be an array')) | ||
return Promise.reject(new Error('Updates must be an array')); | ||
} | ||
const processAll = Promise.all(updates.map((update) => this.handleUpdate(update))) | ||
const processAll = Promise.all( | ||
updates.map(update => this.handleUpdate(update)), | ||
); | ||
if (this.options.handlerTimeout === 0) { | ||
return processAll | ||
return processAll; | ||
} | ||
return Promise.race([ | ||
processAll, | ||
new Promise((resolve) => setTimeout(resolve, this.options.handlerTimeout)) | ||
]) | ||
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)) | ||
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 () { | ||
fetchUpdates() { | ||
if (!this.polling.started) { | ||
this.polling.stopCallback && this.polling.stopCallback() | ||
return | ||
this.polling.stopCallback && this.polling.stopCallback(); | ||
return; | ||
} | ||
const { timeout, limit, offset, allowedUpdates } = this.polling | ||
this.telegram.getUpdates(timeout, limit, offset, allowedUpdates) | ||
.catch((err) => { | ||
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 | ||
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, [])) | ||
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) | ||
: [] | ||
.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 [] | ||
.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) => { | ||
.then(updates => { | ||
if (updates.length > 0) { | ||
this.polling.offset = updates[updates.length - 1].update_id + 1 | ||
this.polling.offset = updates[updates.length - 1].update_id + 1; | ||
} | ||
this.fetchUpdates() | ||
}) | ||
this.fetchUpdates(); | ||
}); | ||
} | ||
@@ -213,19 +239,11 @@ } | ||
Composer, | ||
default: Telegraf, | ||
Extra, | ||
Markup, | ||
Router, | ||
Telegraf, | ||
Telegram, | ||
session | ||
}) | ||
module.exports.default = Object.assign(Telegraf, { | ||
Context, | ||
Composer, | ||
Extra, | ||
Markup, | ||
Router, | ||
Telegram, | ||
Stage, | ||
BaseScene, | ||
session | ||
}) | ||
session, | ||
}); |
452
telegram.js
@@ -1,37 +0,40 @@ | ||
const replicators = require('./core/replicators') | ||
const ApiClient = require('./core/network/client') | ||
const replicators = require('./core/replicators'); | ||
const ApiClient = require('./core/network/client'); | ||
class Telegram extends ApiClient { | ||
getMe () { | ||
return this.callApi('getMe') | ||
getMe() { | ||
return this.callApi('getMe'); | ||
} | ||
getFile (fileId) { | ||
return this.callApi('getFile', { file_id: fileId }) | ||
getFile(fileId) { | ||
return this.callApi('getFile', { file_id: fileId }); | ||
} | ||
getFileLink (fileId) { | ||
getFileLink(fileId) { | ||
return Promise.resolve(fileId) | ||
.then((fileId) => { | ||
.then(fileId => { | ||
if (fileId && fileId.file_path) { | ||
return fileId | ||
return fileId; | ||
} | ||
const id = fileId && fileId.file_id ? fileId.file_id : fileId | ||
return this.getFile(id) | ||
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}`) | ||
.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}` | ||
getUpdates(timeout, limit, offset, allowedUpdates) { | ||
const url = `getUpdates?offset=${offset}&limit=${limit}&timeout=${timeout}`; | ||
return this.callApi(url, { | ||
allowed_updates: allowedUpdates | ||
}) | ||
allowed_updates: allowedUpdates, | ||
}); | ||
} | ||
getWebhookInfo () { | ||
return this.callApi('getWebhookInfo') | ||
getWebhookInfo() { | ||
return this.callApi('getWebhookInfo'); | ||
} | ||
getGameHighScores (userId, inlineMessageId, chatId, messageId) { | ||
getGameHighScores(userId, inlineMessageId, chatId, messageId) { | ||
return this.callApi('getGameHighScores', { | ||
@@ -41,7 +44,15 @@ user_id: userId, | ||
chat_id: chatId, | ||
message_id: messageId | ||
}) | ||
message_id: messageId, | ||
}); | ||
} | ||
setGameScore (userId, score, inlineMessageId, chatId, messageId, editMessage = true, force) { | ||
setGameScore( | ||
userId, | ||
score, | ||
inlineMessageId, | ||
chatId, | ||
messageId, | ||
editMessage = true, | ||
force, | ||
) { | ||
return this.callApi('setGameScore', { | ||
@@ -54,7 +65,7 @@ force, | ||
message_id: messageId, | ||
disable_edit_message: !editMessage | ||
}) | ||
disable_edit_message: !editMessage, | ||
}); | ||
} | ||
setWebhook (url, certificate, maxConnections, allowedUpdates) { | ||
setWebhook(url, certificate, maxConnections, allowedUpdates) { | ||
return this.callApi('setWebhook', { | ||
@@ -64,15 +75,15 @@ url, | ||
max_connections: maxConnections, | ||
allowed_updates: allowedUpdates | ||
}) | ||
allowed_updates: allowedUpdates, | ||
}); | ||
} | ||
deleteWebhook () { | ||
return this.callApi('deleteWebhook') | ||
deleteWebhook() { | ||
return this.callApi('deleteWebhook'); | ||
} | ||
sendMessage (chatId, text, extra) { | ||
return this.callApi('sendMessage', { chat_id: chatId, text, ...extra }) | ||
sendMessage(chatId, text, extra) { | ||
return this.callApi('sendMessage', { chat_id: chatId, text, ...extra }); | ||
} | ||
forwardMessage (chatId, fromChatId, messageId, extra) { | ||
forwardMessage(chatId, fromChatId, messageId, extra) { | ||
return this.callApi('forwardMessage', { | ||
@@ -82,19 +93,28 @@ chat_id: chatId, | ||
message_id: messageId, | ||
...extra | ||
}) | ||
...extra, | ||
}); | ||
} | ||
sendChatAction (chatId, action) { | ||
return this.callApi('sendChatAction', { chat_id: chatId, action }) | ||
sendChatAction(chatId, action) { | ||
return this.callApi('sendChatAction', { chat_id: chatId, action }); | ||
} | ||
getUserProfilePhotos (userId, offset, limit) { | ||
return this.callApi('getUserProfilePhotos', { user_id: userId, offset, limit }) | ||
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 }) | ||
sendLocation(chatId, latitude, longitude, extra) { | ||
return this.callApi('sendLocation', { | ||
chat_id: chatId, | ||
latitude, | ||
longitude, | ||
...extra, | ||
}); | ||
} | ||
sendVenue (chatId, latitude, longitude, title, address, extra) { | ||
sendVenue(chatId, latitude, longitude, title, address, extra) { | ||
return this.callApi('sendVenue', { | ||
@@ -106,18 +126,31 @@ latitude, | ||
chat_id: chatId, | ||
...extra | ||
}) | ||
...extra, | ||
}); | ||
} | ||
sendInvoice (chatId, invoice, extra) { | ||
return this.callApi('sendInvoice', { chat_id: chatId, ...invoice, ...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 }) | ||
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 }) | ||
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) { | ||
@@ -127,123 +160,178 @@ return this.callApi('sendDocument', { chat_id: chatId, document, ...extra }) | ||
sendAudio (chatId, audio, extra) { | ||
return this.callApi('sendAudio', { chat_id: chatId, audio, ...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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
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 }) | ||
stopPoll(chatId, messageId, extra) { | ||
return this.callApi('stopPoll', { | ||
chat_id: chatId, | ||
message_id: messageId, | ||
...extra, | ||
}); | ||
} | ||
getChat (chatId) { | ||
return this.callApi('getChat', { chat_id: chatId }) | ||
getChat(chatId) { | ||
return this.callApi('getChat', { chat_id: chatId }); | ||
} | ||
getChatAdministrators (chatId) { | ||
return this.callApi('getChatAdministrators', { 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 }) | ||
getChatMember(chatId, userId) { | ||
return this.callApi('getChatMember', { chat_id: chatId, user_id: userId }); | ||
} | ||
getChatMembersCount (chatId) { | ||
return this.callApi('getChatMembersCount', { chat_id: chatId }) | ||
getChatMembersCount(chatId) { | ||
return this.callApi('getChatMembersCount', { chat_id: chatId }); | ||
} | ||
answerInlineQuery (inlineQueryId, results, extra) { | ||
return this.callApi('answerInlineQuery', { inline_query_id: inlineQueryId, results, ...extra }) | ||
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 }) | ||
setChatPermissions(chatId, permissions) { | ||
return this.callApi('setChatPermissions', { chat_id: chatId, permissions }); | ||
} | ||
kickChatMember (chatId, userId, untilDate) { | ||
return this.callApi('kickChatMember', { chat_id: chatId, user_id: userId, until_date: untilDate }) | ||
kickChatMember(chatId, userId, untilDate) { | ||
return this.callApi('kickChatMember', { | ||
chat_id: chatId, | ||
user_id: userId, | ||
until_date: untilDate, | ||
}); | ||
} | ||
promoteChatMember (chatId, userId, extra) { | ||
return this.callApi('promoteChatMember', { chat_id: chatId, user_id: userId, ...extra }) | ||
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 }) | ||
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 }) | ||
setChatAdministratorCustomTitle(chatId, userId, title) { | ||
return this.callApi('setChatAdministratorCustomTitle', { | ||
chat_id: chatId, | ||
user_id: userId, | ||
custom_title: title, | ||
}); | ||
} | ||
exportChatInviteLink (chatId) { | ||
return this.callApi('exportChatInviteLink', { chat_id: chatId }) | ||
exportChatInviteLink(chatId) { | ||
return this.callApi('exportChatInviteLink', { chat_id: chatId }); | ||
} | ||
setChatPhoto (chatId, photo) { | ||
return this.callApi('setChatPhoto', { chat_id: chatId, photo }) | ||
setChatPhoto(chatId, photo) { | ||
return this.callApi('setChatPhoto', { chat_id: chatId, photo }); | ||
} | ||
deleteChatPhoto (chatId) { | ||
return this.callApi('deleteChatPhoto', { chat_id: chatId }) | ||
deleteChatPhoto(chatId) { | ||
return this.callApi('deleteChatPhoto', { chat_id: chatId }); | ||
} | ||
setChatTitle (chatId, title) { | ||
return this.callApi('setChatTitle', { chat_id: chatId, title }) | ||
setChatTitle(chatId, title) { | ||
return this.callApi('setChatTitle', { chat_id: chatId, title }); | ||
} | ||
setChatDescription (chatId, description) { | ||
return this.callApi('setChatDescription', { chat_id: chatId, description }) | ||
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 }) | ||
pinChatMessage(chatId, messageId, extra) { | ||
return this.callApi('pinChatMessage', { | ||
chat_id: chatId, | ||
message_id: messageId, | ||
...extra, | ||
}); | ||
} | ||
unpinChatMessage (chatId) { | ||
return this.callApi('unpinChatMessage', { chat_id: chatId }) | ||
unpinChatMessage(chatId) { | ||
return this.callApi('unpinChatMessage', { chat_id: chatId }); | ||
} | ||
leaveChat (chatId) { | ||
return this.callApi('leaveChat', { chat_id: chatId }) | ||
leaveChat(chatId) { | ||
return this.callApi('leaveChat', { chat_id: chatId }); | ||
} | ||
unbanChatMember (chatId, userId) { | ||
return this.callApi('unbanChatMember', { chat_id: chatId, user_id: userId }) | ||
unbanChatMember(chatId, userId) { | ||
return this.callApi('unbanChatMember', { | ||
chat_id: chatId, | ||
user_id: userId, | ||
}); | ||
} | ||
answerCbQuery (callbackQueryId, text, showAlert, extra) { | ||
answerCbQuery(callbackQueryId, text, showAlert, extra) { | ||
return this.callApi('answerCallbackQuery', { | ||
@@ -253,14 +341,14 @@ text, | ||
callback_query_id: callbackQueryId, | ||
...extra | ||
}) | ||
...extra, | ||
}); | ||
} | ||
answerGameQuery (callbackQueryId, url) { | ||
answerGameQuery(callbackQueryId, url) { | ||
return this.callApi('answerCallbackQuery', { | ||
url, | ||
callback_query_id: callbackQueryId | ||
}) | ||
callback_query_id: callbackQueryId, | ||
}); | ||
} | ||
answerShippingQuery (shippingQueryId, ok, shippingOptions, errorMessage) { | ||
answerShippingQuery(shippingQueryId, ok, shippingOptions, errorMessage) { | ||
return this.callApi('answerShippingQuery', { | ||
@@ -270,15 +358,15 @@ ok, | ||
shipping_options: shippingOptions, | ||
error_message: errorMessage | ||
}) | ||
error_message: errorMessage, | ||
}); | ||
} | ||
answerPreCheckoutQuery (preCheckoutQueryId, ok, errorMessage) { | ||
answerPreCheckoutQuery(preCheckoutQueryId, ok, errorMessage) { | ||
return this.callApi('answerPreCheckoutQuery', { | ||
ok, | ||
pre_checkout_query_id: preCheckoutQueryId, | ||
error_message: errorMessage | ||
}) | ||
error_message: errorMessage, | ||
}); | ||
} | ||
editMessageText (chatId, messageId, inlineMessageId, text, extra) { | ||
editMessageText(chatId, messageId, inlineMessageId, text, extra) { | ||
return this.callApi('editMessageText', { | ||
@@ -289,7 +377,7 @@ text, | ||
inline_message_id: inlineMessageId, | ||
...extra | ||
}) | ||
...extra, | ||
}); | ||
} | ||
editMessageCaption (chatId, messageId, inlineMessageId, caption, extra = {}) { | ||
editMessageCaption(chatId, messageId, inlineMessageId, caption, extra = {}) { | ||
return this.callApi('editMessageCaption', { | ||
@@ -301,7 +389,8 @@ caption, | ||
parse_mode: extra.parse_mode, | ||
reply_markup: extra.parse_mode || extra.reply_markup ? extra.reply_markup : extra | ||
}) | ||
reply_markup: | ||
extra.parse_mode || extra.reply_markup ? extra.reply_markup : extra, | ||
}); | ||
} | ||
editMessageMedia (chatId, messageId, inlineMessageId, media, extra = {}) { | ||
editMessageMedia(chatId, messageId, inlineMessageId, media, extra = {}) { | ||
return this.callApi('editMessageMedia', { | ||
@@ -312,7 +401,7 @@ chat_id: chatId, | ||
media: { ...media, parse_mode: extra.parse_mode }, | ||
reply_markup: extra.reply_markup ? extra.reply_markup : extra | ||
}) | ||
reply_markup: extra.reply_markup ? extra.reply_markup : extra, | ||
}); | ||
} | ||
editMessageReplyMarkup (chatId, messageId, inlineMessageId, markup) { | ||
editMessageReplyMarkup(chatId, messageId, inlineMessageId, markup) { | ||
return this.callApi('editMessageReplyMarkup', { | ||
@@ -322,7 +411,14 @@ chat_id: chatId, | ||
inline_message_id: inlineMessageId, | ||
reply_markup: markup | ||
}) | ||
reply_markup: markup, | ||
}); | ||
} | ||
editMessageLiveLocation (latitude, longitude, chatId, messageId, inlineMessageId, markup) { | ||
editMessageLiveLocation( | ||
latitude, | ||
longitude, | ||
chatId, | ||
messageId, | ||
inlineMessageId, | ||
markup, | ||
) { | ||
return this.callApi('editMessageLiveLocation', { | ||
@@ -334,7 +430,7 @@ latitude, | ||
inline_message_id: inlineMessageId, | ||
reply_markup: markup | ||
}) | ||
reply_markup: markup, | ||
}); | ||
} | ||
stopMessageLiveLocation (chatId, messageId, inlineMessageId, markup) { | ||
stopMessageLiveLocation(chatId, messageId, inlineMessageId, markup) { | ||
return this.callApi('stopMessageLiveLocation', { | ||
@@ -344,36 +440,36 @@ chat_id: chatId, | ||
inline_message_id: inlineMessageId, | ||
reply_markup: markup | ||
}) | ||
reply_markup: markup, | ||
}); | ||
} | ||
deleteMessage (chatId, messageId) { | ||
deleteMessage(chatId, messageId) { | ||
return this.callApi('deleteMessage', { | ||
chat_id: chatId, | ||
message_id: messageId | ||
}) | ||
message_id: messageId, | ||
}); | ||
} | ||
setChatStickerSet (chatId, setName) { | ||
setChatStickerSet(chatId, setName) { | ||
return this.callApi('setChatStickerSet', { | ||
chat_id: chatId, | ||
sticker_set_name: setName | ||
}) | ||
sticker_set_name: setName, | ||
}); | ||
} | ||
deleteChatStickerSet (chatId) { | ||
return this.callApi('deleteChatStickerSet', { chat_id: chatId }) | ||
deleteChatStickerSet(chatId) { | ||
return this.callApi('deleteChatStickerSet', { chat_id: chatId }); | ||
} | ||
getStickerSet (name) { | ||
return this.callApi('getStickerSet', { name }) | ||
getStickerSet(name) { | ||
return this.callApi('getStickerSet', { name }); | ||
} | ||
uploadStickerFile (ownerId, stickerFile) { | ||
uploadStickerFile(ownerId, stickerFile) { | ||
return this.callApi('uploadStickerFile', { | ||
user_id: ownerId, | ||
png_sticker: stickerFile | ||
}) | ||
png_sticker: stickerFile, | ||
}); | ||
} | ||
createNewStickerSet (ownerId, name, title, stickerData) { | ||
createNewStickerSet(ownerId, name, title, stickerData) { | ||
return this.callApi('createNewStickerSet', { | ||
@@ -383,7 +479,7 @@ name, | ||
user_id: ownerId, | ||
...stickerData | ||
}) | ||
...stickerData, | ||
}); | ||
} | ||
addStickerToSet (ownerId, name, stickerData, isMasks) { | ||
addStickerToSet(ownerId, name, stickerData, isMasks) { | ||
return this.callApi('addStickerToSet', { | ||
@@ -393,13 +489,17 @@ name, | ||
is_masks: isMasks, | ||
...stickerData | ||
}) | ||
...stickerData, | ||
}); | ||
} | ||
setStickerPositionInSet (sticker, position) { | ||
setStickerPositionInSet(sticker, position) { | ||
return this.callApi('setStickerPositionInSet', { | ||
sticker, | ||
position | ||
}) | ||
position, | ||
}); | ||
} | ||
setStickerSetThumb (name, userId, thumb) { | ||
return this.callApi('setStickerSetThumb', { name, user_id: userId, thumb }) | ||
} | ||
deleteStickerFromSet (sticker) { | ||
@@ -409,16 +509,26 @@ return this.callApi('deleteStickerFromSet', { sticker }) | ||
getMyCommands () { | ||
return this.callApi('getMyCommands') | ||
} | ||
setMyCommands (commands) { | ||
return this.callApi('setMyCommands', { commands }) | ||
} | ||
setPassportDataErrors (userId, errors) { | ||
return this.callApi('setPassportDataErrors', { | ||
user_id: userId, | ||
errors: errors | ||
}) | ||
errors: errors, | ||
}); | ||
} | ||
sendCopy (chatId, message, extra) { | ||
sendCopy(chatId, message, extra) { | ||
if (!message) { | ||
throw new Error('Message is required') | ||
throw new Error('Message is required'); | ||
} | ||
const type = Object.keys(replicators.copyMethods).find((type) => message[type]) | ||
const type = Object.keys(replicators.copyMethods).find( | ||
type => message[type], | ||
); | ||
if (!type) { | ||
throw new Error('Unsupported message type') | ||
throw new Error('Unsupported message type'); | ||
} | ||
@@ -428,8 +538,8 @@ const opts = { | ||
...replicators[type](message), | ||
...extra | ||
} | ||
return this.callApi(replicators.copyMethods[type], opts) | ||
...extra, | ||
}; | ||
return this.callApi(replicators.copyMethods[type], opts); | ||
} | ||
} | ||
module.exports = Telegram | ||
module.exports = Telegram; |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
267286
35
8177
65
9
+ Addeddebug@4.0.1(transitive)
+ Addedminimist@1.2.0(transitive)
+ Addedmodule-alias@2.2.2(transitive)
+ Addedms@2.1.3(transitive)
+ Addednode-fetch@2.2.0(transitive)
+ Addedsandwich-stream@2.0.1(transitive)
- Removeddebug@4.3.4(transitive)
- Removedminimist@1.2.8(transitive)
- Removedmodule-alias@2.2.3(transitive)
- Removedms@2.1.2(transitive)
- Removednode-fetch@2.7.0(transitive)
- Removedsandwich-stream@2.0.2(transitive)
- Removedtr46@0.0.3(transitive)
- Removedwebidl-conversions@3.0.1(transitive)
- Removedwhatwg-url@5.0.0(transitive)
Updateddebug@4.0.1
Updatedminimist@1.2.0
Updatedmodule-alias@2.2.2
Updatednode-fetch@2.2.0
Updatedsandwich-stream@2.0.1