Answer class

Sends many messages, reply to the messages in middlewares

Why do you need to use the Answer class?

We recommend using return when sending a message, but there are cases where this is impossible. For example, if you are using middleware, or you need to get response from the method, you need to use Answer class

Get Answer class and use it

If you want to get the Answer class in the middleware, get it as the 2nd argument. But if you're in a handler, you can get the Answer class using the @GetAnswer parameter decorator

app.contoller.ts
import { GetAnswer, Answer, OnCommand, Controller } from 'nestgram';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService?: AppService) {}

  @OnCommand('start')
  async start(@GetAnswer() answer: Answer): Promise<void> {
    await answer.send('First message');
    await answer.send('Second message');
  }
}

More info about the Answer class

The Answer class is asynchronous. You can pass the MessageSend class as content to the Answer class too. If you're using the Answer class, you can return class-method too

app.controller.ts
import { GetAnswer, Answer, OnCommand, Controller, MessageSend } from 'nestgram';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService?: AppService) {}

  @OnCommand('start')
  async start(@GetAnswer() answer: Answer): Promise<MessageSend> {
    await answer.send(new MessageSend('First message'));
    return new MessageSend('Second message');
  }
}

Add answer class to context

If you often use the Answer class, you shouldn't use the @GetAnswer decorator in every handler. You can use the @GetAnswerContext property decorator in the controller and use it like this.answer

app.controller.ts
import { Answer, Controller, GetAnswerContext, Keyboard, KeyboardTypes, MessageSend, OnCommand } from 'nestgram';
import { AppService } from './app.service';

@Controller()
export class AppController {
  @GetAnswerContext() answer: Answer;

  constructor(private readonly appService?: AppService) {}

  @OnCommand('start')
  async start() {
    await this.answer.send('Hello, world!');
    await this.answer.send(
      new MessageSend('How are you?'),
      new Keyboard(KeyboardTypes.underTheMessage)
        .btn('Fine!', 'fine'),
    )
  }
}

You can read more about keyboard here

Last updated