Code Monkey home page Code Monkey logo

Comments (7)

webpct avatar webpct commented on May 11, 2024 1

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 :)

from nestjs-telegraf.

webpct avatar webpct commented on May 11, 2024

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

from nestjs-telegraf.

legitimoth avatar legitimoth commented on May 11, 2024

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")

from nestjs-telegraf.

legitimoth avatar legitimoth commented on May 11, 2024

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;
    }
  }
}

from nestjs-telegraf.

evilsprut avatar evilsprut commented on May 11, 2024

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

from nestjs-telegraf.

legitimoth avatar legitimoth commented on May 11, 2024

@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?

from nestjs-telegraf.

legitimoth avatar legitimoth commented on May 11, 2024

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.

from nestjs-telegraf.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.