robot-mafia / nestjs-telegraf

🤖 Powerful Nest module for easy and fast creation Telegram bots
https://nestjs-telegraf.0x467.com
MIT License
512 stars 88 forks source link

Migrating to Webhook #896

Closed legitimoth closed 2 years ago

legitimoth commented 2 years ago

Hello! I'm currently using nestjs-telegraf though long-polling..

I've implemented using decorators, for example:

@Start()
  async startCommand(ctx) {
    await this.cache.del(ctx.chat.id.toString());
    await ctx.telegram.sendMessage(
      ctx.chat.id,
      'Favor, informar seu CPF para iniciar o atendimento',
      MessageUtils.get(MessageCodeEnum.MENU_HIDE),
    );
  }

It work just fine. Now, I'm trying to use webhook. Using webhook I've to use @Ctx() and type it as Context :

@Post()
  public teste(@Ctx() ctx: Context) {
    console.log(ctx);
  }

The problem is: the ctx object (Context) that I receive by parameter isn't the same that I receive using long-polling.

The method ctx.telegram.sendMessage for example is expecting ExtraReplyMessage as third parameter, not a string. It's just one example, there're many others changes over ctx object when i use webook endpoint.

I'm using that ctx method over all my code i cant just change to another object class. Please I don't know what to do anymore. I'm searching about it for 2 weeks.

webpct commented 2 years ago

Hi, it's because you are trying to get an HTTP request, but you don't need it. You need only configure webhook like here, and your code base should work as it was before: https://nestjs-telegraf.vercel.app/getting-updates

legitimoth commented 2 years ago

Hi, it's because you are trying to get an HTTP request, but you don't need it. You need only configure webhook like here, and your code base should work as it was before: https://nestjs-telegraf.vercel.app/getting-updates

But what I'm suppose to set here:

  webhook: {
        domain: 'domain.tld',
        hookPath: '/secret-path',

I thought that I must create a endpoint to receive the calls and set it in domain/endpoint. If not, what should I set there when I've nothing but annotations like @on("text")

webpct commented 2 years ago

You don't need to set up endpoint on your own. You need to set launchOptions with the correct values. Note, in the hook path you could specify the full path, example bellow.

useFactory: (configService: ConfigService) => ({
    token: configService.get<string>('TELEGRAM_BOT_TOKEN'),
    launchOptions: {
      webhook: {
       hookPath: 'https://2e69-176-19-123-112.eu.ngrok.io/bot',
      }
    }
  }),

After that, in your main file, you need setup middleware, example bellow:

  const bot = app.get(getBotToken());

  app.use(bot.webhookCallback('/bot'));
  await app.listen(3000);

And after that setup, all requests that are sent to /bot, will be processed by annotations :)

legitimoth commented 2 years ago

launchOptions: { webhook: { hookPath: 'https://2e69-176-19-123-112.eu.ngrok.io/bot', } }

I tried but didn't work. My main.ts :

import { NestFactory } from '@nestjs/core';
import { AppModule } from './modules/app/modules/app.module';
import { ValidationPipe } from '@nestjs/common';
import { Swagger } from './modules/utils/swagger';
import { getBotToken } from 'nestjs-telegraf';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.setGlobalPrefix('/extrata-chatbot');
  app.enableShutdownHooks();
  app.useGlobalPipes(new ValidationPipe({ transform: true }));
  const bot = app.get(getBotToken());
  app.use(bot.webhookCallback('/extrata-chatbot'));

  Swagger.init(app);
  await app.listen(3002);
}
bootstrap();

My module:

TelegrafModule.forRootAsync({
      useFactory: async (configService: ConfigService) => ({
        token: configService.get('TELEGRAM_BOT_TOKEN'),
        launchOptions: {
          webhook: {
            hookPath:
              'https://b77e-2804-14c-65e4-8522-1550-2541-7442-7252.sa.ngrok.io/extrata-chatbot',
          },
        },
      }),
      inject: [ConfigService],
    }),

I don't know if it matters but my annotations are within services and not controllers. I don't actually have controllers.

import { On, Start, Update } from 'nestjs-telegraf';
import { Inject, Injectable } from '@nestjs/common';
import { TelegramCacheService } from './telegram-cache.service';
import { StepEnum } from '../enums/step.enum';
import { TelegramUserService } from './telegram-user.service';
import { MessageUtils } from '../utils/message.utils';
import { MessageCodeEnum } from '../enums/message-code.enum';
import { TelegramInstitutionService } from './telegram-institution.service';
import { ConfigService } from '@nestjs/config';
import { TelegramMenuService } from './telegram-menu.service';
import { TelegramOpportunitiesService } from './telegram-opportunities.service';
import { TelegramProceedingService } from './telegram-proceeding.service';
import { TelegramContactUsService } from './telegram-contact-us.service';
import { ActionsUtils } from '../utils/actions.utils';
import { ActionsEnum } from '../enums/actions.enum';

@Update()
@Injectable()
export class TelegramService {
  @Inject(TelegramCacheService)
  private readonly cache: TelegramCacheService;

  @Inject(TelegramUserService)
  private readonly userService: TelegramUserService;

  @Inject(TelegramInstitutionService)
  private readonly institutionService: TelegramInstitutionService;

