Socket
Socket
Sign inDemoInstall

nestgram

Package Overview
Dependencies
19
Maintainers
1
Versions
28
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.8.4 to 1.8.5

dist/classes/Scope/ScopeController.d.ts

14

dist/classes/Context/Answer.d.ts

@@ -8,5 +8,17 @@ import { Keyboard, ChatActions, ContentTypes, IAnswerCallbackQueryOptions, IForwardMessageOptions, ICopyMessageOptions, IStopMessageLiveLocationOptions, IMessage, IUpdate, IFile, IUserProfilePhotos, IMessageId, IChatPermissions, IPromoteChatPermissions, ICreateChatInviteLinkOptions, IChatInviteLink, Photo, IChat, ChatMember, IBotCommand, BotCommandScope, IChatAdministratorRights, IEditTextOptions, EditContentTypes, SendOptions, IStopPollOptions, IPoll } from '../..';

private readonly update;
api: Api;
private readonly scopeController;
readonly api: Api;
constructor(token: string, update: IUpdate);
/**
* Enter scope
* @param scopeId Scope id in which you want to enter user
* @return true on success
* */
scope(scopeId: string): Promise<true>;
/**
* Leave scope
* @return true on success
* */
unscope(): Promise<true>;
/**
* Sends a message to the chat where got update

@@ -13,0 +25,0 @@ * @param content Message data that you want to send, some media (e.g. Photo class) or string for text message

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Answer = void 0;
const __1 = require("../..");
const logger_1 = require("../../logger");

@@ -13,5 +14,27 @@ const Filter_1 = require("./Filter");

this.update = update;
this.scopeController = new __1.ScopeController();
this.api = new Api_1.Api(this.token);
}
/**
* Enter scope
* @param scopeId Scope id in which you want to enter user
* @return true on success
* */
async scope(scopeId) {
const userId = Filter_1.Filter.getUserId(this.update);
if (!userId)
throw (0, logger_1.error)(`Can't scope to ${scopeId}, can't get user id from update`);
return this.scopeController.enter(userId, scopeId);
}
/**
* Leave scope
* @return true on success
* */
async unscope() {
const userId = Filter_1.Filter.getUserId(this.update);
if (!userId)
throw (0, logger_1.error)(`Can't leave scope: can't get user id from update`);
return this.scopeController.leave(userId);
}
/**
* Sends a message to the chat where got update

@@ -18,0 +41,0 @@ * @param content Message data that you want to send, some media (e.g. Photo class) or string for text message

2

dist/classes/Helpers/ListenMiddleware.d.ts

@@ -13,4 +13,4 @@ import { NextFunction, Answer, IUpdate, MiddlewareFunction, MessageEntityTypes, MediaFileTypes } from '../..';

static message(subtype?: MessageSubtypes): MiddlewareFunction;
static click(buttonId: string): MiddlewareFunction;
static click(buttonId: string | RegExp): MiddlewareFunction;
static media(type?: MediaFileTypes): MiddlewareFunction;
}

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

return next();
if (message.text.slice(entity.offset, entity.length) !== `/${commandText}`)
if (!message.text.slice(entity.offset, entity.length).startsWith(`/${commandText}`))
return fail();

@@ -108,3 +108,9 @@ next();

return fail();
if (update.callback_query.data !== buttonId)
if (buttonId instanceof RegExp) {
const match = update.callback_query.data.match(buttonId);
if (!match)
return fail();
params._match = match;
}
else if (update.callback_query.data !== buttonId)
return fail();

@@ -111,0 +117,0 @@ next();

export * from './Context/Answer';
export * from './Context/Filter';
export * from './Scope/ScopeController';
export * from './Helpers/NestgramDefault';

@@ -4,0 +5,0 @@ export * from './Helpers/ControllerHelper';

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

__exportStar(require("./Context/Filter"), exports);
__exportStar(require("./Scope/ScopeController"), exports);
__exportStar(require("./Helpers/NestgramDefault"), exports);

@@ -21,0 +22,0 @@ __exportStar(require("./Helpers/ControllerHelper"), exports);

@@ -5,3 +5,3 @@ import { IHandler, IUpdate } from '../../types';

private readonly token;
private readonly handlers;
private readonly allHandlers;
private readonly logging?;

@@ -11,7 +11,10 @@ private readonly fileLogging?;

fileLogger: FileLogger;
constructor(token: string, handlers: IHandler[], logging?: boolean, fileLogging?: boolean, fileLoggingLimit?: number);
handlers: IHandler[];
scopes: IHandler[];
constructor(token: string, allHandlers: IHandler[], logging?: boolean, fileLogging?: boolean, fileLoggingLimit?: number);
private getNextFunction;
static getAnswerInfo(resultMessageToSend: any): [string, any[]];
private getHandlers;
private handleMiddleware;
handleUpdate(update: IUpdate): Promise<void>;
}

@@ -9,6 +9,7 @@ "use strict";

const logger_1 = require("../../logger");
const ScopeStore_1 = require("../Scope/ScopeStore");
class Handler {
constructor(token, handlers, logging, fileLogging, fileLoggingLimit) {
constructor(token, allHandlers, logging, fileLogging, fileLoggingLimit) {
this.token = token;
this.handlers = handlers;
this.allHandlers = allHandlers;
this.logging = logging;

@@ -18,2 +19,6 @@ this.fileLogging = fileLogging;

this.fileLogger = new FileLogger_1.FileLogger(this.fileLoggingLimit);
this.handlers = [];
this.scopes = [];
this.handlers = allHandlers.filter((handler) => !handler.scope) || [];
this.scopes = allHandlers.filter((handler) => !!handler.scope) || [];
}

@@ -122,4 +127,13 @@ getNextFunction(update, answer, params, middlewares, middlewareIndex, handlerIndex, handler, failFunction) {

}
getHandlers(update) {
const userId = Filter_1.Filter.getUserId(update);
if (!userId)
return this.handlers;
const current = ScopeStore_1.scopeStore.getCurrent(userId);
if (!current)
return this.handlers;
return this.scopes.filter((scope) => scope.scope === current);
}
handleMiddleware(index, update, answer, middlewareIndex = 0) {
const handler = this.handlers[index];
const handler = this.getHandlers(update)[index];
if (!handler)

@@ -156,2 +170,5 @@ return;

let resultMessageToSend;
const getAnswerKey = Reflect.getMetadata('getAnswer', handler.controller, 'answer');
if (getAnswerKey)
handler.controller[getAnswerKey] = answer;
try {

@@ -195,3 +212,3 @@ resultMessageToSend = await handlerMethod(...args);

const answer = new Answer_1.Answer(this.token, update);
const handler = this.handlers[0];
const handler = this.getHandlers(update)[0];
if (handler)

@@ -198,0 +215,0 @@ this.handleMiddleware(0, update, answer);

@@ -14,5 +14,5 @@ /// <reference types="node" />

api: Api;
server: http.Server;
handler: Handler;
server: http.Server;
constructor(token: string, handlers: IHandler[], config?: IWebhookConfig | null, logging?: boolean, fileLogging?: boolean, fileLoggingLimit?: number);
}

@@ -5,2 +5,3 @@ import 'reflect-metadata';

export * from './injection/controller.decorator';
export * from './injection/scope.decorator';
export * from './updates/update.decorators';

@@ -10,2 +11,4 @@ export * from './updates/argumets.decorator';

export * from './updates/continue.decorator';
export * from './api/api.decorator';
export * from './property/api.decorator';
export * from './property/scope-controller.decorator';
export * from './property/answer.decorator';

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

__exportStar(require("./injection/controller.decorator"), exports);
__exportStar(require("./injection/scope.decorator"), exports);
__exportStar(require("./updates/update.decorators"), exports);

@@ -26,3 +27,5 @@ __exportStar(require("./updates/argumets.decorator"), exports);

__exportStar(require("./updates/continue.decorator"), exports);
__exportStar(require("./api/api.decorator"), exports);
__exportStar(require("./property/api.decorator"), exports);
__exportStar(require("./property/scope-controller.decorator"), exports);
__exportStar(require("./property/answer.decorator"), exports);
//# sourceMappingURL=index.js.map
import { ModuleClass } from '../../types';
/**
* Creates module: part of bot
* @param options Set controllers, services, imports for module {@link ModuleClass}
* @param options Set controllers, services, imports for module. {@link ModuleClass}
* */
export declare function Module(options?: ModuleClass): Function;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Module = void 0;
const logger_1 = require("../../logger");
/**
* Creates module: part of bot
* @param options Set controllers, services, imports for module {@link ModuleClass}
* @param options Set controllers, services, imports for module. {@link ModuleClass}
* */

