Skip to content

Commit

Permalink
Merge branch 'dev' into tokento
Browse files Browse the repository at this point in the history
  • Loading branch information
zk-robin authored Nov 8, 2024
2 parents 63cbf1e + ffce7bb commit 3eab409
Show file tree
Hide file tree
Showing 9 changed files with 126 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { Creator } from './entities/creator.entity';
import { Intention } from './entities/intention.entity';
import { IntentionRecord } from './entities/intentionRecord.entity';
import { IntentionRecordTx } from './entities/intentionRecordTx.entity';
import { ScSession } from './entities/scSession.entity';
import { TgGroupAndChannel } from './entities/tgGroupAndChannel.entity';
import { TgMessage } from './entities/tgMessage.entity';
import { MetricsModule } from './metrics';
Expand Down Expand Up @@ -61,6 +62,7 @@ import { UnitOfWorkModule } from './unitOfWork';
IntentionRecordTx,
TgMessage,
TgGroupAndChannel,
ScSession,
]),
ActionModule.forRoot(),
MetricsModule,
Expand Down
16 changes: 16 additions & 0 deletions src/entities/scSession.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm';

import { BaseEntity } from './base.entity';

@Entity()
@Index(['sessionId'], { unique: true })
export class ScSession extends BaseEntity {
@PrimaryGeneratedColumn()
public readonly id: bigint;

@Column({ type: 'varchar' })
public sessionId: string;

@Column({ type: 'varchar' })
public data: string;
}
21 changes: 21 additions & 0 deletions src/migrations/1731076287218-CreateTableScSession1731076287218.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateTableScSession1731076287218 implements MigrationInterface {
name = 'CreateTableScSession1731076287218';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "sc_session" ("createdAt" TIMESTAMP NOT NULL DEFAULT now(), "updatedAt" TIMESTAMP NOT NULL DEFAULT now(), "deletedAt" TIMESTAMP, "id" SERIAL NOT NULL, "sessionId" character varying NOT NULL, "data" character varying NOT NULL, CONSTRAINT "PK_fb10d649e63815947580f4c6407" PRIMARY KEY ("id"))`,
);
await queryRunner.query(
`CREATE UNIQUE INDEX "IDX_c8eae9e5d612665913e4346081" ON "sc_session" ("sessionId") `,
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`DROP INDEX "public"."IDX_c8eae9e5d612665913e4346081"`,
);
await queryRunner.query(`DROP TABLE "sc_session"`);
}
}
42 changes: 41 additions & 1 deletion src/modules/tgbot/flashNewsBot.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ethers } from 'ethers';
import html2md from 'html-to-md';
import { LRUCache } from 'lru-cache';
import { customAlphabet } from 'nanoid';
import TelegramBot, {
ChatMemberUpdated,
ParseMode,
Expand All @@ -10,9 +11,11 @@ import { LessThanOrEqual, MoreThanOrEqual } from 'typeorm';

import { NetworkDto } from 'src/common/dto';
import configFactory from 'src/config';
import { ScSession } from 'src/entities/scSession.entity';
import { TgGroupAndChannel } from 'src/entities/tgGroupAndChannel.entity';
import { BusinessException } from 'src/exception/business.exception';
import {
ScSessionRepository,
TgGroupAndChannelRepository,
TgMessageRepository,
} from 'src/repositories';
Expand Down Expand Up @@ -41,6 +44,7 @@ export class FlashNewsBotService implements OnModuleInit {
private readonly coingeckoService: CoingeckoService,
private readonly tgMessageRepository: TgMessageRepository,
private readonly tgGroupAndChannelRepository: TgGroupAndChannelRepository,
private readonly scSessionRepository: ScSessionRepository,
) {}

async update(body: any) {
Expand Down Expand Up @@ -580,7 +584,9 @@ ${this.formatMarkdownV2(content).replaceAll(
fromTokenAddress: string,
toTokenAddress: string,
settings: Settings,
sc?: string,
) {
let shareText = '';
const config = await configFactory();
const userMiniApp = config.tgbot.userMiniApp;
const newsChannelIdCn = config.tgbot.newsChannelIdCn;
Expand Down Expand Up @@ -617,6 +623,11 @@ ${this.formatMarkdownV2(content).replaceAll(
let linkIndex = 0;
let lang = 'cn';
if (this.containsChineseCharacters(content)) {
shareText = sc
? sc
: `嘿😎,这是可以自定义你一键操作的 magicLink🎯
现在通过我的邀请链接开始行动吧!`;
newsChannelId = newsChannelIdCn;
captionTemplate = `
🟢*${this.formatMarkdownV2(title)}*🟢
Expand All @@ -634,6 +645,11 @@ ${this.formatMarkdownV2(content).replaceAll(
🌈在您的群中推送 magicNews 邀请 [@magicNews](${tgbot}?startgroup=join_cn) 到您的群中
`;
} else {
shareText = sc
? sc
: `Hey😎, here's the magicLink that can customize your one-click action🎯
Start ACTION from my invite link now!`;
lang = 'en';
newsChannelId = newsChannelIdEn;
captionTemplate = `
Expand Down Expand Up @@ -682,6 +698,12 @@ ${this.formatMarkdownV2(content).replaceAll(
];
}
inlineKeyboard.push(typeActions);

const nanoid = customAlphabet(
'1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
8,
);
const shareTextArr: ScSession[] = [];
const actions = settings.intentList;
for (let i = 0; i < actions.length; i++) {
const lineButtons = [];
Expand All @@ -699,13 +721,20 @@ ${this.formatMarkdownV2(content).replaceAll(
) {
const urlTmp = new URL(action.value);
const pathSegments = urlTmp.pathname.split('/');
const scOfUrl = urlTmp.searchParams.get('sc');
const shareTextLink = scOfUrl ? scOfUrl : shareText;
const sessionId = nanoid(20);
shareTextArr.push({
sessionId,
data: shareTextLink,
} as ScSession);
const code = pathSegments[pathSegments.length - 1];
const btnIndex = action.btnIndex ?? '';
const btnIndexStr =
btnIndex === ''
? ''
: Math.max(parseInt(btnIndex) - 1, 0).toString();
url = `${userMiniApp}?startapp=${code}_${btnIndexStr}`;
url = `${userMiniApp}?startapp=${code}_${btnIndexStr}___${sessionId}`;
} else {
url = action.value;
}
Expand All @@ -717,6 +746,13 @@ ${this.formatMarkdownV2(content).replaceAll(
}
inlineKeyboard.push(lineButtons);
}
if (shareTextArr.length > 0) {
try {
await this.scSessionRepository.addMany(shareTextArr);
} catch (error) {
this.logger.error('sendNewsOrigin error', error.stack);
}
}
const reply_markup = {
inline_keyboard: inlineKeyboard,
};
Expand Down Expand Up @@ -769,6 +805,10 @@ ${this.formatMarkdownV2(content).replaceAll(
}
}

async getScBySessionId(sessionId: string) {
return await this.scSessionRepository.getData(sessionId);
}

async editMessageReplyMarkupPollText(
chatId: string,
messageId: string,
Expand Down
12 changes: 12 additions & 0 deletions src/modules/tgbot/tgbot.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export class TgbotController extends BaseController {
body.fromTokenAddress,
body.toTokenAddress,
body.settings,
body.sc,
);
return this.success(true);
} catch (error) {
Expand All @@ -103,6 +104,17 @@ export class TgbotController extends BaseController {
}
}

@Get('getSc')
async getSc(@Query('sessionId') sessionId: string) {
try {
const res = await this.flashNewsBotService.getScBySessionId(sessionId);
return this.success(res);
} catch (error) {
this.logger.error(error);
return this.error(error.message);
}
}

@Get('testEditMessageReplyMarkupPollText')
async testEditMessageReplyMarkupPollText(
@Query('userId') userId: string,
Expand Down
9 changes: 9 additions & 0 deletions src/modules/tgbot/tgbot.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ export class SendNewsOriginRequestDto {
})
metadata: string;

@ApiProperty({
name: 'sc',
description: 'sc.',
required: true,
})
@IsString()
@IsNotEmpty()
sc: string;

@ApiProperty({
name: 'fromTokenAddress',
description: 'Address of from token.',
Expand Down
2 changes: 2 additions & 0 deletions src/modules/tgbot/tgbot.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
IntentionRecordRepository,
IntentionRecordTxRepository,
IntentionRepository,
ScSessionRepository,
TgGroupAndChannelRepository,
TgMessageRepository,
} from 'src/repositories';
Expand Down Expand Up @@ -40,6 +41,7 @@ import { CoingeckoService } from '../coingecko/coingecko.service';
TgGroupAndChannelRepository,
FlashNewsBotService,
AibotService,
ScSessionRepository,
],
exports: [TgbotService, FlashNewsBotService],
controllers: [TgbotController],
Expand Down
1 change: 1 addition & 0 deletions src/repositories/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ export * from './intentionRecordTx.repository';
export * from './commission.repository';
export * from './tgMessage.repository';
export * from './tgGroupAndChannel.repository';
export * from './scSession.repository';
22 changes: 22 additions & 0 deletions src/repositories/scSession.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';

import { ScSession } from 'src/entities/scSession.entity';

import { BaseRepository } from './base.repository';
import { UnitOfWork } from '../unitOfWork';

@Injectable()
export class ScSessionRepository extends BaseRepository<ScSession> {
public constructor(unitOfWork: UnitOfWork) {
super(ScSession, unitOfWork);
}

async getData(sessionId: string): Promise<string> {
const res = await this.findOneBy({ sessionId });
return res?.data ?? '';
}

async setData(sessionId: string, data: string): Promise<void> {
return await this.upsert({ sessionId, data }, true, ['sessionId']);
}
}

0 comments on commit 3eab409

Please sign in to comment.