Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-telegraf-decorators

Package Overview
Dependencies
Maintainers
1
Versions
25
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-telegraf-decorators - npm Package Compare versions

Comparing version 0.3.3 to 0.3.4

build/sample/controllers/SceneController.js

12

build/sample/app.js

@@ -5,6 +5,4 @@ "use strict";

var src_1 = require("../src");
var typedi_1 = require("typedi");
var bot = src_1.buildBot({
token: "<token>",
container: typedi_1.Container,
token: process.env.TOKEN,
// bot: bot bot instance

@@ -14,2 +12,8 @@ // session: session() custom session

controllers: [__dirname + '/controllers/**.ts'],
}).startPolling();
// or controllers: [ControllerTest],
});
bot
.launch()
.then(function () {
console.log('start');
});

@@ -55,4 +55,4 @@ "use strict";

var TestService_1 = require("../services/TestService");
var params_1 = require("../params");
var telegraf_1 = require("telegraf");
var params_1 = require("../params");
var ControllerTest = /** @class */ (function () {

@@ -86,3 +86,10 @@ function ControllerTest() {

};
var _a;
ControllerTest.prototype.wizardStart1 = function (ctx) {
// @ts-ignore
ctx.scene.enter("steps");
};
ControllerTest.prototype.wizardStart = function (ctx) {
// @ts-ignore
ctx.scene.enter("steps2");
};
__decorate([

@@ -96,3 +103,3 @@ typedi_1.Inject(),

__metadata("design:type", Function),
__metadata("design:paramtypes", [typeof (_a = typeof telegraf_1.ContextMessageUpdate !== "undefined" && telegraf_1.ContextMessageUpdate) === "function" ? _a : Object, Object, Object, telegraf_1.Telegram]),
__metadata("design:paramtypes", [telegraf_1.Context, Object, Object, Object]),
__metadata("design:returntype", Promise)

@@ -107,2 +114,16 @@ ], ControllerTest.prototype, "test", null);

], ControllerTest.prototype, "enter", null);
__decorate([
src_1.Hears('wizard1'),
__param(0, src_1.TFContext()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [telegraf_1.Context]),
__metadata("design:returntype", void 0)
], ControllerTest.prototype, "wizardStart1", null);
__decorate([
src_1.Hears('wizard'),
__param(0, src_1.TFContext()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [telegraf_1.Context]),
__metadata("design:returntype", void 0)
], ControllerTest.prototype, "wizardStart", null);
ControllerTest = __decorate([

@@ -109,0 +130,0 @@ src_1.TFController(),

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

var typedi_1 = require("typedi");
var src_1 = require("../../src");
var TestService = /** @class */ (function () {

@@ -82,4 +83,7 @@ function TestService() {

};
Aaaa = __decorate([
src_1.TFMiddleware()
], Aaaa);
return Aaaa;
}());
exports.Aaaa = Aaaa;
"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildFromMetadata = void 0;
var container_1 = require("./container");
exports.BotBuilder = void 0;
var telegraf_1 = require("telegraf");
var MetadataStorage_1 = require("./MetadataStorage");
var WizardScene = require('telegraf/scenes/wizard');
var Stage = require('telegraf/stage');
var Scene = require('telegraf/scenes/base');
var session = require('telegraf/session');
function buildFromMetadata(bot, options) {
var stage = options.stage || new Stage();
bot.use(options.session ? options.session : session());
bot.use(stage.middleware());
MetadataStorage_1.MetadataArgsStorage.composerMetadata
.forEach(function (controller) {
var controllerInstance = container_1.getFromContainer(controller.target);
var middlewareInstances = MetadataStorage_1.MetadataArgsStorage
.middlewareMetadata
.filter(function (value) { return value.target.prototype == controller.target.prototype; }).map(function (value) { return container_1.getFromContainer(value.middleware); });
if (controller.options.type == "controller")
buildController(bot, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "scene")
buildScene(stage, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "wizard")
buildWizard(bot, stage, controller, controllerInstance, middlewareInstances);
});
return bot;
}
exports.buildFromMetadata = buildFromMetadata;
function buildScene(stage, controllerScene, controllerInstance, middlewareInstances) {
var scene = new Scene(controllerScene.options.data.scene);
scene.use.apply(scene, middlewareInstances.map(function (value) { return function (ctx, next) {
return value.use(ctx, next);
}; }));
MetadataStorage_1.MetadataArgsStorage
.handlers
.filter(function (value) { return controllerScene.target.prototype == value.target; })
.forEach(function (handler) {
scene[handler.type].apply(scene, __spreadArrays(handler.data, [function (ctx) {
controllerInstance[handler.propertyName].apply(controllerInstance, getInjectParams(ctx, controllerScene.target, handler.propertyName));
}]));
});
stage.register(scene);
}
function buildController(bot, controller, controllerInstance, middlewareInstances) {
var _a;
var composer = new telegraf_1.Composer();
(_a = composer).use.apply(_a, middlewareInstances.map(function (value) { return function (ctx, next) {
return value.use(ctx, next);
}; }));
MetadataStorage_1.MetadataArgsStorage
.handlers
.filter(function (value) { return controller.target.prototype == value.target && value.type != "enter" && value.type != 'leave'; })
.forEach(function (handler) {
composer[handler.type].apply(composer, __spreadArrays(handler.data, [function (ctx) {
controllerInstance[handler.propertyName].apply(controllerInstance, getInjectParams(ctx, controller.target, handler.propertyName));
}]));
});
bot.use(controller.options.data.compose ? controller.options.data.compose(composer) : composer);
}
function buildWizard(bot, stage, wizard, controllerInstance, middlewareInstances) {
var group = MetadataStorage_1.MetadataArgsStorage
.wizardStep
.sort(function (a, b) { return a.step - b.step; })
.reduce(function (r, a) {
r[a.step] = r[a.step] || [];
r[a.step].push(a);
return r;
}, Object.create(null));
var steps = Object.values(group).map(function (stepsMetadata, index) {
var typedi_1 = require("typedi");
var BotBuilder = /** @class */ (function () {
function BotBuilder(bot, options) {
this.bot = bot;
this.options = options;
}
BotBuilder.prototype.buildFromMetadata = function () {
var _this = this;
var stage = this.options.stage || new telegraf_1.Scenes.Stage();
this.bot.use(this.options.session ? this.options.session : telegraf_1.session());
this.bot.use(stage.middleware());
MetadataStorage_1.MetadataArgsStorage.composerMetadata
.forEach(function (controller) {
var controllerInstance = typedi_1.Container.get(controller.target);
var middlewareInstances = MetadataStorage_1.MetadataArgsStorage
.middlewareMetadata
.filter(function (value) { return value.target.prototype == controller.target.prototype; })
.map(function (value) { return typedi_1.Container.get(value.middleware); });
if (controller.options.type == "controller")
_this.buildController(_this.bot, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "scene")
_this.buildScene(stage, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "wizard")
_this.buildWizard(_this.bot, stage, controller, controllerInstance, middlewareInstances);
});
return this.bot;
};
BotBuilder.prototype.buildScene = function (stage, controllerScene, controllerInstance, middlewareInstances) {
var _this = this;
var scene = new telegraf_1.Scenes.BaseScene(controllerScene.options.data.scene);
scene.use.apply(scene, middlewareInstances.map(function (value) { return function (ctx, next) {
return value.use(ctx, next);
}; }));
MetadataStorage_1.MetadataArgsStorage
.handlers
.filter(function (value) { return controllerScene.target.prototype == value.target; })
.forEach(function (handler) {
scene[handler.type].apply(scene, __spreadArray(__spreadArray([], handler.data), [function (ctx) {
controllerInstance[handler.propertyName].apply(controllerInstance, _this.getInjectParams(ctx, controllerScene.target, handler.propertyName));
}]));
});
stage.register(scene);
};
BotBuilder.prototype.buildController = function (bot, controller, controllerInstance, middlewareInstances) {
var _a;
var _this = this;
var composer = new telegraf_1.Composer();
var method;
stepsMetadata.forEach(function (stepMethod) {
var handlers = MetadataStorage_1.MetadataArgsStorage.handlers.filter(function (value) { return value.target == wizard.target.prototype && value.propertyName == stepMethod.propertyName; });
if (handlers.length) {
handlers.forEach(function (handler) {
composer[handler.type].apply(composer, __spreadArrays(handler.data, [function (ctx) {
return controllerInstance[handler.propertyName].apply(controllerInstance, getInjectParams(ctx, wizard.target, handler.propertyName));
}]));
});
}
else {
method = function (ctx) {
return controllerInstance[stepMethod.propertyName].apply(controllerInstance, getInjectParams(ctx, wizard.target, stepMethod.propertyName));
};
}
(_a = composer).use.apply(_a, middlewareInstances.map(function (value) { return function (ctx, next) {
return value.use(ctx, next);
}; }));
MetadataStorage_1.MetadataArgsStorage
.handlers
.filter(function (value) { return controller.target.prototype == value.target && value.type != "enter" && value.type != 'leave'; })
.forEach(function (handler) {
composer[handler.type].apply(composer, __spreadArray(__spreadArray([], handler.data), [function (ctx) {
controllerInstance[handler.propertyName].apply(controllerInstance, _this.getInjectParams(ctx, controller.target, handler.propertyName));
}]));
});
return method || composer;
});
var wizardInstance = new (WizardScene.bind.apply(WizardScene, __spreadArrays([void 0, wizard.options.data.name], steps)))();
var handlers = MetadataStorage_1.MetadataArgsStorage.handlers.filter(function (value) { return wizard.target.prototype == value.target && !MetadataStorage_1.MetadataArgsStorage.wizardStep.find(function (value1) { return value1.propertyName == value.propertyName; }); });
handlers.forEach(function (handler) {
wizardInstance[handler.type].apply(wizardInstance, __spreadArrays(handler.data, [function (ctx) {
return controllerInstance[handler.propertyName].apply(controllerInstance, getInjectParams(ctx, wizard.target, handler.propertyName));
}]));
});
stage.register(wizardInstance);
}
function getInjectParams(ctx, target, methodName) {
return MetadataStorage_1.MetadataArgsStorage
.paramMetadata
.filter(function (value) { return value.target == target.prototype && methodName === value.propertyName; })
.sort(function (a, b) { return a.index - b.index; })
.map(function (value) {
return value.foo(ctx);
});
}
bot.use(controller.options.data.compose ? controller.options.data.compose(composer) : composer);
};
BotBuilder.prototype.buildWizard = function (bot, stage, wizard, controllerInstance, middlewareInstances) {
var _a;
var _this = this;
var group = MetadataStorage_1.MetadataArgsStorage
.wizardStep
.sort(function (a, b) { return a.step - b.step; })
.reduce(function (r, a) {
r[a.step] = r[a.step] || [];
r[a.step].push(a);
return r;
}, Object.create(null));
var steps = Object.values(group)
.map(function (stepsMetadata, index) {
var composer = new telegraf_1.Composer();
var method;
stepsMetadata.forEach(function (stepMethod) {
var handlers = MetadataStorage_1.MetadataArgsStorage
.handlers
.filter(function (value) { return value.target == wizard.target.prototype && value.propertyName == stepMethod.propertyName; });
if (handlers.length) {
handlers.forEach(function (handler) {
composer[handler.type].apply(composer, __spreadArray(__spreadArray([], handler.data), [function (ctx) {
return controllerInstance[handler.propertyName].apply(controllerInstance, _this.getInjectParams(ctx, wizard.target, handler.propertyName));
}]));
});
}
else {
method = function (ctx) {
return controllerInstance[stepMethod.propertyName].apply(controllerInstance, _this.getInjectParams(ctx, wizard.target, stepMethod.propertyName));
};
}
});
return method || composer;
});
var wizardInstance = new ((_a = telegraf_1.Scenes.WizardScene).bind.apply(_a, __spreadArray([void 0, wizard.options.data.name], steps)))();
var handlers = MetadataStorage_1.MetadataArgsStorage
.handlers
.filter(function (value) { return wizard.target.prototype == value.target && !MetadataStorage_1.MetadataArgsStorage.wizardStep.find(function (value1) { return value1.propertyName == value.propertyName; }); });
handlers.forEach(function (handler) {
wizardInstance[handler.type].apply(wizardInstance, __spreadArray(__spreadArray([], handler.data), [function (ctx) {
return controllerInstance[handler.propertyName].apply(controllerInstance, _this.getInjectParams(ctx, wizard.target, handler.propertyName));
}]));
});
stage.register(wizardInstance);
};
BotBuilder.prototype.getInjectParams = function (ctx, target, methodName) {
return MetadataStorage_1.MetadataArgsStorage
.paramMetadata
.filter(function (value) { return value.target == target.prototype && methodName === value.propertyName; })
.sort(function (a, b) { return a.index - b.index; })
.map(function (value) {
return value.foo(ctx);
});
};
return BotBuilder;
}());
exports.BotBuilder = BotBuilder;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createParamDecorator = exports.TFMessage = exports.TFChat = exports.TFTelegram = exports.TFContext = exports.Leave = exports.GameQuery = exports.InlineQuery = exports.Action = exports.Enter = exports.Command = exports.Hears = exports.On = exports.Help = exports.Cashtag = exports.Hashtag = exports.Phone = exports.Mention = exports.Entity = exports.Settings = exports.Start = exports.Composer = exports.TFWizard = exports.TFWizardStep = exports.TFScene = exports.TFController = exports.UseMiddleware = void 0;
exports.createParamDecorator = exports.TFMessage = exports.TFChat = exports.TFTelegram = exports.TFContext = exports.Leave = exports.GameQuery = exports.InlineQuery = exports.Action = exports.Enter = exports.Command = exports.Hears = exports.On = exports.Help = exports.Cashtag = exports.Hashtag = exports.Phone = exports.Mention = exports.Entity = exports.Settings = exports.Start = exports.Composer = exports.TFWizard = exports.TFMiddleware = exports.TFWizardStep = exports.TFScene = exports.TFController = exports.UseMiddleware = void 0;
var ParamsMetadata_1 = require("./metadata/ParamsMetadata");

@@ -8,2 +8,3 @@ var ComposerMetadata_1 = require("./metadata/ComposerMetadata");

var MetadataStorage_1 = require("./MetadataStorage");
var typedi_1 = require("typedi");
function UseMiddleware() {

@@ -15,2 +16,3 @@ var middlewares = [];

return function (target) {
typedi_1.Service()(target);
middlewares.forEach(function (value) {

@@ -24,2 +26,3 @@ MetadataStorage_1.MetadataArgsStorage.middlewareMetadata.push({ middleware: value, target: target, type: "class" });

return function (target, propertyKey, descriptor) {
typedi_1.Service()(target, propertyKey, descriptor);
Composer({

@@ -37,2 +40,3 @@ type: "controller",

return function (target, propertyKey, descriptor) {
typedi_1.Service()(target, propertyKey, descriptor);
Composer({

@@ -55,4 +59,6 @@ type: "scene",

exports.TFWizardStep = TFWizardStep;
exports.TFMiddleware = typedi_1.Service;
function TFWizard(name) {
return function (target, propertyKey, descriptor) {
typedi_1.Service()(target, propertyKey, descriptor);
Composer({

@@ -70,2 +76,3 @@ type: "wizard",

return function (target, propertyKey, descriptor) {
typedi_1.Service()(target, propertyKey, descriptor);
MetadataStorage_1.MetadataArgsStorage.composerMetadata.push(new ComposerMetadata_1.ComposerMetadata(target, options));

@@ -186,2 +193,3 @@ return descriptor;

return function (target, propertyKey, descriptor) {
console.log(propertyKey);
MetadataStorage_1.MetadataArgsStorage.handlers.push({

@@ -188,0 +196,0 @@ propertyName: propertyKey,

@@ -14,12 +14,11 @@ "use strict";

exports.buildBot = void 0;
var path = require("path");
var telegraf_1 = require("telegraf");
var path = require("path");
var typedi_1 = require("typedi");
var builder_1 = require("./builder");
var container_1 = require("./container");
var glob = require("glob");
function buildBot(options) {
if (options.container)
container_1.useContainer(options.container);
var bot = options.bot || new telegraf_1.default(options.token);
container_1.getContainer().set(telegraf_1.default, bot);
// if (options.container) useContainer(options.container)
var bot = options.bot || new telegraf_1.Telegraf(options.token);
typedi_1.Container.set(telegraf_1.Telegraf, bot);
if (!options.controllers.every(function (value) { return value instanceof Function; }))

@@ -29,3 +28,4 @@ options.controllers.forEach(function (value) { return glob.sync(path.normalize(value)).filter(function (file) {

}).forEach(function (dir) { return require(dir); }); });
return builder_1.buildFromMetadata(bot, options);
var builder = new builder_1.BotBuilder(bot, options);
return builder.buildFromMetadata();
}

@@ -32,0 +32,0 @@ exports.buildBot = buildBot;

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

this.handlers = [];
this.handlersTo = [];
this.paramMetadata = [];

@@ -15,2 +16,3 @@ this.composerMetadata = [];

this.handlers = [];
this.handlersTo = [];
this.paramMetadata = [];

@@ -17,0 +19,0 @@ this.composerMetadata = [];

import { TestService } from "../services/TestService";
import { Chat, IncomingMessage } from 'telegraf/typings/telegram-types';
import { ContextMessageUpdate, Telegram } from "telegraf";
import { Context } from "telegraf";
export declare class ControllerTest {
service: TestService;
test(ctx: ContextMessageUpdate, msg: IncomingMessage, chat: Chat, telegram: Telegram): Promise<void>;
test(ctx: Context, msg: any, chat: any, telegram: any): Promise<void>;
enter(ctx: any, user: any): Promise<void>;
wizardStart1(ctx: Context): void;
wizardStart(ctx: Context): void;
}
import { IBotOptions } from "./interfaces/IBotOptions";
export declare function buildFromMetadata(bot: any, options: IBotOptions): any;
import { Telegraf } from "telegraf";
import { ComposerMetadata } from "./metadata/ComposerMetadata";
import { TFIMiddleware } from "./TFIMiddleware";
export declare class BotBuilder {
private readonly bot;
private readonly options;
constructor(bot: Telegraf, options: IBotOptions);
buildFromMetadata(): Telegraf;
buildScene(stage: any, controllerScene: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]): void;
buildController(bot: any, controller: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]): void;
buildWizard(bot: any, stage: any, wizard: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]): void;
getInjectParams(ctx: any, target: Function, methodName: string): any[];
}
import * as tt from "telegraf/typings/telegram-types";
import { ComposerOptions } from "./metadata/ComposerMetadata";
import { Composer as Comp, Context, ContextMessageUpdate } from "telegraf";
import { Composer as Comp, Context } from "telegraf";
import { TFIMiddleware } from "./TFIMiddleware";
import { Service } from "typedi";
export declare function UseMiddleware(...middlewares: {

@@ -11,2 +12,3 @@ new (...args: any[]): TFIMiddleware;

export declare function TFWizardStep(step: number): Function;
export declare const TFMiddleware: typeof Service;
export declare function TFWizard(name?: string): Function;

@@ -22,3 +24,3 @@ export declare function Composer(options: ComposerOptions): Function;

export declare function Help(): Function;
export declare function On(event: tt.UpdateType | tt.UpdateType[] | tt.MessageSubTypes | tt.MessageSubTypes[]): Function;
export declare function On<T extends tt.UpdateType | tt.MessageSubType>(event: T | T[]): Function;
export declare function Hears(match: string | RegExp): Function;

@@ -35,2 +37,2 @@ export declare function Command(command: string): Function;

export declare const TFMessage: () => (target: any, propertyKey: string, parameterIndex: number) => void;
export declare function createParamDecorator(foo: (ctx: Context | ContextMessageUpdate) => any): () => (target: any, propertyKey: string, parameterIndex: number) => void;
export declare function createParamDecorator(foo: (ctx: Context) => any): () => (target: any, propertyKey: string, parameterIndex: number) => void;
import { IBotOptions } from "./interfaces/IBotOptions";
export declare function buildBot(options: IBotOptions): any;
import { Telegraf } from "telegraf";
export declare function buildBot(options: IBotOptions): Telegraf;
export * from './decorators';

@@ -4,0 +5,0 @@ export * from './interfaces/IBotOptions';

@@ -1,5 +0,3 @@

import { Container } from "../container";
export interface IBotOptions {
bot?: any;
container?: Container;
token?: string;

@@ -6,0 +4,0 @@ session?: any;

@@ -8,2 +8,5 @@ import { ParamsMetadata } from "./metadata/ParamsMetadata";

handlers: HandlerMetadata[];
handlersTo: (HandlerMetadata & {
to: string;
})[];
paramMetadata: ParamsMetadata[];

@@ -10,0 +13,0 @@ composerMetadata: ComposerMetadata[];

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

import { Context, ContextMessageUpdate } from "telegraf";
import { Context } from "telegraf";
export interface TFIMiddleware {
use(ctx: ContextMessageUpdate | Context, next: (...args: any[]) => Promise<any>): any;
use(ctx: Context, next: (...args: any[]) => Promise<any>): any;
}
{
"name": "ts-telegraf-decorators",
"version": "0.3.3",
"version": "0.3.4",
"author": "Ivan Surkov <panarama360@gmail.com>",

@@ -10,3 +10,4 @@ "main": "build/src/index.js",

"test": "jest",
"example": "ts-node sample/app.ts"
"example": "ts-node sample/app.ts",
"prepublish": "tsc"
},

@@ -26,13 +27,14 @@ "keywords": [

"dependencies": {
"glob": "^7.1.6",
"glob": "^7.1.7",
"reflect-metadata": "^0.1.13",
"telegraf": "^3.38.0",
"typedi": "^0.8.0"
"telegraf": "^4.3.0",
"typedi": "^0.10.0"
},
"devDependencies": {
"@types/jest": "26.0.16",
"jest": "26.6.3",
"ts-jest": "26.4.4",
"typescript": "4.1.2"
"@types/jest": "26.0.23",
"jest": "27.0.4",
"ts-jest": "27.0.3",
"ts-node-dev": "^1.1.6",
"typescript": "4.3.2"
}
}
import 'reflect-metadata'
import {buildBot, MetadataArgsStorage} from "../src";
import {Container} from "typedi";
const bot = buildBot({
token: "<token>",
container: Container,
token: process.env.TOKEN,
// bot: bot bot instance

@@ -13,2 +11,9 @@ // session: session() custom session

// or controllers: [ControllerTest],
}).startPolling()
});
bot
.launch()
.then(() => {
console.log('start')
});
import {Hears, Help, TFChat, TFContext, TFController, TFMessage, TFTelegram, UseMiddleware} from '../../src/'
import {Inject} from "typedi";
import {Aaaa, TestService} from "../services/TestService";
import {Chat, IncomingMessage} from 'telegraf/typings/telegram-types';
import {ContextMessageUpdate, Telegram} from "telegraf";
import {CurrentUser} from "../params";
import {Context, Scenes} from "telegraf";

@@ -18,3 +17,3 @@

@Hears('test')
async test(@TFContext()ctx: ContextMessageUpdate, @TFMessage()msg: IncomingMessage, @TFChat()chat: Chat, @TFTelegram() telegram: Telegram) {
async test(@TFContext()ctx: Context, @TFMessage()msg: any, @TFChat()chat: any, @TFTelegram() telegram: any) {
console.log('Hello');

@@ -29,2 +28,14 @@ ctx.reply('Hello');

}
@Hears('wizard1')
wizardStart1(@TFContext()ctx: Context){
// @ts-ignore
ctx.scene.enter("steps")
}
@Hears('wizard')
wizardStart(@TFContext()ctx: Context){
// @ts-ignore
ctx.scene.enter("steps2")
}
}
import {Service} from "typedi";
import {TFIMiddleware} from "../../src/TFIMiddleware";
import {Context, ContextMessageUpdate} from "telegraf";
import {Context} from "telegraf";
import {TFMiddleware} from "../../src";

@@ -12,3 +13,3 @@ @Service()

}
@TFMiddleware()
export class Aaaa implements TFIMiddleware{

@@ -15,0 +16,0 @@ async use(ctx: Context, next: (...args: any[]) => Promise<any>) {

import {IBotOptions} from "./interfaces/IBotOptions";
import {getFromContainer} from "./container";
import {Composer} from "telegraf";
import {Composer, session, Telegraf, Scenes} from "telegraf";

@@ -10,116 +9,120 @@

import {TFIMiddleware} from "./TFIMiddleware";
import {Container} from "typedi";
const WizardScene = require('telegraf/scenes/wizard')
const Stage = require('telegraf/stage')
const Scene = require('telegraf/scenes/base')
const session = require('telegraf/session')
export class BotBuilder {
constructor(private readonly bot: Telegraf, private readonly options: IBotOptions) {
}
export function buildFromMetadata(bot: any, options: IBotOptions): any {
const stage = options.stage || new Stage();
buildFromMetadata(): Telegraf {
const stage = this.options.stage || new Scenes.Stage();
this.bot.use(this.options.session ? this.options.session : session());
this.bot.use(stage.middleware());
MetadataArgsStorage.composerMetadata
.forEach(controller => {
const controllerInstance = Container.get(controller.target)
const middlewareInstances = MetadataArgsStorage
.middlewareMetadata
.filter(value => value.target.prototype == controller.target.prototype)
.map(value => Container.get<TFIMiddleware>(value.middleware));
if (controller.options.type == "controller")
this.buildController(this.bot, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "scene")
this.buildScene(stage, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "wizard")
this.buildWizard(this.bot, stage, controller, controllerInstance, middlewareInstances);
});
bot.use(options.session ? options.session : session())
return this.bot;
}
bot.use(stage.middleware())
buildScene(stage: any, controllerScene: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]) {
const scene = new Scenes.BaseScene(controllerScene.options.data.scene);
scene.use(...middlewareInstances.map(value => (ctx, next) => {
return value.use(ctx, next);
}));
MetadataArgsStorage
.handlers
.filter(value => controllerScene.target.prototype == value.target)
.forEach(handler => {
scene[handler.type](...[...handler.data, (ctx) => {
controllerInstance[handler.propertyName](...this.getInjectParams(ctx, controllerScene.target, handler.propertyName));
}])
});
stage.register(scene);
}
MetadataArgsStorage.composerMetadata
.forEach(controller => {
const controllerInstance = getFromContainer(controller.target)
const middlewareInstances = MetadataArgsStorage
.middlewareMetadata
.filter(value => value.target.prototype == controller.target.prototype).map(value => getFromContainer<TFIMiddleware>(value.middleware));
if (controller.options.type == "controller")
buildController(bot, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "scene")
buildScene(stage, controller, controllerInstance, middlewareInstances);
else if (controller.options.type == "wizard")
buildWizard(bot, stage, controller, controllerInstance, middlewareInstances)
});
buildController(bot: any, controller: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]) {
const composer = new Composer();
(composer as any).use(...middlewareInstances.map(value => (ctx, next) => {
return value.use(ctx, next);
}));
MetadataArgsStorage
.handlers
.filter(value => controller.target.prototype == value.target && value.type != "enter" && value.type != 'leave')
.forEach(handler => {
composer[handler.type](...[...handler.data, (ctx) => {
controllerInstance[handler.propertyName](...this.getInjectParams(ctx, controller.target, handler.propertyName));
}])
});
bot.use(controller.options.data.compose ? controller.options.data.compose(composer) : composer);
}
return bot;
}
buildWizard(bot: any, stage: any, wizard: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]) {
const group = MetadataArgsStorage
.wizardStep
.sort((a, b) => a.step - b.step)
.reduce(function (r, a) {
r[a.step] = r[a.step] || [];
r[a.step].push(a);
return r;
}, Object.create(null));
function buildScene(stage: any, controllerScene: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]) {
const scene = new Scene(controllerScene.options.data.scene);
scene.use(...middlewareInstances.map(value => (ctx, next)=>{
return value.use(ctx, next);
}));
MetadataArgsStorage
.handlers
.filter(value => controllerScene.target.prototype == value.target)
.forEach(handler => {
scene[handler.type](...[...handler.data, (ctx) => {
controllerInstance[handler.propertyName](...getInjectParams(ctx, controllerScene.target, handler.propertyName));
}])
});
stage.register(scene);
}
function buildController(bot: any, controller: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]) {
const composer = new Composer();
(composer as any).use(...middlewareInstances.map(value => (ctx, next)=>{
return value.use(ctx, next);
}));
MetadataArgsStorage
.handlers
.filter(value => controller.target.prototype == value.target && value.type != "enter" && value.type != 'leave')
.forEach(handler => {
composer[handler.type](...[...handler.data, (ctx) => {
controllerInstance[handler.propertyName](...getInjectParams(ctx, controller.target, handler.propertyName));
}])
});
bot.use(controller.options.data.compose ? controller.options.data.compose(composer) : composer);
}
function buildWizard(bot: any, stage: any, wizard: ComposerMetadata, controllerInstance: any, middlewareInstances: TFIMiddleware[]) {
const group = MetadataArgsStorage
.wizardStep
.sort((a, b) => a.step - b.step)
.reduce(function (r, a) {
r[a.step] = r[a.step] || [];
r[a.step].push(a);
return r;
}, Object.create(null));
const steps = Object.values(group).map((stepsMetadata: WizardMetadata[], index) => {
const composer = new Composer();
let method;
stepsMetadata.forEach(stepMethod => {
const handlers = MetadataArgsStorage.handlers.filter(value => value.target == wizard.target.prototype && value.propertyName == stepMethod.propertyName);
if (handlers.length) {
handlers.forEach(handler => {
composer[handler.type](...[...handler.data, (ctx) => {
return controllerInstance[handler.propertyName](...getInjectParams(ctx, wizard.target, handler.propertyName));
}])
const steps = Object.values(group)
.map((stepsMetadata: WizardMetadata[], index) => {
const composer = new Composer();
let method;
stepsMetadata.forEach(stepMethod => {
const handlers = MetadataArgsStorage
.handlers
.filter(value => value.target == wizard.target.prototype && value.propertyName == stepMethod.propertyName)
if (handlers.length) {
handlers.forEach(handler => {
composer[handler.type](...[...handler.data, (ctx) => {
return controllerInstance[handler.propertyName](...this.getInjectParams(ctx, wizard.target, handler.propertyName));
}])
})
} else {
method = (ctx) => {
return controllerInstance[stepMethod.propertyName](...this.getInjectParams(ctx, wizard.target, stepMethod.propertyName));
}
}
})
} else {
method = (ctx) => {
return controllerInstance[stepMethod.propertyName](...getInjectParams(ctx, wizard.target, stepMethod.propertyName));
}
}
})
return method || composer;
})
return method || composer;
})
const wizardInstance = new WizardScene(wizard.options.data.name, ...steps);
const handlers = MetadataArgsStorage.handlers.filter(value => wizard.target.prototype == value.target && !MetadataArgsStorage.wizardStep.find(value1 => value1.propertyName == value.propertyName))
handlers.forEach(handler => {
wizardInstance[handler.type](...[...handler.data, (ctx) => {
return controllerInstance[handler.propertyName](...getInjectParams(ctx, wizard.target, handler.propertyName));
}])
});
stage.register(wizardInstance);
}
const wizardInstance = new Scenes.WizardScene(wizard.options.data.name, ...steps);
const handlers = MetadataArgsStorage
.handlers
.filter(value => wizard.target.prototype == value.target && !MetadataArgsStorage.wizardStep.find(value1 => value1.propertyName == value.propertyName))
handlers.forEach(handler => {
wizardInstance[handler.type](...[...handler.data, (ctx) => {
return controllerInstance[handler.propertyName](...this.getInjectParams(ctx, wizard.target, handler.propertyName));
}])
});
stage.register(wizardInstance);
}
function getInjectParams(ctx: any, target: Function, methodName: string): any[] {
getInjectParams(ctx: any, target: Function, methodName: string): any[] {
return MetadataArgsStorage
.paramMetadata
.filter(value => value.target == target.prototype && methodName === value.propertyName)
.sort((a, b) => a.index - b.index)
.map(value => {
return value.foo(ctx);
})
}
return MetadataArgsStorage
.paramMetadata
.filter(value => value.target == target.prototype && methodName === value.propertyName)
.sort((a, b) => a.index - b.index)
.map(value => {
return value.foo(ctx);
})
}

@@ -5,8 +5,11 @@ import * as tt from "telegraf/typings/telegram-types";

import {WizardStepMetadata} from "./metadata/WizardStepMetadata";
import {Composer as Comp, Context, ContextMessageUpdate} from "telegraf";
import {Composer as Comp, Context} from "telegraf";
import {MetadataArgsStorage} from "./MetadataStorage";
import {TFIMiddleware} from "./TFIMiddleware";
import {Service} from "typedi";
export function UseMiddleware(...middlewares: {new (...args: any[]): TFIMiddleware}[]): ClassDecorator {
return target => {
Service()(target)
middlewares.forEach(value => {

@@ -20,2 +23,3 @@ MetadataArgsStorage.middlewareMetadata.push({middleware:value, target: target, type: "class"})

return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
Service()(target, propertyKey, descriptor)
Composer({

@@ -33,3 +37,3 @@ type: "controller",

return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
Service()(target, propertyKey, descriptor)
Composer({

@@ -51,5 +55,7 @@ type: "scene",

}
export const TFMiddleware = Service;
export function TFWizard(name?: string): Function {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
Service()(target, propertyKey, descriptor)
Composer({

@@ -67,2 +73,3 @@ type: "wizard",

return function (target: Function, propertyKey: string, descriptor: PropertyDescriptor) {
Service()(target, propertyKey, descriptor)
MetadataArgsStorage.composerMetadata.push(new ComposerMetadata(target, options))

@@ -172,5 +179,4 @@ return descriptor;

export function On(event: tt.UpdateType | tt.UpdateType[] | tt.MessageSubTypes | tt.MessageSubTypes[]): Function {
export function On<T extends tt.UpdateType | tt.MessageSubType>(event: T | T[]): Function {
return function (target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
MetadataArgsStorage.handlers.push({

@@ -188,2 +194,3 @@ propertyName: propertyKey,

return function (target: Object, propertyKey: string, descriptor: PropertyDescriptor) {
console.log(propertyKey)
MetadataArgsStorage.handlers.push({

@@ -289,3 +296,3 @@ propertyName: propertyKey,

export function createParamDecorator(foo: (ctx: Context | ContextMessageUpdate)=>any){
export function createParamDecorator(foo: (ctx: Context)=>any){
return () => (target: any, propertyKey: string, parameterIndex: number) => {

@@ -292,0 +299,0 @@ MetadataArgsStorage.paramMetadata.push(new ParamsMetadata(target, propertyKey, parameterIndex, foo));

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

import Telegraf from 'telegraf'
import * as path from "path";
import {buildFromMetadata} from "./builder";
import {IBotOptions} from "./interfaces/IBotOptions";
import {getContainer, useContainer} from "./container";
import {Telegraf} from "telegraf";
import {Container} from "typedi";
import {BotBuilder} from "./builder";
const glob = require("glob");
export function buildBot(options: IBotOptions) {
if (options.container) useContainer(options.container)
export function buildBot(options: IBotOptions): Telegraf{
// if (options.container) useContainer(options.container)
let bot = options.bot || new Telegraf(options.token)
getContainer().set(Telegraf, bot);
Container.set(Telegraf, bot);
if (!(options.controllers as any[]).every(value => value instanceof Function))

@@ -17,4 +17,4 @@ (options.controllers as string[]).forEach(value => glob.sync(path.normalize(value)).filter(file =>

).forEach(dir => require(dir)))
return buildFromMetadata(bot, options);
const builder = new BotBuilder(bot, options);
return builder.buildFromMetadata();
}

@@ -21,0 +21,0 @@

@@ -1,6 +0,3 @@

import {Container} from "../container";
export interface IBotOptions {
bot?: any,
container?: Container,
token?: string,

@@ -7,0 +4,0 @@ session?: any,

export interface HandlerMetadata {
type: string ,
type: string,
target: Object,

@@ -5,0 +5,0 @@ propertyName: string,

@@ -10,2 +10,3 @@ import {ParamsMetadata} from "./metadata/ParamsMetadata";

public handlers: HandlerMetadata[] = [];
public handlersTo: (HandlerMetadata & {to: string})[] = [];

@@ -22,2 +23,3 @@ public paramMetadata: ParamsMetadata[] = [];

this.handlers = [];
this.handlersTo = [];
this.paramMetadata = [];

@@ -24,0 +26,0 @@ this.composerMetadata = [];

@@ -1,5 +0,5 @@

import {Context, ContextMessageUpdate} from "telegraf";
import {Context} from "telegraf";
export interface TFIMiddleware {
use(ctx: ContextMessageUpdate | Context, next: (...args: any[]) => Promise<any>);
use(ctx: Context, next: (...args: any[]) => Promise<any>);
}

@@ -15,3 +15,3 @@ import {

import {Container} from "typedi";
import Telegraf from "telegraf";
import {Telegraf} from "telegraf";

@@ -96,3 +96,3 @@ const BaseTextMessage = {

it('should provide update payload for ' + update.type, function () {
bot.handleUpdate(update.update)
bot.handleUpdate((update as any).update)
});

@@ -99,0 +99,0 @@ })

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