@@ -20,2 +21,6 @@ function Module(options = {}) {

Reflect.defineMetadata('modules', options.modules, target);
if (options.scopes)
Reflect.defineMetadata('scopes', options.scopes, target);
if (options.scopes && options.controllers)
throw (0, logger_1.error)(`You can't use controllers in the scopes module`);
return target;

@@ -22,0 +27,0 @@ };

@@ -48,3 +48,3 @@ import { MediaFileTypes, MessageEntityTypes } from '../../types';

* */
export declare const OnClick: (buttonId: string) => MethodDecorator;
export declare const OnClick: (buttonId: string | RegExp) => MethodDecorator;
/**

@@ -51,0 +51,0 @@ * Listen for a user that send some media file (e.g. photo, video, audio)

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

import { ConfigTypes, IRunConfig, IHandler, IUser } from '.';
import { ServiceClass, ConfigTypes, IRunConfig, IHandler, IUser } from '.';
import { Api } from './classes';
import { Polling } from './classes/Launch/Polling';
import { Webhook } from './classes/Launch/Webhook';
import { ScopeController } from './classes/Scope/ScopeController';
export declare class NestGram {

@@ -10,2 +11,3 @@ private readonly token;

private readonly runConfig;
scope: ScopeController;
handlers: IHandler[];

@@ -24,2 +26,3 @@ info: IUser;

constructor(token: string, module?: any, config?: ConfigTypes, runConfig?: IRunConfig);
static getServices(Module: any): Promise<ServiceClass[]>;
private setupImports;

@@ -30,3 +33,3 @@ private setupModule;

* Use an API class with a different token
* @param token Bot token you want to get api class
* @param token Bot token you want to get property class
* */

