init simple bot

This commit is contained in:
2024-12-26 15:29:46 +04:00
parent ed4a09a0ee
commit fa1451696f
21 changed files with 11569 additions and 806 deletions

View File

@@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

36
client/src/app.module.ts Normal file
View File

@@ -0,0 +1,36 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TelegrafModule } from 'nestjs-telegraf';
import { BotModule } from './bot/bot.module';
import { BotUpdate } from './bot/update';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '../.env',
}),
TelegrafModule.forRoot({
token: process.env.TELEGRAM_BOT_TOKEN,
launchOptions: {
webhook: {
domain: process.env.TELEGRAM_BOT_WEBHOOK_URL,
path: '/webhook',
}
}
}),
TypeOrmModule.forRoot({
type: 'sqlite',
database: '../db/database.sqlite',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
BotModule
],
controllers: [AppController],
providers: [AppService, BotUpdate],
})
export class AppModule {}

View File

@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { BotUpdate } from './update';
import { PurchaseService } from './purchase.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Purchase } from './entities/purchase.entity';
@Module({
providers: [BotUpdate, PurchaseService],
imports: [TypeOrmModule.forFeature([Purchase])],
exports: [PurchaseService],
})
export class BotModule {}

View File

@@ -0,0 +1,19 @@
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Purchase {
@PrimaryGeneratedColumn()
id: number;
@Column()
userId: number;
@Column('decimal')
amount: number;
@Column('decimal')
price: number;
@Column()
date: Date;
}

View File

@@ -0,0 +1,38 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Purchase } from './entities/purchase.entity';
@Injectable()
export class PurchaseService {
constructor(
@InjectRepository(Purchase)
private purchaseRepository: Repository<Purchase>,
) { }
async addPurchase(purchase: Partial<Purchase>): Promise<void> {
await this.purchaseRepository.save(purchase);
}
async getUserPurchases(userId: number): Promise<Purchase[]> {
return this.purchaseRepository.find({ where: { userId } });
}
async getStats(userId: number) {
const userPurchases = await this.getUserPurchases(userId);
if (userPurchases.length === 0) {
return null;
}
const totalAmount = userPurchases.reduce((sum, p) => sum + p.amount, 0);
const totalSpent = userPurchases.reduce((sum, p) => sum + (p.amount * p.price), 0);
const averagePrice = totalSpent / totalAmount;
return {
totalAmount,
totalSpent,
averagePrice,
purchaseCount: userPurchases.length
};
}
}

92
client/src/bot/update.ts Normal file
View File

@@ -0,0 +1,92 @@
import { Command, Ctx, Update } from 'nestjs-telegraf';
import { Context, NarrowedContext } from 'telegraf';
import { Logger } from '@nestjs/common';
import { PurchaseService } from './purchase.service';
import { validate } from 'class-validator';
import { Message, Update as UpdateType } from 'telegraf/typings/core/types/typegram';
class PurchaseDto {
userId: number;
amount: number;
price: number;
date: Date;
}
@Update()
export class BotUpdate {
private readonly logger = new Logger(BotUpdate.name);
constructor (
private readonly purchaseService: PurchaseService
) {
this.logger.log('BotUpdate initialized');
}
@Command('start')
async onStart(ctx: Context) {
await ctx.reply(
'Привет! Я помогу отслеживать ваши покупки TON.\n' +
'Используйте команду /buy <количество> <цена> для записи покупки\n' +
'Например: /buy 100 2.5\n' +
'Используйте /stats для просмотра статистики'
);
}
@Command('buy')
async onBuy(ctx: NarrowedContext<Context, UpdateType.MessageUpdate<Message.TextMessage>>) {
try {
const message = ctx.message.text;
const [_, amount, price] = message.split(' ');
if (!amount || !price) {
await ctx.reply('Пожалуйста, укажите количество и цену.\nПример: /buy 100 2.5');
return;
}
const purchaseDto = new PurchaseDto();
purchaseDto.userId = ctx.from.id;
purchaseDto.amount = parseFloat(amount);
purchaseDto.price = parseFloat(price);
purchaseDto.date = new Date();
const errors = await validate(purchaseDto);
if (errors.length > 0) {
await ctx.reply('Пожалуйста, укажите корректные данные');
return;
}
await this.purchaseService.addPurchase(purchaseDto);
await ctx.reply(
`✅ Покупка записана:\n` +
`Количество: ${purchaseDto.amount.toFixed(2)} TON\n` +
`Цена: $${purchaseDto.price.toFixed(2)}\n` +
`Сумма: $${(purchaseDto.amount * purchaseDto.price).toFixed(2)}`
);
} catch (error) {
this.logger.error('Error processing buy command:', error);
await ctx.reply('Произошла ошибка. Попробуйте еще раз');
}
}
@Command('stats')
async onStats(ctx: Context) {
try {
const stats = await this.purchaseService.getStats(ctx.from.id);
if (!stats) {
await ctx.reply('У вас пока нет записанных покупок');
return;
}
await ctx.reply(
`📊 Ваша статистика:\n\n` +
`Всего куплено: ${stats.totalAmount.toFixed(2)} TON\n` +
`Потрачено: $${stats.totalSpent.toFixed(2)}\n` +
`Средняя цена покупки: $${stats.averagePrice.toFixed(2)}\n` +
`Количество покупок: ${stats.purchaseCount}`
);
} catch (error) {
this.logger.error('Error processing stats command:', error);
await ctx.reply('Произошла ошибка при получении статистики');
}
}
}

15
client/src/main.ts Normal file
View File

@@ -0,0 +1,15 @@
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { getBotToken } from "nestjs-telegraf";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const bot = app.get(getBotToken());
console.log('Setting up webhook callback...');
app.use('/webhook', bot.webhookCallback());
await app.listen(2000);
console.log('Application is running on port 2000');
}
bootstrap();