From f10df2e96057cb61e5009cdc8a3ccf1bd1cabadf Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 26 Dec 2020 16:48:04 +0300 Subject: [PATCH] feat(sample): make echo bot --- sample/app.module.ts | 3 ++- sample/app.update.ts | 32 ++++++++++++++++++++++++++++++-- sample/echo.service.ts | 8 ++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 sample/echo.service.ts diff --git a/sample/app.module.ts b/sample/app.module.ts index e35a9f4..19b71ac 100644 --- a/sample/app.module.ts +++ b/sample/app.module.ts @@ -1,5 +1,6 @@ import { Module } from '@nestjs/common'; import { TelegrafModule } from '../lib'; +import { EchoService } from './echo.service'; import { AppUpdate } from './app.update'; @Module({ @@ -8,6 +9,6 @@ import { AppUpdate } from './app.update'; token: '1467731595:AAHCvH65H9VQYKF9jE-E8c2rXsQBVAYseg8', }), ], - providers: [AppUpdate], + providers: [EchoService, AppUpdate], }) export class AppModule {} diff --git a/sample/app.update.ts b/sample/app.update.ts index a0dc748..dab2a76 100644 --- a/sample/app.update.ts +++ b/sample/app.update.ts @@ -1,9 +1,37 @@ -import { On, Update } from '../lib/decorators'; +import { Telegraf } from 'telegraf'; +import { Help, InjectBot, On, Start, Update } from '../lib/decorators'; +import { Context } from '../lib/interfaces'; +import { EchoService } from './echo.service'; @Update() export class AppUpdate { + constructor( + @InjectBot() + private readonly bot: Telegraf, + private readonly echoService: EchoService, + ) {} + + @Start() + async onStart(ctx: Context): Promise { + const me = await this.bot.telegram.getMe(); + await ctx.reply(`Hey, I'm ${me.first_name}`); + } + + @Help() + async onHelp(ctx: Context): Promise { + await ctx.reply('Send me any text'); + } + @On('message') - onMessage(): void { + async onMessage(ctx: Context): Promise { console.log('New message received'); + + if ('text' in ctx.message) { + const messageText = ctx.message.text; + const echoText = this.echoService.echo(messageText); + await ctx.reply(echoText); + } else { + await ctx.reply('Only text messages'); + } } } diff --git a/sample/echo.service.ts b/sample/echo.service.ts new file mode 100644 index 0000000..2603cc2 --- /dev/null +++ b/sample/echo.service.ts @@ -0,0 +1,8 @@ +import { Injectable } from '@nestjs/common'; + +@Injectable() +export class EchoService { + echo(text: string): string { + return `Echo: ${text}`; + } +}