  @Inject(TelegramMenuService)
  private readonly menuService: TelegramMenuService;

  @Inject(TelegramOpportunitiesService)
  private readonly opportunitiesService: TelegramOpportunitiesService;

  @Inject(TelegramProceedingService)
  private readonly proceedingMenu: TelegramProceedingService;

  @Inject(TelegramContactUsService)
  private readonly contactUsService: TelegramContactUsService;

  @Inject(ConfigService)
  private config: ConfigService;

  private success: boolean;

  @Start()
  async startCommand(ctx) {
    await this.cache.del(ctx.chat.id.toString());
    await ctx.telegram.sendMessage(
      ctx.chat.id,
      'Favor, informar seu CPF para iniciar o atendimento',
      MessageUtils.get(MessageCodeEnum.MENU_HIDE),
    );
  }

  private async completeService(ctx) {
    await ctx.reply(MessageUtils.get(MessageCodeEnum.SERVICE_COMPLETED));
    await this.startCommand(ctx);
  }

  @On('text')
  public async hears(ctx) {
    if (ctx.update.message.text == ActionsUtils.get(ActionsEnum.EXIT)) {
      await this.completeService(ctx);
      return;
    }

    const chatId = ctx.chat.id.toString();

    if (!(await this.cache.exists(chatId))) {
      await this.cache.init(ctx);
    }

    const session = await this.cache.get(chatId);

    switch (session.step) {
      case StepEnum.INITIAL:
        this.success = await this.userService.login(ctx, session);
        if (this.success) {
          session.step = StepEnum.USER_VERIFICATION;
          await this.cache.set(chatId, session);
          await this.userService.requestVerification(ctx);
        }
        break;
      case StepEnum.USER_VERIFICATION:
        await this.userService.requestVerification(ctx, true);
        break;
      case StepEnum.INSTITUTION_REQUEST:
        await this.institutionService.list(ctx, session);
        break;
      case StepEnum.INSTITUTION_PICK:
        this.success = await this.institutionService.pick(ctx, session);
        if (this.success) {
          await this.menuService.show(ctx, session);
        }
        break;
      case StepEnum.MENU_MAIN:
        await this.menuService.show(ctx, session);
        break;
      case StepEnum.MENU_MAIN_PICK:
        await this.menuService.goTo(ctx, session);
        break;
      case StepEnum.OPPORTUNITIES_MENU_PICK:
        await this.opportunitiesService.goTo(ctx, session);
        break;
      case StepEnum.OPPORTUNITIES_REQUEST:
        await this.opportunitiesService.findByCode(ctx, session);
        break;
      case StepEnum.OPPORTUNITIES_GROUP_MENU:
        await this.opportunitiesService.findByGroup(ctx, session);
        break;
      case StepEnum.PROCEEDING_MENU_PICK:
        await this.proceedingMenu.goTo(ctx, session);
        break;
      case StepEnum.PROCEEDING_ACTIVATE:
        await this.proceedingMenu.activateMonitoring(ctx, session);
        break;
      case StepEnum.PROCEEDING_REQUEST:
        await this.proceedingMenu.findByNumber(ctx, session);
        break;
      case StepEnum.MENU_CONTACT_US:
        await this.contactUsService.goTo(ctx, session);
        break;
      case StepEnum.PROPOSAL_SHOW:
        await this.proceedingMenu.proposalShow(ctx, session);
        break;
      case StepEnum.PROCEEDING_MONITORED:
        await this.proceedingMenu.monitoredShow(ctx, session);
        break;
      case StepEnum.REQUEST_BUG:
        await this.contactUsService.reportBug(ctx, session);
        break;
      case StepEnum.REQUEST_SUGGESTION:
        await this.contactUsService.sendSuggestion(ctx, session);
        break;
    }
  }

  @On('contact')
  public async validateUser(ctx) {
    const chatId = ctx.chat.id.toString();
    const session = await this.cache.get(chatId);

    switch (session.step) {
      case StepEnum.USER_VERIFICATION:
        if (await this.userService.validate(ctx)) {
          await this.userService.linkTelegram(ctx);
          await ctx.telegram.sendMessage(
            chatId,
            MessageUtils.get(MessageCodeEnum.WELCOME, session.user.name),
          );
          await this.institutionService.list(ctx, session);
        } else {
          await this.completeService(ctx);
        }
        break;
    }
  }
}
evilsprut commented 2 years ago

@tharbts if you use ngrok2 free version, it won't work. Because ngrok requires a special header to be sent

legitimoth commented 2 years ago

@tharbts if you use ngrok2 free version, it won't work. Because ngrok requires a special header to be sent

So, I did everything correctly? I set hookPath with my root application url (that doesn't have any endpoint created (controller)) and the service methods masked with annotations @on('text'), @start() and @on('contact') is gonna to listen any message sent to bot?

The code above when I send any message to bot nothing happens, so the only problem is that I'm using ngrok free, if I publish that for real, It's gonna work?

legitimoth commented 2 years ago

Guys in the first try my mistake was that I created the endpoint that I set on hookpath. The second try my mistake was set the root url as hookpath.

The correct is set as hookpath a fake endpoint like: HTTPS://your-application-url/fakeEndpointHere

The telegraf will create that endpoint automatically and you need do nothing else. Just set the settings like the @webpct said.