New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More ā†’
Socket
Sign inDemoInstall
Socket

telegraf

Package Overview
Dependencies
Maintainers
3
Versions
241
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

telegraf - npm Package Compare versions

Comparing version 4.12.3-canary.1 to 4.13.0

lib/core/helpers/args.js

84

lib/composer.js

@@ -10,2 +10,3 @@ "use strict";

const filters_1 = require("./filters");
const args_1 = require("./core/helpers/args");
function always(x) {

@@ -113,9 +114,3 @@ return () => x;

const handler = Composer.compose(fns);
return this.command('start', (ctx, next) => {
// First entity is the /start bot_command itself
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const entity = ctx.message.entities[0];
const startPayload = ctx.message.text.slice(entity.length + 1);
return handler(Object.assign(ctx, { startPayload }), next);
});
return this.command('start', (ctx, next) => handler(Object.assign(ctx, { startPayload: ctx.payload }), next));
}

@@ -263,3 +258,3 @@ /**

if (typeof predicate !== 'function') {
const entityTypes = normalizeTextArguments(predicate);
const entityTypes = normaliseTextArguments(predicate);
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns);

@@ -278,4 +273,5 @@ }

return entities.some((entity) => predicate(entity, text.substring(entity.offset, entity.offset + entity.length), ctx));
// @ts-expect-error see explanation above
}, ...fns);
},
// @ts-expect-error see explanation above
...fns);
}

@@ -291,3 +287,3 @@ static entityText(entityType, predicate, ...fns) {

}
const triggers = normalizeTriggers(predicate);
const triggers = normaliseTriggers(predicate);
return Composer.entity(({ type }, value, ctx) => {

@@ -304,4 +300,5 @@ if (type !== entityType) {

return false;
// @ts-expect-error see explanation above
}, ...fns);
},
// @ts-expect-error see explanation above
...fns);
}

@@ -324,9 +321,9 @@ static email(email, ...fns) {

static mention(mention, ...fns) {
return Composer.entityText('mention', normalizeTextArguments(mention, '@'), ...fns);
return Composer.entityText('mention', normaliseTextArguments(mention, '@'), ...fns);
}
static hashtag(hashtag, ...fns) {
return Composer.entityText('hashtag', normalizeTextArguments(hashtag, '#'), ...fns);
return Composer.entityText('hashtag', normaliseTextArguments(hashtag, '#'), ...fns);
}
static cashtag(cashtag, ...fns) {
return Composer.entityText('cashtag', normalizeTextArguments(cashtag, '$'), ...fns);
return Composer.entityText('cashtag', normaliseTextArguments(cashtag, '$'), ...fns);
}

@@ -344,8 +341,5 @@ static spoiler(text, ...fns) {

for (const trigger of triggers) {
// @ts-expect-error Trust me, TS!
const match = trigger(text, ctx);
if (match) {
// @ts-expect-error define so far unknown property `match`
if (match)
return handler(Object.assign(ctx, { match }), next);
}
}

@@ -359,3 +353,3 @@ return next();

static hears(triggers, ...fns) {
return Composer.on('text', Composer.match(normalizeTriggers(triggers), ...fns));
return Composer.on('text', Composer.match(normaliseTriggers(triggers), ...fns));
}

@@ -369,12 +363,15 @@ /**

return Composer.entity('bot_command', command);
const triggers = normalizeTriggers(command);
const triggers = normaliseTriggers(command);
const filter = (0, filters_1.message)('text');
const handler = Composer.compose(fns);
return Composer.on(filter, (ctx, next) => {
var _a;
const first = (_a = ctx.message.entities) === null || _a === void 0 ? void 0 : _a[0];
if ((first === null || first === void 0 ? void 0 : first.type) !== 'bot_command')
const { entities } = ctx.message;
const cmdEntity = entities === null || entities === void 0 ? void 0 : entities[0];
if ((cmdEntity === null || cmdEntity === void 0 ? void 0 : cmdEntity.type) !== 'bot_command')
return next();
if (first.offset > 0)
if (cmdEntity.offset > 0)
return next();
const [cmdPart, to] = ctx.message.text.slice(0, first.length).split('@');
const len = cmdEntity.length;
const text = ctx.message.text;
const [cmdPart, to] = text.slice(0, len).split('@');
if (!cmdPart)

@@ -385,6 +382,25 @@ return next();

return next();
const cmd = cmdPart.slice(1);
const command = cmdPart.slice(1);
for (const trigger of triggers)
if (trigger(cmd, ctx))
return Composer.compose(fns)(ctx, next);
if (trigger(command, ctx)) {
const payloadOffset = len + 1;
const payload = text.slice(payloadOffset);
const c = Object.assign(ctx, { command, payload, args: [] });
let _args = undefined;
// using defineProperty only to make parsing lazy on access
Object.defineProperty(c, 'args', {
enumerable: true,
configurable: true,
get() {
if (_args != null)
return _args;
// once parsed, cache and don't parse again on every access
return (_args = (0, args_1.argsParser)(payload, entities, payloadOffset));
},
set(args) {
_args = args;
},
});
return handler(c, next);
}
return next();

@@ -397,3 +413,3 @@ });

static action(triggers, ...fns) {
return Composer.on('callback_query', Composer.match(normalizeTriggers(triggers), ...fns));
return Composer.on('callback_query', Composer.match(normaliseTriggers(triggers), ...fns));
}

@@ -404,3 +420,3 @@ /**

static inlineQuery(triggers, ...fns) {
return Composer.on('inline_query', Composer.match(normalizeTriggers(triggers), ...fns));
return Composer.on('inline_query', Composer.match(normaliseTriggers(triggers), ...fns));
}

@@ -515,3 +531,3 @@ /**

}
function normalizeTriggers(triggers) {
function normaliseTriggers(triggers) {
if (!Array.isArray(triggers))

@@ -556,3 +572,3 @@ triggers = [triggers];

}
function normalizeTextArguments(argument, prefix = '') {
function normaliseTextArguments(argument, prefix = '') {
const args = Array.isArray(argument) ? argument : [argument];

@@ -559,0 +575,0 @@ // prettier-ignore

@@ -96,3 +96,2 @@ "use strict";

return undefined;
// @ts-expect-error Bug in TS 4.9+, fix will land in 5.0 https://github.com/microsoft/TypeScript/pull/51502
if (!('passport_data' in this.message))

@@ -886,2 +885,15 @@ return undefined;

/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator
* right in the supergroup.
*
* @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
*
* @see https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
*/
unpinAllGeneralForumTopicMessages() {
this.assert(this.chat, 'unpinAllGeneralForumTopicMessages');
return this.telegram.unpinAllGeneralForumTopicMessages(this.chat.id);
}
/**
* @deprecated use {@link Telegram.setStickerPositionInSet}

@@ -894,8 +906,29 @@ * @see https://core.telegram.org/bots/api#setstickerpositioninset

/**
* @deprecated use {@link Telegram.setStickerSetThumb}
* @see https://core.telegram.org/bots/api#setstickersetthumb
* @deprecated use {@link Telegram.setStickerSetThumbnail}
* @see https://core.telegram.org/bots/api#setstickersetthumbnail
*/
setStickerSetThumb(...args) {
return this.telegram.setStickerSetThumb(...args);
return this.telegram.setStickerSetThumbnail(...args);
}
setStickerSetThumbnail(...args) {
return this.telegram.setStickerSetThumbnail(...args);
}
setStickerMaskPosition(...args) {
return this.telegram.setStickerMaskPosition(...args);
}
setStickerKeywords(...args) {
return this.telegram.setStickerKeywords(...args);
}
setStickerEmojiList(...args) {
return this.telegram.setStickerEmojiList(...args);
}
deleteStickerSet(...args) {
return this.telegram.deleteStickerSet(...args);
}
setStickerSetTitle(...args) {
return this.telegram.setStickerSetTitle(...args);
}
setCustomEmojiStickerSetThumbnail(...args) {
return this.telegram.setCustomEmojiStickerSetThumbnail(...args);
}
/**

@@ -902,0 +935,0 @@ * @deprecated use {@link Telegram.deleteStickerFromSet}

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.linkOrMention = exports._fmt = exports.replace = exports.join = exports.FmtString = void 0;
const util_1 = require("../../util");
exports.linkOrMention = exports._fmt = exports.join = exports.FmtString = void 0;
const util_1 = require("./util");
class FmtString {

@@ -66,34 +66,2 @@ constructor(text, entities) {

exports.join = join;
const replace = (source, search, value) => {
var _a;
const v = FmtString.normalise(value);
let entities = undefined;
if (typeof search === 'string') {
const offset = source.indexOf(search);
const length = search.length;
source = source.slice(0, offset) + v.text + source.slice(offset + length);
entities = (_a = v.entities) === null || _a === void 0 ? void 0 : _a.map((e) => ({ ...e, offset: e.offset + offset }));
}
else {
let index = 0; // context position in source string
let acc = ''; // incremental return value
let correction = 0;
let regexArray;
while ((regexArray = search.exec(source))) {
const offset = regexArray.index;
const length = regexArray[0].length;
acc += source.slice(index, offset) + v.text;
if (v.entities && v.entities.length)
(entities !== null && entities !== void 0 ? entities : (entities = [])).push(...v.entities.map((e) => ({
...e,
offset: e.offset + offset + correction,
})));
index = offset + length;
correction += v.text.length - length;
}
source = acc + source.slice(index);
}
return new FmtString(source, entities);
};
exports.replace = replace;
function _fmt(kind, opts) {

@@ -100,0 +68,0 @@ return function fmt(parts, ...items) {

@@ -280,2 +280,3 @@ "use strict";

config.agent = options.agent;
// @ts-expect-error AbortSignal shim is missing some props from Request.AbortSignal
config.signal = signal;

@@ -282,0 +283,0 @@ config.timeout = 500000; // ms

@@ -18,10 +18,11 @@ "use strict";

// internal type provisions
__exportStar(require("typegram/api"), exports);
__exportStar(require("typegram/markup"), exports);
__exportStar(require("typegram/menu-button"), exports);
__exportStar(require("typegram/inline"), exports);
__exportStar(require("typegram/manage"), exports);
__exportStar(require("typegram/message"), exports);
__exportStar(require("typegram/passport"), exports);
__exportStar(require("typegram/payment"), exports);
__exportStar(require("typegram/update"), exports);
__exportStar(require("@telegraf/types/api"), exports);
__exportStar(require("@telegraf/types/inline"), exports);
__exportStar(require("@telegraf/types/manage"), exports);
__exportStar(require("@telegraf/types/markup"), exports);
__exportStar(require("@telegraf/types/message"), exports);
__exportStar(require("@telegraf/types/methods"), exports);
__exportStar(require("@telegraf/types/passport"), exports);
__exportStar(require("@telegraf/types/payment"), exports);
__exportStar(require("@telegraf/types/settings"), exports);
__exportStar(require("@telegraf/types/update"), exports);
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.replace = exports.join = exports.FmtString = exports.mention = exports.link = exports.pre = exports.code = exports.underline = exports.strikethrough = exports.spoiler = exports.italic = exports.bold = exports.fmt = void 0;
exports.join = exports.mention = exports.link = exports.pre = exports.code = exports.underline = exports.strikethrough = exports.spoiler = exports.italic = exports.bold = exports.fmt = exports.FmtString = void 0;
const formatting_1 = require("./core/helpers/formatting");
Object.defineProperty(exports, "FmtString", { enumerable: true, get: function () { return formatting_1.FmtString; } });
exports.fmt = (0, formatting_1._fmt)();
exports.bold = (0, formatting_1._fmt)('bold');
exports.italic = (0, formatting_1._fmt)('italic');
exports.spoiler = (0, formatting_1._fmt)('spoiler');
exports.strikethrough = (0, formatting_1._fmt)('strikethrough');
exports.underline = (0, formatting_1._fmt)('underline');
exports.code = (0, formatting_1._fmt)('code');
Object.defineProperty(exports, "join", { enumerable: true, get: function () { return formatting_1.join; } });
const fmt = (0, formatting_1._fmt)();
exports.fmt = fmt;
const bold = (0, formatting_1._fmt)('bold');
exports.bold = bold;
const italic = (0, formatting_1._fmt)('italic');
exports.italic = italic;
const spoiler = (0, formatting_1._fmt)('spoiler');
exports.spoiler = spoiler;
const strikethrough = (0, formatting_1._fmt)('strikethrough');
exports.strikethrough = strikethrough;
const underline = (0, formatting_1._fmt)('underline');
exports.underline = underline;
const code = (0, formatting_1._fmt)('code');
exports.code = code;
const pre = (language) => (0, formatting_1._fmt)('pre', { language });

@@ -18,7 +26,4 @@ exports.pre = pre;

const mention = (name, user) => typeof user === 'number'
? (0, exports.link)(name, 'tg://user?id=' + user)
? link(name, 'tg://user?id=' + user)
: (0, formatting_1.linkOrMention)(name, { type: 'text_mention', user });
exports.mention = mention;
var formatting_2 = require("./core/helpers/formatting");
Object.defineProperty(exports, "join", { enumerable: true, get: function () { return formatting_2.join; } });
Object.defineProperty(exports, "replace", { enumerable: true, get: function () { return formatting_2.replace; } });

@@ -15,5 +15,5 @@ "use strict";

*
* > āš ļø Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
* > āš ļø Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
* >
* > If you want to store data across restarts, or share it among workers, you should use
* > If you want to persist data across process restarts, or share it among multiple instances, you should use
* [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.

@@ -26,4 +26,4 @@ *

var _a, _b, _c;
const getSessionKey = (_a = options === null || options === void 0 ? void 0 : options.getSessionKey) !== null && _a !== void 0 ? _a : defaultGetSessionKey;
const prop = (_b = options === null || options === void 0 ? void 0 : options.property) !== null && _b !== void 0 ? _b : 'session';
const prop = (_a = options === null || options === void 0 ? void 0 : options.property) !== null && _a !== void 0 ? _a : 'session';
const getSessionKey = (_b = options === null || options === void 0 ? void 0 : options.getSessionKey) !== null && _b !== void 0 ? _b : defaultGetSessionKey;
const store = (_c = options === null || options === void 0 ? void 0 : options.store) !== null && _c !== void 0 ? _c : new MemorySessionStore();

@@ -45,7 +45,4 @@ // caches value from store in-memory while simultaneous updates share it

if (!key) {
Object.defineProperty(ctx, prop, {
get() {
undefined;
},
});
// Leaving this here could be useful to check for `prop in ctx` in future middleware
ctx[prop] = undefined;
return await next();

@@ -115,7 +112,7 @@ }

if (ctx[prop] == null) {
debug(`(${updId}) ctx.session missing, removing from store`);
debug(`(${updId}) ctx.${prop} missing, removing from store`);
await store.delete(key);
}
else {
debug(`(${updId}) ctx.session found, updating store`);
debug(`(${updId}) ctx.${prop} found, updating store`);
await store.set(key, ctx[prop]);

@@ -162,2 +159,3 @@ }

exports.MemorySessionStore = MemorySessionStore;
/** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
function isSessionContext(ctx) {

@@ -164,0 +162,0 @@ return 'session' in ctx;

@@ -11,3 +11,3 @@ "use strict";

const format_1 = require("./format");
const util_1 = require("./util");
const util_1 = require("./core/helpers/util");
class Telegram extends client_1.default {

@@ -852,2 +852,12 @@ /**

}
/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator
* right in the supergroup.
*
* @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
*/
unpinAllGeneralForumTopicMessages(chat_id) {
return this.callApi('unpinAllGeneralForumTopicMessages', { chat_id });
}
getStickerSet(name) {

@@ -862,6 +872,7 @@ return this.callApi('getStickerSet', { name });

*/
uploadStickerFile(ownerId, stickerFile) {
uploadStickerFile(ownerId, sticker, sticker_format) {
return this.callApi('uploadStickerFile', {
user_id: ownerId,
png_sticker: stickerFile,
sticker_format,
sticker,
});

@@ -906,6 +917,53 @@ }

}
setStickerSetThumb(name, userId, thumb) {
return this.callApi('setStickerSetThumb', { name, user_id: userId, thumb });
/**
* @deprecated since API 6.8. Use {@link Telegram.setStickerSetThumbnail}
*/
get setStickerSetThumb() {
return this.setStickerSetThumbnail;
}
/**
* Use this method to set the thumbnail of a regular or mask sticker set.
* The format of the thumbnail file must match the format of the stickers in the set.
* @param name Sticker set name
* @param userId User identifier of the sticker set owner
* @param thumbnail A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size
* and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to
* 32 kilobytes in size (see
* [animated sticker technical requirements](https://core.telegram.org/stickers#animated-sticker-requirements)),
* or a WEBM video with the thumbnail up to 32 kilobytes in size; see
* [video sticker technical requirements](https://core.telegram.org/stickers#video-sticker-requirements).
* Pass a file_id as a String to send a file that already exists on the Telegram servers, pass a
* HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using
* Input helpers. Animated and video sticker set thumbnails can't be uploaded via HTTP URL.
* If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.
*/
setStickerSetThumbnail(name, userId, thumbnail) {
return this.callApi('setStickerSetThumbnail', {
name,
user_id: userId,
thumbnail,
});
}
setStickerMaskPosition(sticker, mask_position) {
return this.callApi('setStickerMaskPosition', { sticker, mask_position });
}
setStickerKeywords(sticker, keywords) {
return this.callApi('setStickerKeywords', { sticker, keywords });
}
setStickerEmojiList(sticker, emoji_list) {
return this.callApi('setStickerEmojiList', { sticker, emoji_list });
}
deleteStickerSet(name) {
return this.callApi('deleteStickerSet', { name });
}
setStickerSetTitle(name, title) {
return this.callApi('setStickerSetTitle', { name, title });
}
setCustomEmojiStickerSetThumbnail(name, custom_emoji_id) {
return this.callApi('setCustomEmojiStickerSetThumbnail', {
name,
custom_emoji_id,
});
}
/**
* Delete a sticker from a set created by the bot.

@@ -921,8 +979,2 @@ * @param sticker File identifier of the sticker

/**
* Get the current list of the bot's commands.
*/
getMyCommands(extra = {}) {
return this.callApi('getMyCommands', extra);
}
/**
* Change the list of the bot's commands.

@@ -937,2 +989,56 @@ * @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.

}
/**
* Get the current list of the bot's commands.
*/
getMyCommands(extra = {}) {
return this.callApi('getMyCommands', extra);
}
/**
* Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
* @param description New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.
*/
setMyDescription(description, language_code) {
return this.callApi('setMyDescription', { description, language_code });
}
/**
* Use this method to change the bot's name.
* @param name New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name.
*/
setMyName(name, language_code) {
return this.callApi('setMyName', { name, language_code });
}
/**
* Use this method to get the current bot name for the given user language.
* @param language_code A two-letter ISO 639-1 language code or an empty string
*/
getMyName(language_code) {
return this.callApi('getMyName', { language_code });
}
/**
* Use this method to get the current bot description for the given user language.
* @param language_code A two-letter ISO 639-1 language code.
*/
getMyDescription(language_code) {
return this.callApi('getMyDescription', { language_code });
}
/**
* Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.
* @param description New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description.
*/
setMyShortDescription(short_description, language_code) {
return this.callApi('setMyShortDescription', {
short_description,
language_code,
});
}
/**
* Use this method to get the current bot short description for the given user language.
* @param language_code A two-letter ISO 639-1 language code or an empty string
*/
getMyShortDescription(language_code) {
return this.callApi('getMyShortDescription', { language_code });
}
setPassportDataErrors(userId, errors) {

@@ -939,0 +1045,0 @@ return this.callApi('setPassportDataErrors', {

{
"name": "telegraf",
"version": "4.12.3-canary.1",
"version": "4.13.0",
"description": "Modern Telegram Bot Framework",

@@ -40,2 +40,6 @@ "license": "MIT",

"default": "./format.js"
},
"./utils": {
"types": "./typings/utils.d.ts",
"default": "./lib/utils.d.ts"
}

@@ -80,2 +84,3 @@ },

"dependencies": {
"@telegraf/types": "^6.8.1",
"abort-controller": "^3.0.0",

@@ -87,23 +92,23 @@ "debug": "^4.3.4",

"safe-compare": "^1.1.4",
"sandwich-stream": "^2.0.2",
"typegram": "^4.3.0"
"sandwich-stream": "^2.0.2"
},
"devDependencies": {
"@types/debug": "^4.1.7",
"@types/node": "^18.11.18",
"@types/debug": "^4.1.8",
"@types/node": "^20.4.2",
"@types/node-fetch": "^2.6.2",
"@types/safe-compare": "^1.1.0",
"@typescript-eslint/eslint-plugin": "^5.49.0",
"@typescript-eslint/parser": "^5.49.0",
"ava": "^4.3.3",
"eslint": "^8.33.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-ava": "^13.2.0",
"@typescript-eslint/eslint-plugin": "^6.1.0",
"@typescript-eslint/parser": "^6.1.0",
"ava": "^5.3.1",
"eslint": "^8.45.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-ava": "^14.0.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-promise": "^6.1.1",
"prettier": "^2.8.3",
"typedoc": "^0.23.24",
"typescript": "^4.9.4"
"fast-check": "^3.12.0",
"prettier": "^3.0.3",
"typedoc": "^0.25.0",
"typescript": "^5.2.2"
},

@@ -110,0 +115,0 @@ "keywords": [

@@ -7,9 +7,15 @@ /** @format */

import Context, { FilteredContext, NarrowedContext } from './context'
import { MaybeArray, NonemptyReadonlyArray, MaybePromise, Guard } from './util'
import {
MaybeArray,
NonemptyReadonlyArray,
MaybePromise,
Guard,
} from './core/helpers/util'
import { type CallbackQuery } from './core/types/typegram'
import { message, callbackQuery } from './filters'
import { argsParser } from './core/helpers/args'
export type Triggers<C> = MaybeArray<
string | RegExp | ((value: string, ctx: C) => RegExpExecArray | null)
>
export type Triggers<C> = MaybeArray<string | RegExp | TriggerFn<C>>
type TriggerFn<C> = (value: string, ctx: C) => RegExpExecArray | null
export type Predicate<T> = (t: T) => boolean

@@ -20,5 +26,5 @@ export type AsyncPredicate<T> = (t: T) => Promise<boolean>

C extends Context,
T extends tt.UpdateType | tt.MessageSubType = 'message' | 'channel_post'
T extends tt.UpdateType | tt.MessageSubType = 'message' | 'channel_post',
> = NonemptyReadonlyArray<
Middleware<NarrowedContext<C & { match: RegExpExecArray }, tt.MountMap[T]>>
Middleware<NarrowedContext<C, tt.MountMap[T]> & { match: RegExpExecArray }>
>

@@ -33,3 +39,3 @@

C extends Context,
T extends tt.UpdateType | tt.MessageSubType
T extends tt.UpdateType | tt.MessageSubType,
> = NarrowedContext<C, tt.MountMap[T]>

@@ -40,2 +46,45 @@

}
interface StartContextExtn {
/**
* @deprecated Use ctx.payload instead
*/
startPayload: string
}
interface CommandContextExtn {
/**
* Matched command. This will always be the actual command, excluding preceeding slash and `@botname`
*
* Examples:
* ```
* /command abc -> command
* /command@xyzbot abc -> command
* ```
*/
command: string
/**
* The unparsed payload part of the command
*
* Examples:
* ```
* /command abc def -> "abc def"
* /command "token1 token2" -> "\"token1 token2\""
* ```
*/
payload: string
/**
* Command args parsed into an array.
*
* Examples:
* ```
* /command token1 token2 -> [ "token1", "token2" ]
* /command "token1 token2" -> [ "token1 token2" ]
* /command token1 "token2 token3" -> [ "token1" "token2 token3" ]
* ```
* @unstable Parser implementation might vary until considered stable
* */
args: string[]
}
const anoop = always(Promise.resolve())

@@ -108,3 +157,6 @@

*/
hears(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'text'>) {
hears(
triggers: Triggers<NarrowedContext<C, tt.MountMap['text']>>,
...fns: MatchedMiddleware<C, 'text'>
) {
return this.use(Composer.hears<C>(triggers, ...fns))

@@ -117,5 +169,5 @@ }

command(
command: Triggers<C>,
command: Triggers<NarrowedContext<C, tt.MountMap['text']>>,
...fns: NonemptyReadonlyArray<
Middleware<NarrowedContext<C, tt.MountMap['text']>>
Middleware<NarrowedContext<C, tt.MountMap['text']> & CommandContextExtn>
>

@@ -130,3 +182,3 @@ ) {

action(
triggers: Triggers<C>,
triggers: Triggers<NarrowedContext<C, tt.MountMap['callback_query']>>,
...fns: MatchedMiddleware<C, 'callback_query'>

@@ -141,3 +193,3 @@ ) {

inlineQuery(
triggers: Triggers<C>,
triggers: Triggers<NarrowedContext<C, tt.MountMap['inline_query']>>,
...fns: MatchedMiddleware<C, 'inline_query'>

@@ -179,3 +231,3 @@ ) {

| 'message'
| 'channel_post'
| 'channel_post',
>(

@@ -231,15 +283,9 @@ predicate:

...fns: NonemptyReadonlyArray<
Middleware<
NarrowedContext<C, tt.MountMap['text']> & { startPayload: string }
>
Middleware<NarrowedContext<C, tt.MountMap['text']> & StartContextExtn>
>
) {
const handler = Composer.compose(fns)
return this.command('start', (ctx, next) => {
// First entity is the /start bot_command itself
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const entity = ctx.message.entities![0]!
const startPayload = ctx.message.text.slice(entity.length + 1)
return handler(Object.assign(ctx, { startPayload }), next)
})
return this.command('start', (ctx, next) =>
handler(Object.assign(ctx, { startPayload: ctx.payload }), next)
)
}

@@ -378,3 +424,3 @@

C extends Context,
Handlers extends Record<string | number | symbol, Middleware<C>>
Handlers extends Record<string | number | symbol, Middleware<C>>,
>(

@@ -433,3 +479,3 @@ routeFn: (ctx: C) => MaybePromise<keyof Handlers>,

Ctx extends Context,
Filter extends tt.UpdateType | Guard<Ctx['update']>
Filter extends tt.UpdateType | Guard<Ctx['update']>,
>(

@@ -446,3 +492,3 @@ filters: MaybeArray<Filter>,

Ctx extends Context,
Filter extends tt.UpdateType | tt.MessageSubType
Filter extends tt.UpdateType | tt.MessageSubType,
>(

@@ -457,3 +503,3 @@ filters: MaybeArray<Filter>,

Ctx extends Context,
Filter extends tt.UpdateType | tt.MessageSubType | Guard<Ctx['update']>
Filter extends tt.UpdateType | tt.MessageSubType | Guard<Ctx['update']>,
>(

@@ -499,3 +545,3 @@ updateType: MaybeArray<Filter>,

| 'message'
| 'channel_post'
| 'channel_post',
>(

@@ -508,22 +554,25 @@ predicate:

if (typeof predicate !== 'function') {
const entityTypes = normalizeTextArguments(predicate)
const entityTypes = normaliseTextArguments(predicate)
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns)
}
return Composer.optional<C>((ctx) => {
const msg: tg.Message | undefined = ctx.message ?? ctx.channelPost
if (msg === undefined) {
return false
}
const text = getText(msg)
const entities = getEntities(msg)
if (text === undefined) return false
return entities.some((entity) =>
predicate(
entity,
text.substring(entity.offset, entity.offset + entity.length),
ctx
return Composer.optional<C>(
(ctx) => {
const msg: tg.Message | undefined = ctx.message ?? ctx.channelPost
if (msg === undefined) {
return false
}
const text = getText(msg)
const entities = getEntities(msg)
if (text === undefined) return false
return entities.some((entity) =>
predicate(
entity,
text.substring(entity.offset, entity.offset + entity.length),
ctx
)
)
)
},
// @ts-expect-error see explanation above
}, ...fns)
...fns
)
}

@@ -544,16 +593,19 @@

}
const triggers = normalizeTriggers(predicate)
return Composer.entity<C>(({ type }, value, ctx) => {
if (type !== entityType) {
const triggers = normaliseTriggers(predicate)
return Composer.entity<C>(
({ type }, value, ctx) => {
if (type !== entityType) {
return false
}
for (const trigger of triggers) {
// @ts-expect-error define so far unknown property `match`
if ((ctx.match = trigger(value, ctx))) {
return true
}
}
return false
}
for (const trigger of triggers) {
// @ts-expect-error define so far unknown property `match`
if ((ctx.match = trigger(value, ctx))) {
return true
}
}
return false
},
// @ts-expect-error see explanation above
}, ...fns)
...fns
)
}

@@ -602,3 +654,3 @@

'mention',
normalizeTextArguments(mention, '@'),
normaliseTextArguments(mention, '@'),
...fns

@@ -614,3 +666,3 @@ )

'hashtag',
normalizeTextArguments(hashtag, '#'),
normaliseTextArguments(hashtag, '#'),
...fns

@@ -626,3 +678,3 @@ )

'cashtag',
normalizeTextArguments(cashtag, '$'),
normaliseTextArguments(cashtag, '$'),
...fns

@@ -639,14 +691,6 @@ )

private static match<
C extends Context,
T extends
| 'message'
| 'channel_post'
| 'callback_query'
| 'inline_query'
| tt.MessageSubType
>(
triggers: ReadonlyArray<(text: string, ctx: C) => RegExpExecArray | null>,
...fns: MatchedMiddleware<C, T>
): MiddlewareFn<NarrowedContext<C, tt.MountMap[T]>> {
private static match<C extends Context>(
triggers: ReadonlyArray<TriggerFn<C>>,
...fns: Middleware<C & { match: RegExpExecArray }>[]
): MiddlewareFn<C> {
const handler = Composer.compose(fns)

@@ -661,8 +705,4 @@ return (ctx, next) => {

for (const trigger of triggers) {
// @ts-expect-error Trust me, TS!
const match = trigger(text, ctx)
if (match) {
// @ts-expect-error define so far unknown property `match`
return handler(Object.assign(ctx, { match }), next)
}
if (match) return handler(Object.assign(ctx, { match }), next)
}

@@ -677,3 +717,3 @@ return next()

static hears<C extends Context>(
triggers: Triggers<C>,
triggers: Triggers<NarrowedContext<C, tt.MountMap['text']>>,
...fns: MatchedMiddleware<C, 'text'>

@@ -683,3 +723,6 @@ ): MiddlewareFn<C> {

'text',
Composer.match<C, 'text'>(normalizeTriggers(triggers), ...fns)
Composer.match<NarrowedContext<C, tt.MountMap['text']>>(
normaliseTriggers(triggers),
...fns
)
)

@@ -692,5 +735,5 @@ }

static command<C extends Context>(
command: Triggers<C>,
command: Triggers<NarrowedContext<C, tt.MountMap['text']>>,
...fns: NonemptyReadonlyArray<
Middleware<NarrowedContext<C, tt.MountMap['text']>>
Middleware<NarrowedContext<C, tt.MountMap['text']> & CommandContextExtn>
>

@@ -702,16 +745,39 @@ ): MiddlewareFn<C> {

const triggers = normalizeTriggers<C>(command)
const triggers = normaliseTriggers(command)
const filter = message('text')
const handler = Composer.compose(fns)
return Composer.on<C, typeof filter>(filter, (ctx, next) => {
const first = ctx.message.entities?.[0]
if (first?.type !== 'bot_command') return next()
if (first.offset > 0) return next()
const [cmdPart, to] = ctx.message.text.slice(0, first.length).split('@')
const { entities } = ctx.message
const cmdEntity = entities?.[0]
if (cmdEntity?.type !== 'bot_command') return next()
if (cmdEntity.offset > 0) return next()
const len = cmdEntity.length
const text = ctx.message.text
const [cmdPart, to] = text.slice(0, len).split('@')
if (!cmdPart) return next()
// always check for bot's own username case-insensitively
if (to && to.toLowerCase() !== ctx.me.toLowerCase()) return next()
const cmd = cmdPart.slice(1)
const command = cmdPart.slice(1)
for (const trigger of triggers)
if (trigger(cmd, ctx as C)) return Composer.compose(fns)(ctx, next)
if (trigger(command, ctx)) {
const payloadOffset = len + 1
const payload = text.slice(payloadOffset)
const c = Object.assign(ctx, { command, payload, args: [] })
let _args: string[] | undefined = undefined
// using defineProperty only to make parsing lazy on access
Object.defineProperty(c, 'args', {
enumerable: true,
configurable: true,
get() {
if (_args != null) return _args
// once parsed, cache and don't parse again on every access
return (_args = argsParser(payload, entities, payloadOffset))
},
set(args: string[]) {
_args = args
},
})
return handler(c, next)
}
return next()

@@ -725,3 +791,3 @@ })

static action<C extends Context>(
triggers: Triggers<C>,
triggers: Triggers<NarrowedContext<C, tt.MountMap['callback_query']>>,
...fns: MatchedMiddleware<C, 'callback_query'>

@@ -731,3 +797,3 @@ ): MiddlewareFn<C> {

'callback_query',
Composer.match<C, 'callback_query'>(normalizeTriggers(triggers), ...fns)
Composer.match(normaliseTriggers(triggers), ...fns)
)

@@ -740,3 +806,3 @@ }

static inlineQuery<C extends Context>(
triggers: Triggers<C>,
triggers: Triggers<NarrowedContext<C, tt.MountMap['inline_query']>>,
...fns: MatchedMiddleware<C, 'inline_query'>

@@ -746,3 +812,3 @@ ): MiddlewareFn<C> {

'inline_query',
Composer.match<C, 'inline_query'>(normalizeTriggers(triggers), ...fns)
Composer.match(normaliseTriggers(triggers), ...fns)
)

@@ -771,7 +837,10 @@ }

const statuses = Array.isArray(status) ? status : [status]
return Composer.optional(async (ctx) => {
if (ctx.message === undefined) return false
const member = await ctx.getChatMember(ctx.message.from.id)
return statuses.includes(member.status)
}, ...fns)
return Composer.optional(
async (ctx) => {
if (ctx.message === undefined) return false
const member = await ctx.getChatMember(ctx.message.from.id)
return statuses.includes(member.status)
},
...fns
)
}

@@ -805,6 +874,9 @@

const types = Array.isArray(type) ? type : [type]
return Composer.optional((ctx) => {
const chat = ctx.chat
return chat !== undefined && types.includes(chat.type)
}, ...fns)
return Composer.optional(
(ctx) => {
const chat = ctx.chat
return chat !== undefined && types.includes(chat.type)
},
...fns
)
}

@@ -892,5 +964,5 @@

function normalizeTriggers<C extends Context>(
function normaliseTriggers<C extends Context>(
triggers: Triggers<C>
): Array<(value: string, ctx: C) => RegExpExecArray | null> {
): Array<TriggerFn<C>> {
if (!Array.isArray(triggers)) triggers = [triggers]

@@ -930,3 +1002,3 @@

function normalizeTextArguments(argument: MaybeArray<string>, prefix = '') {
function normaliseTextArguments(argument: MaybeArray<string>, prefix = '') {
const args = Array.isArray(argument) ? argument : [argument]

@@ -933,0 +1005,0 @@ // prettier-ignore

@@ -5,3 +5,3 @@ import * as tg from './core/types/typegram'

import ApiClient from './core/network/client'
import { Guard, Guarded, MaybeArray } from './util'
import { Guard, Guarded, MaybeArray } from './core/helpers/util'
import Telegram from './telegram'

@@ -28,3 +28,3 @@ import { FmtString } from './format'

C extends Context,
U extends tg.Update
U extends tg.Update,
> = Context<U> & Omit<C, keyof Context>

@@ -34,3 +34,3 @@

Ctx extends Context,
Filter extends tt.UpdateType | Guard<Ctx['update']>
Filter extends tt.UpdateType | Guard<Ctx['update']>,
> = Filter extends tt.UpdateType

@@ -163,3 +163,2 @@ ? NarrowedContext<Ctx, Extract<tg.Update, Record<Filter, object>>>

if (this.message == null) return undefined
// @ts-expect-error Bug in TS 4.9+, fix will land in 5.0 https://github.com/microsoft/TypeScript/pull/51502
if (!('passport_data' in this.message)) return undefined

@@ -284,3 +283,3 @@ return this.message?.passport_data

*/
editMessageText(text: string, extra?: tt.ExtraEditMessageText) {
editMessageText(text: string | FmtString, extra?: tt.ExtraEditMessageText) {
this.assert(this.callbackQuery ?? this.inlineMessageId, 'editMessageText')

@@ -1164,2 +1163,16 @@ return this.telegram.editMessageText(

/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator
* right in the supergroup.
*
* @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
*
* @see https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
*/
unpinAllGeneralForumTopicMessages() {
this.assert(this.chat, 'unpinAllGeneralForumTopicMessages')
return this.telegram.unpinAllGeneralForumTopicMessages(this.chat.id)
}
/**
* @deprecated use {@link Telegram.setStickerPositionInSet}

@@ -1173,9 +1186,43 @@ * @see https://core.telegram.org/bots/api#setstickerpositioninset

/**
* @deprecated use {@link Telegram.setStickerSetThumb}
* @see https://core.telegram.org/bots/api#setstickersetthumb
* @deprecated use {@link Telegram.setStickerSetThumbnail}
* @see https://core.telegram.org/bots/api#setstickersetthumbnail
*/
setStickerSetThumb(...args: Parameters<Telegram['setStickerSetThumb']>) {
return this.telegram.setStickerSetThumb(...args)
setStickerSetThumb(...args: Parameters<Telegram['setStickerSetThumbnail']>) {
return this.telegram.setStickerSetThumbnail(...args)
}
setStickerSetThumbnail(
...args: Parameters<Telegram['setStickerSetThumbnail']>
) {
return this.telegram.setStickerSetThumbnail(...args)
}
setStickerMaskPosition(
...args: Parameters<Telegram['setStickerMaskPosition']>
) {
return this.telegram.setStickerMaskPosition(...args)
}
setStickerKeywords(...args: Parameters<Telegram['setStickerKeywords']>) {
return this.telegram.setStickerKeywords(...args)
}
setStickerEmojiList(...args: Parameters<Telegram['setStickerEmojiList']>) {
return this.telegram.setStickerEmojiList(...args)
}
deleteStickerSet(...args: Parameters<Telegram['deleteStickerSet']>) {
return this.telegram.deleteStickerSet(...args)
}
setStickerSetTitle(...args: Parameters<Telegram['setStickerSetTitle']>) {
return this.telegram.setStickerSetTitle(...args)
}
setCustomEmojiStickerSetThumbnail(
...args: Parameters<Telegram['setCustomEmojiStickerSetThumbnail']>
) {
return this.telegram.setCustomEmojiStickerSetThumbnail(...args)
}
/**

@@ -1182,0 +1229,0 @@ * @deprecated use {@link Telegram.deleteStickerFromSet}

@@ -53,3 +53,3 @@ interface Mapping {

T extends keyof Mapping,
V extends Mapping[T]
V extends Mapping[T],
>(obj: O | undefined, prop: K, type: T): obj is O & Record<K, V> {

@@ -56,0 +56,0 @@ return hasProp(obj, prop) && type === typeof obj[prop]

@@ -1,3 +0,4 @@

import { MessageEntity, User } from 'typegram'
import { zip } from '../../util'
/* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
import { MessageEntity, User } from '@telegraf/types'
import { zip } from './util'

@@ -11,3 +12,6 @@ export interface FmtString {

export class FmtString implements FmtString {
constructor(public text: string, entities?: MessageEntity[]) {
constructor(
public text: string,
entities?: MessageEntity[]
) {
if (entities) {

@@ -85,44 +89,2 @@ this.entities = entities

export const replace = (
source: string,
search: string | RegExp,
value: string | FmtString
): FmtString => {
const v = FmtString.normalise(value)
let entities: MessageEntity[] | undefined = undefined
if (typeof search === 'string') {
const offset = source.indexOf(search)
const length = search.length
source = source.slice(0, offset) + v.text + source.slice(offset + length)
entities = v.entities?.map((e) => ({ ...e, offset: e.offset + offset }))
} else {
let index = 0 // context position in source string
let acc = '' // incremental return value
let correction = 0
let regexArray
while ((regexArray = search.exec(source))) {
const offset = regexArray.index
const length = regexArray[0].length
acc += source.slice(index, offset) + v.text
if (v.entities && v.entities.length)
(entities ??= []).push(
...v.entities.map((e) => ({
...e,
offset: e.offset + offset + correction,
}))
)
index = offset + length
correction += v.text.length - length
}
source = acc + source.slice(index)
}
return new FmtString(source, entities)
}
/** Internal constructor for all fmt helpers */

@@ -129,0 +91,0 @@ export function _fmt(

@@ -362,2 +362,3 @@ /* eslint @typescript-eslint/restrict-template-expressions: [ "error", { "allowNumber": true, "allowBoolean": true } ] */

config.agent = options.agent
// @ts-expect-error AbortSignal shim is missing some props from Request.AbortSignal
config.signal = signal

@@ -364,0 +365,0 @@ config.timeout = 500_000 // ms

@@ -9,3 +9,6 @@ import { ResponseParameters } from '../types/typegram'

export class TelegramError extends Error {
constructor(readonly response: ErrorPayload, readonly on = {}) {
constructor(
readonly response: ErrorPayload,
readonly on = {}
) {
super(`${response.error_code}: ${response.description}`)

@@ -12,0 +15,0 @@ }

@@ -1,13 +0,14 @@

import { Typegram } from 'typegram'
import * as Typegram from '@telegraf/types'
// internal type provisions
export * from 'typegram/api'
export * from 'typegram/markup'
export * from 'typegram/menu-button'
export * from 'typegram/inline'
export * from 'typegram/manage'
export * from 'typegram/message'
export * from 'typegram/passport'
export * from 'typegram/payment'
export * from 'typegram/update'
export * from '@telegraf/types/api'
export * from '@telegraf/types/inline'
export * from '@telegraf/types/manage'
export * from '@telegraf/types/markup'
export * from '@telegraf/types/message'
export * from '@telegraf/types/methods'
export * from '@telegraf/types/passport'
export * from '@telegraf/types/payment'
export * from '@telegraf/types/settings'
export * from '@telegraf/types/update'

@@ -37,13 +38,11 @@ // telegraf input file definition

// typegram proxy type setup
type TelegrafTypegram = Typegram<InputFile>
export type Telegram = Typegram.ApiMethods<InputFile>
export type Telegram = TelegrafTypegram['Telegram']
export type Opts<M extends keyof Telegram> = TelegrafTypegram['Opts'][M]
export type InputMedia = TelegrafTypegram['InputMedia']
export type InputMediaPhoto = TelegrafTypegram['InputMediaPhoto']
export type InputMediaVideo = TelegrafTypegram['InputMediaVideo']
export type InputMediaAnimation = TelegrafTypegram['InputMediaAnimation']
export type InputMediaAudio = TelegrafTypegram['InputMediaAudio']
export type InputMediaDocument = TelegrafTypegram['InputMediaDocument']
export type Opts<M extends keyof Telegram> = Typegram.Opts<InputFile>[M]
export type InputMedia = Typegram.InputMedia<InputFile>
export type InputMediaPhoto = Typegram.InputMediaPhoto<InputFile>
export type InputMediaVideo = Typegram.InputMediaVideo<InputFile>
export type InputMediaAnimation = Typegram.InputMediaAnimation<InputFile>
export type InputMediaAudio = Typegram.InputMediaAudio<InputFile>
export type InputMediaDocument = Typegram.InputMediaDocument<InputFile>

@@ -50,0 +49,0 @@ // tiny helper types

export type PropOr<
T extends object | undefined,
P extends string | symbol | number,
D = undefined
D = undefined,
> = T extends Partial<Record<P, unknown>> ? T[P] : D

@@ -16,3 +16,3 @@

B extends object | undefined,
T extends B = B
T extends B = B,
> = T extends object ? T & AddOptionalKeys<Exclude<UnionKeys<B>, keyof T>> : T

@@ -19,0 +19,0 @@

@@ -7,3 +7,3 @@ /* eslint-disable @typescript-eslint/ban-types */

Update,
} from 'typegram'
} from '@telegraf/types'
import type { Deunionize, UnionKeys } from './deunionize'

@@ -10,0 +10,0 @@

@@ -1,17 +0,19 @@

import { User } from 'typegram'
import { FmtString, _fmt, linkOrMention } from './core/helpers/formatting'
import { User } from '@telegraf/types'
import { FmtString, _fmt, linkOrMention, join } from './core/helpers/formatting'
export const fmt = _fmt()
export const bold = _fmt('bold')
export const italic = _fmt('italic')
export const spoiler = _fmt('spoiler')
export const strikethrough = _fmt('strikethrough')
export const underline = _fmt('underline')
export const code = _fmt('code')
export const pre = (language: string) => _fmt('pre', { language })
export { FmtString }
export const link = (content: string | FmtString, url: string) =>
const fmt = _fmt()
const bold = _fmt('bold')
const italic = _fmt('italic')
const spoiler = _fmt('spoiler')
const strikethrough = _fmt('strikethrough')
const underline = _fmt('underline')
const code = _fmt('code')
const pre = (language: string) => _fmt('pre', { language })
const link = (content: string | FmtString, url: string) =>
linkOrMention(content, { type: 'text_link', url })
export const mention = (name: string | FmtString, user: number | User) =>
const mention = (name: string | FmtString, user: number | User) =>
typeof user === 'number'

@@ -21,3 +23,14 @@ ? link(name, 'tg://user?id=' + user)

export { FmtString }
export { join, replace } from './core/helpers/formatting'
export {
fmt,
bold,
italic,
spoiler,
strikethrough,
underline,
code,
pre,
link,
mention,
join,
}

@@ -8,3 +8,3 @@ import Context from './context'

C extends Context,
E extends { reply_to_message_id?: number }
E extends { reply_to_message_id?: number },
>(ctx: C, extra?: E) {

@@ -11,0 +11,0 @@ const reply_to_message_id = ctx.message?.message_id

@@ -15,4 +15,4 @@ export { Telegraf } from './telegraf'

export { deunionize } from './deunionize'
export { session, MemorySessionStore } from './session'
export { session, MemorySessionStore, SessionStore } from './session'
export * as Scenes from './scenes'

@@ -20,3 +20,3 @@ import {

| ReplyKeyboardRemove
| ForceReply
| ForceReply,
> {

@@ -23,0 +23,0 @@ constructor(readonly reply_markup: T) {}

@@ -35,3 +35,3 @@ import BaseScene from './base'

C extends SessionContext<SceneSession<D>>,
D extends SceneSessionData = SceneSessionData
D extends SceneSessionData = SceneSessionData,
> {

@@ -38,0 +38,0 @@ private readonly options: SceneContextSceneOptions<D>

@@ -15,3 +15,3 @@ import { isSessionContext, SessionContext } from '../session'

},
D extends SceneSessionData = SceneSessionData
D extends SceneSessionData = SceneSessionData,
> extends Composer<C> {

@@ -18,0 +18,0 @@ options: Partial<SceneContextSceneOptions<D>>

@@ -23,3 +23,3 @@ import SceneContextScene, { SceneSession, SceneSessionData } from '../context'

scene: SceneContextScene<C, WizardSessionData>
}
},
> {

@@ -26,0 +26,0 @@ readonly state: object

@@ -12,3 +12,3 @@ import BaseScene, { SceneOptions } from '../base'

wizard: WizardContextWizard<C>
}
},
>

@@ -15,0 +15,0 @@ extends BaseScene<C>

import { Context } from './context'
import { MaybePromise } from './util'
import { ExclusiveKeys, MaybePromise } from './core/helpers/util'
import { MiddlewareFn } from './middleware'

@@ -21,14 +21,11 @@ import d from 'debug'

interface SessionOptions<
S extends object,
C extends Context = Context,
Property extends string = 'session'
> {
interface SessionOptions<S, C extends Context, P extends string> {
/** Customise the session prop. Defaults to "session" and is available as ctx.session. */
property?: P
getSessionKey?: (ctx: C) => MaybePromise<string | undefined>
store?: SessionStore<S>
defaultSession?: (ctx: C) => S
/** Defaults to `session`. If provided, property name will be used instead of `ctx.session`. */
property?: Property
}
/** @deprecated session can use custom properties now. Construct this type directly. */
export interface SessionContext<S extends object> extends Context {

@@ -44,5 +41,5 @@ session?: S

*
* > āš ļø Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
* > āš ļø Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
* >
* > If you want to store data across restarts, or share it among workers, you should use
* > If you want to persist data across process restarts, or share it among multiple instances, you should use
* [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.

@@ -54,8 +51,10 @@ *

export function session<
S extends object,
C extends Context = Context,
P extends string = 'session'
>(options?: SessionOptions<S, C, P>): MiddlewareFn<C & { [session in P]?: S }> {
S extends NonNullable<C[P]>,
C extends Context & { [key in P]?: C[P] },
P extends (ExclusiveKeys<C, Context> & string) | 'session' = 'session',
// ^ Only allow prop names that aren't keys in base Context.
// At type level, this is cosmetic. To not get cluttered with all Context keys.
>(options?: SessionOptions<S, C, P>): MiddlewareFn<C> {
const prop = options?.property ?? ('session' as P)
const getSessionKey = options?.getSessionKey ?? defaultGetSessionKey
const prop = options?.property ?? ('session' as P)
const store = options?.store ?? new MemorySessionStore()

@@ -78,7 +77,4 @@ // caches value from store in-memory while simultaneous updates share it

if (!key) {
Object.defineProperty(ctx, prop, {
get() {
undefined
},
})
// Leaving this here could be useful to check for `prop in ctx` in future middleware
ctx[prop] = undefined as unknown as S
return await next()

@@ -151,6 +147,6 @@ }

if (ctx[prop] == null) {
debug(`(${updId}) ctx.session missing, removing from store`)
debug(`(${updId}) ctx.${prop} missing, removing from store`)
await store.delete(key)
} else {
debug(`(${updId}) ctx.session found, updating store`)
debug(`(${updId}) ctx.${prop} found, updating store`)
await store.set(key, ctx[prop] as S)

@@ -198,2 +194,3 @@ }

/** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
export function isSessionContext<S extends object>(

@@ -200,0 +197,0 @@ ctx: Context

@@ -7,3 +7,3 @@ import * as crypto from 'crypto'

import { Composer } from './composer'
import { MaybePromise } from './util'
import { MaybePromise } from './core/helpers/util'
import ApiClient from './core/network/client'

@@ -10,0 +10,0 @@ import { compactOptions } from './core/helpers/compact'

/** @format */
import { Expand } from './util'
import { Expand } from './core/helpers/util'
import {

@@ -36,3 +36,3 @@ Message,

M extends keyof Telegram,
K extends keyof Omit<Opts<M>, 'chat_id'> = never
K extends keyof Omit<Opts<M>, 'chat_id'> = never,
> = WrapCaption<Omit<Opts<M>, 'chat_id' | K>>

@@ -39,0 +39,0 @@

@@ -7,3 +7,3 @@ import * as tg from './core/types/typegram'

import { FmtString } from './format'
import { fmtCaption } from './util'
import { fmtCaption } from './core/helpers/util'

@@ -1138,2 +1138,13 @@ export class Telegram extends ApiClient {

/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator
* right in the supergroup.
*
* @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
*/
unpinAllGeneralForumTopicMessages(chat_id: number | string) {
return this.callApi('unpinAllGeneralForumTopicMessages', { chat_id })
}
getStickerSet(name: string) {

@@ -1151,7 +1162,9 @@ return this.callApi('getStickerSet', { name })

ownerId: number,
stickerFile: tg.Opts<'uploadStickerFile'>['png_sticker']
sticker: tg.Opts<'uploadStickerFile'>['sticker'],
sticker_format: tg.Opts<'uploadStickerFile'>['sticker_format']
) {
return this.callApi('uploadStickerFile', {
user_id: ownerId,
png_sticker: stickerFile,
sticker_format,
sticker,
})

@@ -1209,10 +1222,64 @@ }

setStickerSetThumb(
/**
* @deprecated since API 6.8. Use {@link Telegram.setStickerSetThumbnail}
*/
get setStickerSetThumb() {
return this.setStickerSetThumbnail
}
/**
* Use this method to set the thumbnail of a regular or mask sticker set.
* The format of the thumbnail file must match the format of the stickers in the set.
* @param name Sticker set name
* @param userId User identifier of the sticker set owner
* @param thumbnail A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size
* and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to
* 32 kilobytes in size (see
* [animated sticker technical requirements](https://core.telegram.org/stickers#animated-sticker-requirements)),
* or a WEBM video with the thumbnail up to 32 kilobytes in size; see
* [video sticker technical requirements](https://core.telegram.org/stickers#video-sticker-requirements).
* Pass a file_id as a String to send a file that already exists on the Telegram servers, pass a
* HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using
* Input helpers. Animated and video sticker set thumbnails can't be uploaded via HTTP URL.
* If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.
*/
setStickerSetThumbnail(
name: string,
userId: number,
thumb?: tg.Opts<'setStickerSetThumb'>['thumb']
thumbnail?: tg.Opts<'setStickerSetThumbnail'>['thumbnail']
) {
return this.callApi('setStickerSetThumb', { name, user_id: userId, thumb })
return this.callApi('setStickerSetThumbnail', {
name,
user_id: userId,
thumbnail,
})
}
setStickerMaskPosition(sticker: string, mask_position?: tg.MaskPosition) {
return this.callApi('setStickerMaskPosition', { sticker, mask_position })
}
setStickerKeywords(sticker: string, keywords?: string[]) {
return this.callApi('setStickerKeywords', { sticker, keywords })
}
setStickerEmojiList(sticker: string, emoji_list: string[]) {
return this.callApi('setStickerEmojiList', { sticker, emoji_list })
}
deleteStickerSet(name: string) {
return this.callApi('deleteStickerSet', { name })
}
setStickerSetTitle(name: string, title: string) {
return this.callApi('setStickerSetTitle', { name, title })
}
setCustomEmojiStickerSetThumbnail(name: string, custom_emoji_id: string) {
return this.callApi('setCustomEmojiStickerSetThumbnail', {
name,
custom_emoji_id,
})
}
/**

@@ -1231,9 +1298,2 @@ * Delete a sticker from a set created by the bot.

/**
* Get the current list of the bot's commands.
*/
getMyCommands(extra: tg.Opts<'getMyCommands'> = {}) {
return this.callApi('getMyCommands', extra)
}
/**
* Change the list of the bot's commands.

@@ -1253,2 +1313,63 @@ * @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.

/**
* Get the current list of the bot's commands.
*/
getMyCommands(extra: tg.Opts<'getMyCommands'> = {}) {
return this.callApi('getMyCommands', extra)
}
/**
* Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
* @param description New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.
*/
setMyDescription(description: string, language_code?: string) {
return this.callApi('setMyDescription', { description, language_code })
}
/**
* Use this method to change the bot's name.
* @param name New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name.
*/
setMyName(name: string, language_code?: string) {
return this.callApi('setMyName', { name, language_code })
}
/**
* Use this method to get the current bot name for the given user language.
* @param language_code A two-letter ISO 639-1 language code or an empty string
*/
getMyName(language_code?: string) {
return this.callApi('getMyName', { language_code })
}
/**
* Use this method to get the current bot description for the given user language.
* @param language_code A two-letter ISO 639-1 language code.
*/
getMyDescription(language_code?: string) {
return this.callApi('getMyDescription', { language_code })
}
/**
* Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.
* @param description New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description.
*/
setMyShortDescription(short_description: string, language_code?: string) {
return this.callApi('setMyShortDescription', {
short_description,
language_code,
})
}
/**
* Use this method to get the current bot short description for the given user language.
* @param language_code A two-letter ISO 639-1 language code or an empty string
*/
getMyShortDescription(language_code?: string) {
return this.callApi('getMyShortDescription', { language_code })
}
setPassportDataErrors(

@@ -1255,0 +1376,0 @@ userId: number,

@@ -6,10 +6,51 @@ /** @format */

import Context, { FilteredContext, NarrowedContext } from './context';
import { MaybeArray, NonemptyReadonlyArray, MaybePromise, Guard } from './util';
import { MaybeArray, NonemptyReadonlyArray, MaybePromise, Guard } from './core/helpers/util';
import { type CallbackQuery } from './core/types/typegram';
export type Triggers<C> = MaybeArray<string | RegExp | ((value: string, ctx: C) => RegExpExecArray | null)>;
export type Triggers<C> = MaybeArray<string | RegExp | TriggerFn<C>>;
type TriggerFn<C> = (value: string, ctx: C) => RegExpExecArray | null;
export type Predicate<T> = (t: T) => boolean;
export type AsyncPredicate<T> = (t: T) => Promise<boolean>;
export type MatchedMiddleware<C extends Context, T extends tt.UpdateType | tt.MessageSubType = 'message' | 'channel_post'> = NonemptyReadonlyArray<Middleware<NarrowedContext<C & {
export type MatchedMiddleware<C extends Context, T extends tt.UpdateType | tt.MessageSubType = 'message' | 'channel_post'> = NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap[T]> & {
match: RegExpExecArray;
}, tt.MountMap[T]>>>;
}>>;
interface StartContextExtn {
/**
* @deprecated Use ctx.payload instead
*/
startPayload: string;
}
interface CommandContextExtn {
/**
* Matched command. This will always be the actual command, excluding preceeding slash and `@botname`
*
* Examples:
* ```
* /command abc -> command
* /command@xyzbot abc -> command
* ```
*/
command: string;
/**
* The unparsed payload part of the command
*
* Examples:
* ```
* /command abc def -> "abc def"
* /command "token1 token2" -> "\"token1 token2\""
* ```
*/
payload: string;
/**
* Command args parsed into an array.
*
* Examples:
* ```
* /command token1 token2 -> [ "token1", "token2" ]
* /command "token1 token2" -> [ "token1 token2" ]
* /command token1 "token2 token3" -> [ "token1" "token2 token3" ]
* ```
* @unstable Parser implementation might vary until considered stable
* */
args: string[];
}
export declare class Composer<C extends Context> implements MiddlewareObj<C> {

@@ -40,15 +81,15 @@ private handler;

*/
hears(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'text'>): this;
hears(triggers: Triggers<NarrowedContext<C, tt.MountMap['text']>>, ...fns: MatchedMiddleware<C, 'text'>): this;
/**
* Registers middleware for handling specified commands.
*/
command(command: Triggers<C>, ...fns: NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap['text']>>>): this;
command(command: Triggers<NarrowedContext<C, tt.MountMap['text']>>, ...fns: NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap['text']> & CommandContextExtn>>): this;
/**
* Registers middleware for handling matching callback queries.
*/
action(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'callback_query'>): this;
action(triggers: Triggers<NarrowedContext<C, tt.MountMap['callback_query']>>, ...fns: MatchedMiddleware<C, 'callback_query'>): this;
/**
* Registers middleware for handling matching inline queries.
*/
inlineQuery(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'inline_query'>): this;
inlineQuery(triggers: Triggers<NarrowedContext<C, tt.MountMap['inline_query']>>, ...fns: MatchedMiddleware<C, 'inline_query'>): this;
/**

@@ -77,5 +118,3 @@ * Registers middleware for handling game queries

*/
start(...fns: NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap['text']> & {
startPayload: string;
}>>): this;
start(...fns: NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap['text']> & StartContextExtn>>): this;
/**

@@ -171,15 +210,15 @@ * Registers a middleware for handling /help

*/
static hears<C extends Context>(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'text'>): MiddlewareFn<C>;
static hears<C extends Context>(triggers: Triggers<NarrowedContext<C, tt.MountMap['text']>>, ...fns: MatchedMiddleware<C, 'text'>): MiddlewareFn<C>;
/**
* Generates middleware for handling specified commands.
*/
static command<C extends Context>(command: Triggers<C>, ...fns: NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap['text']>>>): MiddlewareFn<C>;
static command<C extends Context>(command: Triggers<NarrowedContext<C, tt.MountMap['text']>>, ...fns: NonemptyReadonlyArray<Middleware<NarrowedContext<C, tt.MountMap['text']> & CommandContextExtn>>): MiddlewareFn<C>;
/**
* Generates middleware for handling matching callback queries.
*/
static action<C extends Context>(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'callback_query'>): MiddlewareFn<C>;
static action<C extends Context>(triggers: Triggers<NarrowedContext<C, tt.MountMap['callback_query']>>, ...fns: MatchedMiddleware<C, 'callback_query'>): MiddlewareFn<C>;
/**
* Generates middleware for handling matching inline queries.
*/
static inlineQuery<C extends Context>(triggers: Triggers<C>, ...fns: MatchedMiddleware<C, 'inline_query'>): MiddlewareFn<C>;
static inlineQuery<C extends Context>(triggers: Triggers<NarrowedContext<C, tt.MountMap['inline_query']>>, ...fns: MatchedMiddleware<C, 'inline_query'>): MiddlewareFn<C>;
/**

@@ -186,0 +225,0 @@ * Generates middleware responding only to specified users.

@@ -5,3 +5,3 @@ import * as tg from './core/types/typegram';

import ApiClient from './core/network/client';
import { Guard, Guarded, MaybeArray } from './util';
import { Guard, Guarded, MaybeArray } from './core/helpers/util';
import Telegram from './telegram';

@@ -32,16 +32,16 @@ import { FmtString } from './format';

get tg(): Telegram;
get message(): PropOr<U, "message", undefined>;
get editedMessage(): PropOr<U, "edited_message", undefined>;
get inlineQuery(): PropOr<U, "inline_query", undefined>;
get shippingQuery(): PropOr<U, "shipping_query", undefined>;
get preCheckoutQuery(): PropOr<U, "pre_checkout_query", undefined>;
get chosenInlineResult(): PropOr<U, "chosen_inline_result", undefined>;
get channelPost(): PropOr<U, "channel_post", undefined>;
get editedChannelPost(): PropOr<U, "edited_channel_post", undefined>;
get callbackQuery(): PropOr<U, "callback_query", undefined>;
get poll(): PropOr<U, "poll", undefined>;
get pollAnswer(): PropOr<U, "poll_answer", undefined>;
get myChatMember(): PropOr<U, "my_chat_member", undefined>;
get chatMember(): PropOr<U, "chat_member", undefined>;
get chatJoinRequest(): PropOr<U, "chat_join_request", undefined>;
get message(): PropOr<U, "message">;
get editedMessage(): PropOr<U, "edited_message">;
get inlineQuery(): PropOr<U, "inline_query">;
get shippingQuery(): PropOr<U, "shipping_query">;
get preCheckoutQuery(): PropOr<U, "pre_checkout_query">;
get chosenInlineResult(): PropOr<U, "chosen_inline_result">;
get channelPost(): PropOr<U, "channel_post">;
get editedChannelPost(): PropOr<U, "edited_channel_post">;
get callbackQuery(): PropOr<U, "callback_query">;
get poll(): PropOr<U, "poll">;
get pollAnswer(): PropOr<U, "poll_answer">;
get myChatMember(): PropOr<U, "my_chat_member">;
get chatMember(): PropOr<U, "chat_member">;
get chatJoinRequest(): PropOr<U, "chat_join_request">;
get chat(): Getter<U, 'chat'>;

@@ -88,3 +88,3 @@ get senderChat(): PropOr<GetUpdateContent<U>, "sender_chat", undefined>;

*/
editMessageText(text: string, extra?: tt.ExtraEditMessageText): Promise<true | (tg.Update.Edited & tg.Message.TextMessage)>;
editMessageText(text: string | FmtString, extra?: tt.ExtraEditMessageText): Promise<true | (tg.Update.Edited & tg.Message.TextMessage)>;
/**

@@ -483,2 +483,12 @@ * @see https://core.telegram.org/bots/api#editmessagecaption

/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator
* right in the supergroup.
*
* @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
*
* @see https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
*/
unpinAllGeneralForumTopicMessages(): Promise<true>;
/**
* @deprecated use {@link Telegram.setStickerPositionInSet}

@@ -489,6 +499,13 @@ * @see https://core.telegram.org/bots/api#setstickerpositioninset

/**
* @deprecated use {@link Telegram.setStickerSetThumb}
* @see https://core.telegram.org/bots/api#setstickersetthumb
* @deprecated use {@link Telegram.setStickerSetThumbnail}
* @see https://core.telegram.org/bots/api#setstickersetthumbnail
*/
setStickerSetThumb(...args: Parameters<Telegram['setStickerSetThumb']>): Promise<true>;
setStickerSetThumb(...args: Parameters<Telegram['setStickerSetThumbnail']>): Promise<true>;
setStickerSetThumbnail(...args: Parameters<Telegram['setStickerSetThumbnail']>): Promise<true>;
setStickerMaskPosition(...args: Parameters<Telegram['setStickerMaskPosition']>): Promise<true>;
setStickerKeywords(...args: Parameters<Telegram['setStickerKeywords']>): Promise<true>;
setStickerEmojiList(...args: Parameters<Telegram['setStickerEmojiList']>): Promise<true>;
deleteStickerSet(...args: Parameters<Telegram['deleteStickerSet']>): Promise<true>;
setStickerSetTitle(...args: Parameters<Telegram['setStickerSetTitle']>): Promise<true>;
setCustomEmojiStickerSetThumbnail(...args: Parameters<Telegram['setCustomEmojiStickerSetThumbnail']>): Promise<true>;
/**

@@ -495,0 +512,0 @@ * @deprecated use {@link Telegram.deleteStickerFromSet}

@@ -1,2 +0,2 @@

import { MessageEntity, User } from 'typegram';
import { MessageEntity, User } from '@telegraf/types';
export interface FmtString {

@@ -24,3 +24,2 @@ text: string;

export declare const join: (fragments: Iterable<FmtString | string | Any>, separator?: string | FmtString) => FmtString;
export declare const replace: (source: string, search: string | RegExp, value: string | FmtString) => FmtString;
/** Internal constructor for all fmt helpers */

@@ -27,0 +26,0 @@ export declare function _fmt(kind?: Types.Containers): (parts: TemplateParts, ...items: (Any | FmtString)[]) => FmtString;

/// <reference types="node" />
/// <reference types="node" />
import { Typegram } from 'typegram';
export * from 'typegram/api';
export * from 'typegram/markup';
export * from 'typegram/menu-button';
export * from 'typegram/inline';
export * from 'typegram/manage';
export * from 'typegram/message';
export * from 'typegram/passport';
export * from 'typegram/payment';
export * from 'typegram/update';
import * as Typegram from '@telegraf/types';
export * from '@telegraf/types/api';
export * from '@telegraf/types/inline';
export * from '@telegraf/types/manage';
export * from '@telegraf/types/markup';
export * from '@telegraf/types/message';
export * from '@telegraf/types/methods';
export * from '@telegraf/types/passport';
export * from '@telegraf/types/payment';
export * from '@telegraf/types/settings';
export * from '@telegraf/types/update';
interface InputFileByPath {

@@ -30,11 +31,10 @@ source: string;

export type InputFile = InputFileByPath | InputFileByReadableStream | InputFileByBuffer | InputFileByURL;
type TelegrafTypegram = Typegram<InputFile>;
export type Telegram = TelegrafTypegram['Telegram'];
export type Opts<M extends keyof Telegram> = TelegrafTypegram['Opts'][M];
export type InputMedia = TelegrafTypegram['InputMedia'];
export type InputMediaPhoto = TelegrafTypegram['InputMediaPhoto'];
export type InputMediaVideo = TelegrafTypegram['InputMediaVideo'];
export type InputMediaAnimation = TelegrafTypegram['InputMediaAnimation'];
export type InputMediaAudio = TelegrafTypegram['InputMediaAudio'];
export type InputMediaDocument = TelegrafTypegram['InputMediaDocument'];
export type Telegram = Typegram.ApiMethods<InputFile>;
export type Opts<M extends keyof Telegram> = Typegram.Opts<InputFile>[M];
export type InputMedia = Typegram.InputMedia<InputFile>;
export type InputMediaPhoto = Typegram.InputMediaPhoto<InputFile>;
export type InputMediaVideo = Typegram.InputMediaVideo<InputFile>;
export type InputMediaAnimation = Typegram.InputMediaAnimation<InputFile>;
export type InputMediaAudio = Typegram.InputMediaAudio<InputFile>;
export type InputMediaDocument = Typegram.InputMediaDocument<InputFile>;
export type ChatAction = Opts<'sendChatAction'>['action'];

@@ -41,0 +41,0 @@ /**

@@ -1,2 +0,2 @@

import type { CallbackQuery, CommonMessageBundle, Message, Update } from 'typegram';
import type { CallbackQuery, CommonMessageBundle, Message, Update } from '@telegraf/types';
import type { Deunionize, UnionKeys } from './deunionize';

@@ -6,6 +6,6 @@ type DistinctKeys<T extends object> = Exclude<UnionKeys<T>, keyof T>;

export type Filter<U extends Update> = (update: Update) => update is U;
export declare const message: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "animation" | "reply_markup" | "audio" | "document" | "photo" | "sticker" | "video" | "video_note" | "voice" | "poll" | "channel_chat_created" | "chat_shared" | "connected_website" | "delete_chat_photo" | "group_chat_created" | "invoice" | "left_chat_member" | "message_auto_delete_timer_changed" | "migrate_from_chat_id" | "migrate_to_chat_id" | "new_chat_members" | "new_chat_photo" | "new_chat_title" | "passport_data" | "proximity_alert_triggered" | "forum_topic_created" | "forum_topic_closed" | "forum_topic_reopened" | "pinned_message" | "successful_payment" | "supergroup_chat_created" | "user_shared" | "video_chat_scheduled" | "video_chat_started" | "video_chat_ended" | "video_chat_participants_invited" | "web_app_data" | "media_group_id" | "has_media_spoiler" | "forward_from" | "forward_from_chat" | "forward_from_message_id" | "forward_signature" | "forward_sender_name" | "forward_date" | "is_automatic_forward" | "reply_to_message" | "via_bot" | "edit_date" | "has_protected_content" | "author_signature" | "contact" | "dice" | "location" | "game" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.MessageUpdate<Keyed<Message, Ks[number]>>;
export declare const editedMessage: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "animation" | "audio" | "document" | "photo" | "sticker" | "video" | "video_note" | "voice" | "poll" | "media_group_id" | "has_media_spoiler" | "contact" | "dice" | "location" | "game" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.EditedMessageUpdate<Keyed<CommonMessageBundle, Ks[number]>>;
export declare const channelPost: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "animation" | "reply_markup" | "audio" | "document" | "photo" | "sticker" | "video" | "video_note" | "voice" | "poll" | "channel_chat_created" | "chat_shared" | "connected_website" | "delete_chat_photo" | "group_chat_created" | "invoice" | "left_chat_member" | "message_auto_delete_timer_changed" | "migrate_from_chat_id" | "migrate_to_chat_id" | "new_chat_members" | "new_chat_photo" | "new_chat_title" | "passport_data" | "proximity_alert_triggered" | "forum_topic_created" | "forum_topic_closed" | "forum_topic_reopened" | "pinned_message" | "successful_payment" | "supergroup_chat_created" | "user_shared" | "video_chat_scheduled" | "video_chat_started" | "video_chat_ended" | "video_chat_participants_invited" | "web_app_data" | "media_group_id" | "has_media_spoiler" | "forward_from" | "forward_from_chat" | "forward_from_message_id" | "forward_signature" | "forward_sender_name" | "forward_date" | "is_automatic_forward" | "reply_to_message" | "via_bot" | "edit_date" | "has_protected_content" | "author_signature" | "contact" | "dice" | "location" | "game" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.ChannelPostUpdate<Keyed<Message, Ks[number]>>;
export declare const editedChannelPost: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "animation" | "audio" | "document" | "photo" | "sticker" | "video" | "video_note" | "voice" | "poll" | "media_group_id" | "has_media_spoiler" | "contact" | "dice" | "location" | "game" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.EditedChannelPostUpdate<Keyed<CommonMessageBundle, Ks[number]>>;
export declare const message: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "sticker" | "animation" | "reply_markup" | "audio" | "document" | "photo" | "video" | "video_note" | "voice" | "poll" | "media_group_id" | "has_media_spoiler" | "forward_from" | "forward_from_chat" | "forward_from_message_id" | "forward_signature" | "forward_sender_name" | "forward_date" | "is_automatic_forward" | "reply_to_message" | "via_bot" | "edit_date" | "has_protected_content" | "author_signature" | "contact" | "dice" | "location" | "channel_chat_created" | "chat_shared" | "connected_website" | "delete_chat_photo" | "group_chat_created" | "invoice" | "left_chat_member" | "message_auto_delete_timer_changed" | "migrate_from_chat_id" | "migrate_to_chat_id" | "new_chat_members" | "new_chat_photo" | "new_chat_title" | "passport_data" | "proximity_alert_triggered" | "forum_topic_created" | "forum_topic_closed" | "forum_topic_reopened" | "pinned_message" | "successful_payment" | "supergroup_chat_created" | "user_shared" | "video_chat_scheduled" | "video_chat_started" | "video_chat_ended" | "video_chat_participants_invited" | "web_app_data" | "game" | "story" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.MessageUpdate<Keyed<Message, Ks[number]>>;
export declare const editedMessage: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "sticker" | "animation" | "audio" | "document" | "photo" | "video" | "video_note" | "voice" | "poll" | "media_group_id" | "has_media_spoiler" | "contact" | "dice" | "location" | "game" | "story" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.EditedMessageUpdate<Keyed<CommonMessageBundle, Ks[number]>>;
export declare const channelPost: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "sticker" | "animation" | "reply_markup" | "audio" | "document" | "photo" | "video" | "video_note" | "voice" | "poll" | "media_group_id" | "has_media_spoiler" | "forward_from" | "forward_from_chat" | "forward_from_message_id" | "forward_signature" | "forward_sender_name" | "forward_date" | "is_automatic_forward" | "reply_to_message" | "via_bot" | "edit_date" | "has_protected_content" | "author_signature" | "contact" | "dice" | "location" | "channel_chat_created" | "chat_shared" | "connected_website" | "delete_chat_photo" | "group_chat_created" | "invoice" | "left_chat_member" | "message_auto_delete_timer_changed" | "migrate_from_chat_id" | "migrate_to_chat_id" | "new_chat_members" | "new_chat_photo" | "new_chat_title" | "passport_data" | "proximity_alert_triggered" | "forum_topic_created" | "forum_topic_closed" | "forum_topic_reopened" | "pinned_message" | "successful_payment" | "supergroup_chat_created" | "user_shared" | "video_chat_scheduled" | "video_chat_started" | "video_chat_ended" | "video_chat_participants_invited" | "web_app_data" | "game" | "story" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.ChannelPostUpdate<Keyed<Message, Ks[number]>>;
export declare const editedChannelPost: <Ks extends ("entities" | "text" | "caption" | "caption_entities" | "sticker" | "animation" | "audio" | "document" | "photo" | "video" | "video_note" | "voice" | "poll" | "media_group_id" | "has_media_spoiler" | "contact" | "dice" | "location" | "game" | "story" | "venue")[]>(...keys: Ks) => (update: Update) => update is Update.EditedChannelPostUpdate<Keyed<CommonMessageBundle, Ks[number]>>;
export declare const callbackQuery: <Ks extends ("game_short_name" | "data")[]>(...keys: Ks) => (update: Update) => update is Update.CallbackQueryUpdate<Keyed<CallbackQuery, Ks[number]>>;

@@ -12,0 +12,0 @@ export declare const either: <Us extends Update[]>(...filters: { [UIdx in keyof Us]: Filter<Us[UIdx]>; }) => (update: Update) => update is Us[number];

@@ -1,15 +0,15 @@

import { User } from 'typegram';
import { FmtString } from './core/helpers/formatting';
export declare const fmt: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
export declare const bold: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
export declare const italic: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
export declare const spoiler: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
export declare const strikethrough: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
export declare const underline: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
export declare const code: (parts: string | FmtString | readonly (string | FmtString)[], ...items: ({} | null | undefined)[]) => FmtString;
export declare const pre: (language: string) => (parts: string | FmtString | readonly (string | FmtString)[], ...items: ({} | null | undefined)[]) => FmtString;
export declare const link: (content: string | FmtString, url: string) => FmtString;
export declare const mention: (name: string | FmtString, user: number | User) => FmtString;
import { User } from '@telegraf/types';
import { FmtString, join } from './core/helpers/formatting';
export { FmtString };
export { join, replace } from './core/helpers/formatting';
declare const fmt: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
declare const bold: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
declare const italic: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
declare const spoiler: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
declare const strikethrough: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
declare const underline: (parts: string | FmtString | readonly (string | FmtString)[], ...items: (FmtString | ({} | null | undefined))[]) => FmtString;
declare const code: (parts: string | FmtString | readonly (string | FmtString)[], ...items: ({} | null | undefined)[]) => FmtString;
declare const pre: (language: string) => (parts: string | FmtString | readonly (string | FmtString)[], ...items: ({} | null | undefined)[]) => FmtString;
declare const link: (content: string | FmtString, url: string) => FmtString;
declare const mention: (name: string | FmtString, user: number | User) => FmtString;
export { fmt, bold, italic, spoiler, strikethrough, underline, code, pre, link, mention, join, };
//# sourceMappingURL=format.d.ts.map

@@ -13,4 +13,4 @@ export { Telegraf } from './telegraf';

export { deunionize } from './deunionize';
export { session, MemorySessionStore } from './session';
export { session, MemorySessionStore, SessionStore } from './session';
export * as Scenes from './scenes';
//# sourceMappingURL=index.d.ts.map

@@ -13,3 +13,3 @@ import { SessionContext } from '../session';

register(...scenes: ReadonlyArray<BaseScene<C>>): this;
middleware(): import("../middleware").MiddlewareFn<C>;
middleware(): import("..").MiddlewareFn<C>;
static enter<C extends Context & {

@@ -16,0 +16,0 @@ scene: SceneContextScene<C>;

import { Context } from './context';
import { MaybePromise } from './util';
import { ExclusiveKeys, MaybePromise } from './core/helpers/util';
import { MiddlewareFn } from './middleware';

@@ -15,9 +15,10 @@ export interface SyncSessionStore<T> {

export type SessionStore<T> = SyncSessionStore<T> | AsyncSessionStore<T>;
interface SessionOptions<S extends object, C extends Context = Context, Property extends string = 'session'> {
interface SessionOptions<S, C extends Context, P extends string> {
/** Customise the session prop. Defaults to "session" and is available as ctx.session. */
property?: P;
getSessionKey?: (ctx: C) => MaybePromise<string | undefined>;
store?: SessionStore<S>;
defaultSession?: (ctx: C) => S;
/** Defaults to `session`. If provided, property name will be used instead of `ctx.session`. */
property?: Property;
}
/** @deprecated session can use custom properties now. Construct this type directly. */
export interface SessionContext<S extends object> extends Context {

@@ -32,5 +33,5 @@ session?: S;

*
* > āš ļø Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
* > āš ļø Session data is kept only in memory by default, which means that all data will be lost when the process is terminated.
* >
* > If you want to store data across restarts, or share it among workers, you should use
* > If you want to persist data across process restarts, or share it among multiple instances, you should use
* [@telegraf/session](https://www.npmjs.com/package/@telegraf/session), or pass custom `storage`.

@@ -41,5 +42,5 @@ *

*/
export declare function session<S extends object, C extends Context = Context, P extends string = 'session'>(options?: SessionOptions<S, C, P>): MiddlewareFn<C & {
[session in P]?: S;
}>;
export declare function session<S extends NonNullable<C[P]>, C extends Context & {
[key in P]?: C[P];
}, P extends (ExclusiveKeys<C, Context> & string) | 'session' = 'session'>(options?: SessionOptions<S, C, P>): MiddlewareFn<C>;
/** @deprecated Use `Map` */

@@ -54,4 +55,5 @@ export declare class MemorySessionStore<T> implements SyncSessionStore<T> {

}
/** @deprecated session can use custom properties now. Directly use `'session' in ctx` instead */
export declare function isSessionContext<S extends object>(ctx: Context): ctx is SessionContext<S>;
export {};
//# sourceMappingURL=session.d.ts.map

@@ -7,3 +7,3 @@ /// <reference types="node" />

import { Composer } from './composer';
import { MaybePromise } from './util';
import { MaybePromise } from './core/helpers/util';
import ApiClient from './core/network/client';

@@ -10,0 +10,0 @@ import Context from './context';

/** @format */
import { Expand } from './util';
import { Expand } from './core/helpers/util';
import { Message, Opts, Telegram, Update, InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo } from './core/types/typegram';

@@ -4,0 +4,0 @@ import { UnionKeys } from './deunionize';

@@ -446,2 +446,10 @@ /// <reference types="node" />

unhideGeneralForumTopic(chat_id: number | string): Promise<true>;
/**
* Use this method to clear the list of pinned messages in a General forum topic.
* The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator
* right in the supergroup.
*
* @param chat_id Unique identifier for the target chat or username of the target supergroup (in the format @supergroupusername)
*/
unpinAllGeneralForumTopicMessages(chat_id: number | string): Promise<true>;
getStickerSet(name: string): Promise<tg.StickerSet>;

@@ -454,3 +462,3 @@ /**

*/
uploadStickerFile(ownerId: number, stickerFile: tg.Opts<'uploadStickerFile'>['png_sticker']): Promise<tg.File>;
uploadStickerFile(ownerId: number, sticker: tg.Opts<'uploadStickerFile'>['sticker'], sticker_format: tg.Opts<'uploadStickerFile'>['sticker_format']): Promise<tg.File>;
/**

@@ -475,4 +483,30 @@ * Create new sticker set owned by a user. The bot will be able to edit the created sticker set.

setStickerPositionInSet(sticker: string, position: number): Promise<true>;
setStickerSetThumb(name: string, userId: number, thumb?: tg.Opts<'setStickerSetThumb'>['thumb']): Promise<true>;
/**
* @deprecated since API 6.8. Use {@link Telegram.setStickerSetThumbnail}
*/
get setStickerSetThumb(): (name: string, userId: number, thumbnail?: string | tg.InputFile | undefined) => Promise<true>;
/**
* Use this method to set the thumbnail of a regular or mask sticker set.
* The format of the thumbnail file must match the format of the stickers in the set.
* @param name Sticker set name
* @param userId User identifier of the sticker set owner
* @param thumbnail A .WEBP or .PNG image with the thumbnail, must be up to 128 kilobytes in size
* and have a width and height of exactly 100px, or a .TGS animation with a thumbnail up to
* 32 kilobytes in size (see
* [animated sticker technical requirements](https://core.telegram.org/stickers#animated-sticker-requirements)),
* or a WEBM video with the thumbnail up to 32 kilobytes in size; see
* [video sticker technical requirements](https://core.telegram.org/stickers#video-sticker-requirements).
* Pass a file_id as a String to send a file that already exists on the Telegram servers, pass a
* HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using
* Input helpers. Animated and video sticker set thumbnails can't be uploaded via HTTP URL.
* If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.
*/
setStickerSetThumbnail(name: string, userId: number, thumbnail?: tg.Opts<'setStickerSetThumbnail'>['thumbnail']): Promise<true>;
setStickerMaskPosition(sticker: string, mask_position?: tg.MaskPosition): Promise<true>;
setStickerKeywords(sticker: string, keywords?: string[]): Promise<true>;
setStickerEmojiList(sticker: string, emoji_list: string[]): Promise<true>;
deleteStickerSet(name: string): Promise<true>;
setStickerSetTitle(name: string, title: string): Promise<true>;
setCustomEmojiStickerSetThumbnail(name: string, custom_emoji_id: string): Promise<true>;
/**
* Delete a sticker from a set created by the bot.

@@ -484,2 +518,8 @@ * @param sticker File identifier of the sticker

/**
* Change the list of the bot's commands.
* @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
*/
setMyCommands(commands: readonly tg.BotCommand[], extra?: tt.ExtraSetMyCommands): Promise<true>;
deleteMyCommands(extra?: tg.Opts<'deleteMyCommands'>): Promise<true>;
/**
* Get the current list of the bot's commands.

@@ -489,7 +529,34 @@ */

/**
* Change the list of the bot's commands.
* @param commands A list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.
* Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
* @param description New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.
*/
setMyCommands(commands: readonly tg.BotCommand[], extra?: tt.ExtraSetMyCommands): Promise<true>;
deleteMyCommands(extra?: tg.Opts<'deleteMyCommands'>): Promise<true>;
setMyDescription(description: string, language_code?: string): Promise<true>;
/**
* Use this method to change the bot's name.
* @param name New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name.
*/
setMyName(name: string, language_code?: string): Promise<true>;
/**
* Use this method to get the current bot name for the given user language.
* @param language_code A two-letter ISO 639-1 language code or an empty string
*/
getMyName(language_code?: string): Promise<tg.BotName>;
/**
* Use this method to get the current bot description for the given user language.
* @param language_code A two-letter ISO 639-1 language code.
*/
getMyDescription(language_code?: string): Promise<tg.BotDescription>;
/**
* Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot.
* @param description New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.
* @param language_code A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description.
*/
setMyShortDescription(short_description: string, language_code?: string): Promise<true>;
/**
* Use this method to get the current bot short description for the given user language.
* @param language_code A two-letter ISO 639-1 language code or an empty string
*/
getMyShortDescription(language_code?: string): Promise<tg.BotShortDescription>;
setPassportDataErrors(userId: number, errors: readonly tg.PassportElementError[]): Promise<true>;

@@ -496,0 +563,0 @@ /**

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with āš”ļø by Socket Inc