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

25
client/.eslintrc.js Normal file
View File

@@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

4
client/.prettierrc Normal file
View File

@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

8
client/nest-cli.json Normal file
View File

@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

11206
client/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

63
client/package.json Normal file
View File

@@ -0,0 +1,63 @@
{
"name": "onetondaily",
"version": "1.0.0",
"description": "bot who receive your TON buying and calc your stats",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"repository": {
"type": "git",
"url": "https://gitea.musk.fun/edweiser/one_ton_daily_bot.git"
},
"author": "ezviagintsev",
"license": "ISC",
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.4.15",
"@nestjs/typeorm": "^10.0.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"nestjs-telegraf": "^2.8.1",
"nodemon": "^3.1.9",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"sqlite3": "^5.1.7",
"telegraf": "^4.16.3",
"typeorm": "^0.3.20"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/supertest": "^2.0.12",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.1.3"
}
}

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();

View File

@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
client/tsconfig.json Normal file
View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}