@@ -33,0 +36,0 @@ to(token: string): Api;

@@ -8,2 +8,4 @@ "use strict";

const Webhook_1 = require("./classes/Launch/Webhook");
const ScopeController_1 = require("./classes/Scope/ScopeController");
const ScopeStore_1 = require("./classes/Scope/ScopeStore");
// clear console

@@ -30,2 +32,3 @@ (0, logger_1.clear)();

this.runConfig = runConfig;
this.scope = new ScopeController_1.ScopeController();
this.handlers = [];

@@ -51,4 +54,3 @@ this.api = new classes_1.Api(this.token);

}
async setupImports(Module) {
const controllers = Reflect.getMetadata('controllers', Module);
static async getServices(Module) {
const modules = Reflect.getMetadata('modules', Module) || [];

@@ -80,20 +82,31 @@ const compiledModules = [];

});
controllers.forEach((Controller) => {
const controller = new Controller(...services);
const globalMiddlewares = Reflect.getMetadata('middlewares', Module) || [];
let methodKeys = Reflect.ownKeys(controller.__proto__);
methodKeys = methodKeys.filter((key) => typeof key === 'string');
methodKeys = methodKeys.filter((key) => key !== 'constructor');
methodKeys.forEach((methodKey) => {
const middlewares = Reflect.getMetadata('middlewares', controller[methodKey]) || [];
this.handlers.push({
controller,
methodKey,
middlewares: [...globalMiddlewares, ...middlewares],
return services;
}
async setupImports(Module) {
const controllers = Reflect.getMetadata('controllers', Module);
const services = await NestGram.getServices(Module);
const scopes = Reflect.getMetadata('scopes', Module);
ScopeStore_1.scopeStore.importScopes(Module);
if (controllers || scopes)
(controllers || scopes).forEach((Controller) => {
const controller = new Controller(...services);
const globalMiddlewares = Reflect.getMetadata('middlewares', Module) || [];
let methodKeys = Reflect.ownKeys(controller.__proto__);
methodKeys = methodKeys.filter((key) => typeof key === 'string');
methodKeys = methodKeys.filter((key) => key !== 'constructor');
methodKeys.forEach((methodKey) => {
const middlewares = Reflect.getMetadata('middlewares', controller[methodKey]) || [];
this.handlers.push({
controller,
methodKey,
middlewares: [...globalMiddlewares, ...middlewares],
...((scopes || []).includes(Controller)
? { scope: controller.constructor.name.replace('Scope', '').toLowerCase() }
: {}),
});
});
const apiKey = Reflect.getMetadata('getApi', controller, 'api');
if (apiKey)
controller[apiKey] = this.api;
});
const needApi = Reflect.getMetadata('getApi', controller, 'api');
if (needApi)
controller['api'] = this.api;
});
}

@@ -115,3 +128,3 @@ setupModule(Module) {

* Use an API class with a different token
* @param token Bot token you want to get api class
* @param token Bot token you want to get property class
* */

@@ -118,0 +131,0 @@ to(token) {

@@ -7,2 +7,4 @@ import { MiddlewareFunction } from './middleware.types';

}
export declare class ScopeClass extends ControllerClass {
}
export declare class ServiceClass {

@@ -17,2 +19,3 @@ constructor(...args: any[]);

imports?: any[];
scopes?: ScopeClass[];
}

@@ -11,2 +11,3 @@ import { ControllerClass } from './decorators.types';

methodKey: string;
scope?: string;
}

@@ -13,0 +14,0 @@ export declare type ArgsTypes = [

{
"name": "nestgram",
"description": "Framework for working with Telegram Bot API on TypeScript like Nest.js",
"version": "1.8.4",
"version": "1.8.5",
"main": "dist/index.js",

@@ -6,0 +6,0 @@ "types": "dist/index.d.ts",

@@ -7,6 +7,104 @@ # What is Nestgram?

https://degreetpro.gitbook.io/nestgram/
You can read the [guide on the official Nestgram website](https://degreetpro.gitbook.io/nestgram/getting-started/guide), on [Medium website](https://medium.com/p/ff251fb825fd) or here
## Install Nestgram
You need to install nestgram at first. You can do this using yarn or npm.
```nginx
yarn add nestgram
// or
npm i nestgram
```
## Create main file
Our next step is creating the main file, so let's create the `main.ts` file
```typescript
import { NestGram } from 'nestgram';
import { AppModule } from './app/app.module';
async function bootstrap(): Promise<void> {
const bot = new NestGram('TOKEN', AppModule);
await bot.start();
}
bootstrap();
```
At first, we imported nestgram and our AppModule, later we will create it. In the next step, we created a bootstrap function, in which we set up and run the project. The NestGram class gets bot token as 1st parameter (you can get it via [BotFather](https://t.me/BotFather)), app module as 2nd parameter, options as 3rd parameter, and [run config](https://degreetpro.gitbook.io/nestgram/advenced/webhooks-and-run-config) as 4th parameter
## Create app.module.ts
Let's create the `app.module.ts` file. In it, we will describe all available controllers and services.
```typescript
import { Module } from 'nestgram';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
controllers: [AppController],
services: [AppService],
})
export class AppModule {}
```
At first, we imported Module class from nestgram, AppController and AppService also, that we will create later. Then we described our controllers and services in @Module decorator.
## Create app.controller.ts
Let's create the `app.controller.ts` file. In it, we will describe updates, that we want to handle.
```typescript
import { OnCommand, Controller } from 'nestgram';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService?: AppService) {}
@OnCommand('start')
start(): string {
return 'Hello, world!';
}
}
```
We have created a controller where we describe an update when the user writes /start, and we handle it by sending a message "Hello, world!".
## Create app.service.ts
Let's create the `app.service.ts` file. In it, we will describe methods with working with db, that we will call in controller.
```typescript
import { Service } from 'nestgram';
@Service()
export class AppService {}
```
We can describe methods in AppService class, and call it in controller by this.appService.
## Run project
To run the project, open a terminal in the project directory and type:
```nginx
npm run dev
```
Or build and run production:
```nginx
npm run build && npm run prod
```
# What’s next?
Now you know about the syntax and structure of the Nestgram project, but if you want to write your own pro bot, you can check out the [Nestgram documentation](https://degreetpro.gitbook.io/nestgram/)
# Found a bug or have questions?
You can ask author: https://t.me/degreet

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc