global fix and update bot Api

This commit is contained in:
lendry
2026-06-26 13:01:52 +03:00
parent d3ea470d02
commit aa228d84eb
29 changed files with 980 additions and 221 deletions

View File

@@ -53,6 +53,10 @@ type EditMessageReplyMarkupPayload = ChatPayload & {
reply_markup?: unknown;
};
type PinChatMessagePayload = ChatPayload & {
disable_notification?: boolean;
};
type AnswerCallbackQueryPayload = {
callback_query_id?: string;
text?: string;
@@ -125,12 +129,18 @@ export class BotApiService {
switch (normalizedMethod) {
case 'getMe':
return this.wrapOk(this.buildUserObject(bot));
case 'getChat':
return this.getChat(bot, payload as ChatPayload);
case 'sendMessage':
return this.sendMessage(bot, payload as SendMessagePayload);
case 'editMessageText':
return this.editMessageText(bot, payload as EditMessageTextPayload);
case 'editMessageReplyMarkup':
return this.editMessageReplyMarkup(bot, payload as EditMessageReplyMarkupPayload);
case 'pinChatMessage':
return this.setMessagePinned(bot, payload as PinChatMessagePayload, true);
case 'unpinChatMessage':
return this.setMessagePinned(bot, payload as ChatPayload, false);
case 'answerCallbackQuery':
return this.answerCallbackQuery(payload as AnswerCallbackQueryPayload);
case 'sendPhoto':
@@ -277,7 +287,9 @@ export class BotApiService {
messageType: 'text',
messageId: item.telegramMsgId,
createdAt: item.createdAt.toISOString(),
replyMarkupJson: null as string | null
replyMarkupJson: null as string | null,
isPinned: false,
pinnedAt: null as string | null
})),
...outbound.map((item) => {
const payload = this.serializer.readPayload(item.payload);
@@ -289,7 +301,9 @@ export class BotApiService {
messageType: item.messageType ?? 'text',
messageId: item.telegramMsgId,
createdAt: item.createdAt.toISOString(),
replyMarkupJson: replyMarkup ? JSON.stringify(replyMarkup) : null
replyMarkupJson: replyMarkup ? JSON.stringify(replyMarkup) : null,
isPinned: item.isPinned,
pinnedAt: item.pinnedAt?.toISOString() ?? null
};
})
].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
@@ -564,6 +578,82 @@ export class BotApiService {
return this.wrapOk(this.buildTelegramMessage(bot, located, updated));
}
private async getChat(bot: ValidatedBot, payload: ChatPayload) {
if (!payload.chat_id) {
return this.wrapBadRequest('Bad Request: chat_id is required');
}
const context = await this.resolveChatContext(bot.id, String(payload.chat_id));
if (!context) {
return this.wrapBadRequest('Bad Request: chat not found');
}
const pinned = await this.prisma.botMessage.findFirst({
where: {
botId: bot.id,
botChatId: context.chat.id,
isPinned: true
},
orderBy: { pinnedAt: 'desc' }
});
return this.wrapOk({
id: Number(context.chat.telegramChatId),
type: context.chat.chatType,
first_name: context.recipient.displayName,
...(context.recipient.username ? { username: context.recipient.username } : {}),
...(pinned ? { pinned_message: this.buildTelegramMessage(bot, context, pinned) } : {})
});
}
private async setMessagePinned(bot: ValidatedBot, payload: ChatPayload, pinned: boolean) {
if (!payload.chat_id) {
return this.wrapBadRequest('Bad Request: chat_id is required');
}
if (pinned && payload.message_id === undefined) {
return this.wrapBadRequest('Bad Request: message_id is required');
}
const messageId = payload.message_id === undefined ? undefined : Number(payload.message_id);
if (messageId !== undefined && !Number.isFinite(messageId)) {
return this.wrapBadRequest('Bad Request: message_id is invalid');
}
const context = await this.resolveChatContext(bot.id, String(payload.chat_id));
if (!context) {
return this.wrapBadRequest('Bad Request: chat not found');
}
const message = messageId === undefined
? await this.prisma.botMessage.findFirst({
where: {
botId: bot.id,
botChatId: context.chat.id,
isPinned: true
},
orderBy: { pinnedAt: 'desc' }
})
: await this.prisma.botMessage.findFirst({
where: {
botId: bot.id,
botChatId: context.chat.id,
telegramMsgId: messageId
}
});
if (!message) {
return this.wrapBadRequest(pinned ? 'Bad Request: message to pin not found' : 'Bad Request: message to unpin not found');
}
const updated = await this.prisma.botMessage.update({
where: { id: message.id },
data: pinned ? { isPinned: true, pinnedAt: new Date() } : { isPinned: false, pinnedAt: null }
});
await this.publishBotMessagePinned(context.recipient.id, bot, context.chat, updated);
return this.wrapOk(true);
}
private async answerCallbackQuery(payload: AnswerCallbackQueryPayload) {
const callbackQueryId = payload.callback_query_id?.trim();
if (!callbackQueryId) {
@@ -743,6 +833,8 @@ export class BotApiService {
createdAt: Date;
editedAt?: Date | null;
payload?: unknown;
isPinned?: boolean;
pinnedAt?: Date | null;
}
) {
return this.serializer.buildBotMessageObject({
@@ -786,6 +878,26 @@ export class BotApiService {
});
}
private async publishBotMessagePinned(
userId: string,
bot: ValidatedBot,
chat: { telegramChatId: bigint; chatType: string },
message: {
telegramMsgId: number;
isPinned?: boolean;
pinnedAt?: Date | null;
}
) {
await this.notifications.publishRealtime(userId, 'bot_message_pinned', bot.name, '', {
botId: bot.id,
botUsername: bot.username,
chatId: chat.telegramChatId.toString(),
messageId: message.telegramMsgId,
isPinned: Boolean(message.isPinned),
pinnedAt: message.pinnedAt?.toISOString() ?? null
});
}
private async publishBotMessageEdited(
userId: string,
bot: ValidatedBot,

View File

@@ -1,8 +1,10 @@
import { Injectable, Logger } from '@nestjs/common';
import { BotApiService } from './bot-api.service';
import { BOTFATHER_BOT_USERNAME, buildBotCreateWebAppUrl, buildBotManageWebAppUrl } from './bot-father.constants';
import { PrismaService } from '../../infra/prisma.service';
import { BOTFATHER_BOT_USERNAME, GET_MY_ID_DISPLAY_NAME, buildBotCreateWebAppUrl, buildBotManageWebAppUrl } from './bot-father.constants';
import { BotFatherSeedService } from './bot-father-seed.service';
import { BotFatherService } from './bot-father.service';
import { deriveTelegramChatId } from './bot-token.util';
@Injectable()
export class BotFatherAssistantService {
@@ -11,10 +13,16 @@ export class BotFatherAssistantService {
constructor(
private readonly seed: BotFatherSeedService,
private readonly botFather: BotFatherService,
private readonly botApi: BotApiService
private readonly botApi: BotApiService,
private readonly prisma: PrismaService
) {}
async handleUserMessage(senderUserId: string, text: string) {
async handleUserMessage(systemBotId: string, senderUserId: string, text: string) {
if (systemBotId === await this.seed.getGetMyIdBotId()) {
await this.handleGetMyIdMessage(senderUserId, text, systemBotId);
return;
}
const botId = await this.seed.getBotFatherBotId();
const trimmed = text.trim();
const lower = trimmed.toLowerCase();
@@ -52,7 +60,12 @@ export class BotFatherAssistantService {
);
}
async handleCallbackQuery(senderUserId: string, callbackData: string) {
async handleCallbackQuery(systemBotId: string, senderUserId: string, callbackData: string) {
if (systemBotId === await this.seed.getGetMyIdBotId()) {
await this.handleGetMyIdMessage(senderUserId, '/id', systemBotId);
return;
}
const botId = await this.seed.getBotFatherBotId();
if (callbackData === 'newbot_help' || callbackData === 'newbot') {
await this.botApi.sendInternalBotMessage(
@@ -84,6 +97,72 @@ export class BotFatherAssistantService {
);
}
private async handleGetMyIdMessage(senderUserId: string, text: string, botId: string) {
const lower = text.trim().toLowerCase();
if (lower === '/start' || lower === '/help') {
await this.botApi.sendInternalBotMessage(
botId,
senderUserId,
[
`Привет! Я ${GET_MY_ID_DISPLAY_NAME}.`,
'',
'Отправьте /id, чтобы получить:',
'• UUID пользователя',
'• username',
'• chat_id для этого бота',
'• chat_id для ваших ботов, которые можно вставлять в Bot API-скрипты'
].join('\n'),
{ inline_keyboard: [[{ text: 'Показать мои ID', callback_data: 'get_my_id' }]] }
);
return;
}
await this.sendMyIdReport(senderUserId, botId);
}
private async sendMyIdReport(senderUserId: string, botId: string) {
const user = await this.prisma.user.findUnique({
where: { id: senderUserId },
select: { id: true, displayName: true, username: true, email: true, phone: true }
});
if (!user) {
await this.botApi.sendInternalBotMessage(botId, senderUserId, 'Пользователь не найден');
return;
}
const ownBots = await this.prisma.bot.findMany({
where: { ownerId: senderUserId, isActive: true },
orderBy: { name: 'asc' },
select: { id: true, name: true, username: true }
});
const currentChatId = deriveTelegramChatId(`${botId}:${senderUserId}`).toString();
const botLines = ownBots.length
? ownBots.map((bot) => `${bot.name} (@${bot.username})\n bot_id: ${bot.id}\n chat_id: ${deriveTelegramChatId(`${bot.id}:${senderUserId}`).toString()}`)
: ['У вас пока нет созданных ботов.'];
await this.botApi.sendInternalBotMessage(
botId,
senderUserId,
[
'Ваши ID для интеграций:',
'',
`user_id: ${user.id}`,
`name: ${user.displayName}`,
`username: ${user.username ? `@${user.username}` : 'не указан'}`,
`email: ${user.email ?? 'не указан'}`,
`phone: ${user.phone ?? 'не указан'}`,
'',
`chat_id с ${GET_MY_ID_DISPLAY_NAME}: ${currentChatId}`,
'',
'chat_id для ваших ботов:',
...botLines,
'',
'Используйте нужный chat_id в методах sendMessage, editMessageText, pinChatMessage и getChat.'
].join('\n')
);
}
private parseProfileCommand(text: string):
| { kind: 'setdescription' | 'setabouttext' | 'setuserpic' | 'setmenubutton'; botUsername: string; value: string }
| null {

View File

@@ -7,6 +7,11 @@ import {
BOTFATHER_SETTING_BOT_ID,
BOTFATHER_SETTING_USER_ID,
BOTFATHER_USER_USERNAME,
GET_MY_ID_BOT_USERNAME,
GET_MY_ID_DISPLAY_NAME,
GET_MY_ID_SETTING_BOT_ID,
GET_MY_ID_SETTING_USER_ID,
GET_MY_ID_USER_USERNAME,
SYSTEM_BOT_OWNER_EMAIL
} from './bot-father.constants';
import { generateTelegramStyleBotToken, hashBotToken } from './bot-token.util';
@@ -16,6 +21,8 @@ export class BotFatherSeedService implements OnModuleInit {
private readonly logger = new Logger(BotFatherSeedService.name);
private cachedUserId: string | null = null;
private cachedBotId: string | null = null;
private cachedGetMyIdUserId: string | null = null;
private cachedGetMyIdBotId: string | null = null;
constructor(
private readonly prisma: PrismaService,
@@ -24,6 +31,7 @@ export class BotFatherSeedService implements OnModuleInit {
async onModuleInit() {
await this.ensureBotFather();
await this.ensureGetMyIdBot();
}
async getBotFatherUserId() {
@@ -48,6 +56,28 @@ export class BotFatherSeedService implements OnModuleInit {
return ensured.botId;
}
async getGetMyIdBotUserId() {
if (this.cachedGetMyIdUserId) return this.cachedGetMyIdUserId;
const setting = await this.prisma.systemSetting.findUnique({ where: { key: GET_MY_ID_SETTING_USER_ID } });
if (setting?.value) {
this.cachedGetMyIdUserId = setting.value;
return setting.value;
}
const ensured = await this.ensureGetMyIdBot();
return ensured.userId;
}
async getGetMyIdBotId() {
if (this.cachedGetMyIdBotId) return this.cachedGetMyIdBotId;
const setting = await this.prisma.systemSetting.findUnique({ where: { key: GET_MY_ID_SETTING_BOT_ID } });
if (setting?.value) {
this.cachedGetMyIdBotId = setting.value;
return setting.value;
}
const ensured = await this.ensureGetMyIdBot();
return ensured.botId;
}
async ensureBotFather() {
const existingBotId = await this.prisma.systemSetting.findUnique({ where: { key: BOTFATHER_SETTING_BOT_ID } });
const existingUserId = await this.prisma.systemSetting.findUnique({ where: { key: BOTFATHER_SETTING_USER_ID } });
@@ -112,6 +142,72 @@ export class BotFatherSeedService implements OnModuleInit {
return { userId: botFatherUser.id, botId: bot.id };
}
async ensureGetMyIdBot() {
const existingBotId = await this.prisma.systemSetting.findUnique({ where: { key: GET_MY_ID_SETTING_BOT_ID } });
const existingUserId = await this.prisma.systemSetting.findUnique({ where: { key: GET_MY_ID_SETTING_USER_ID } });
if (existingBotId?.value && existingUserId?.value) {
this.cachedGetMyIdBotId = existingBotId.value;
this.cachedGetMyIdUserId = existingUserId.value;
return { userId: existingUserId.value, botId: existingBotId.value };
}
const ownerId = await this.resolveBotOwnerId();
let systemUser = await this.prisma.user.findFirst({
where: { username: GET_MY_ID_USER_USERNAME, isSystemAccount: true }
});
if (!systemUser) {
systemUser = await this.prisma.user.create({
data: {
displayName: GET_MY_ID_DISPLAY_NAME,
username: GET_MY_ID_USER_USERNAME,
isSystemAccount: true,
isVerified: true,
verificationIcon: 'bot'
}
});
this.logger.log(`Создан системный пользователь ${GET_MY_ID_DISPLAY_NAME}`);
}
let bot = await this.prisma.bot.findUnique({ where: { username: GET_MY_ID_BOT_USERNAME } });
if (!bot) {
const { token, tokenPrefix } = generateTelegramStyleBotToken();
bot = await this.prisma.bot.create({
data: {
name: GET_MY_ID_DISPLAY_NAME,
username: GET_MY_ID_BOT_USERNAME,
tokenHash: hashBotToken(token),
tokenPrefix,
ownerId,
description: 'Показывает ваш user_id и chat_id для Bot API.',
aboutText: 'Получите ID пользователя и chat_id для интеграций.',
isSystemBot: true
}
});
this.logger.log(`Создан системный бот @${GET_MY_ID_BOT_USERNAME}`);
} else if (!bot.isSystemBot) {
bot = await this.prisma.bot.update({
where: { id: bot.id },
data: { isSystemBot: true, isActive: true }
});
}
if (systemUser.linkedBotId !== bot.id) {
await this.prisma.user.update({
where: { id: systemUser.id },
data: { linkedBotId: bot.id }
});
}
await this.upsertSetting(GET_MY_ID_SETTING_USER_ID, systemUser.id, 'UUID системного пользователя GetMyIdBot');
await this.upsertSetting(GET_MY_ID_SETTING_BOT_ID, bot.id, 'UUID системного бота GetMyIdBot');
await this.rbac.ensureBotUserRole(systemUser.id);
this.cachedGetMyIdUserId = systemUser.id;
this.cachedGetMyIdBotId = bot.id;
return { userId: systemUser.id, botId: bot.id };
}
private async resolveBotOwnerId() {
const superAdmin = await this.prisma.user.findFirst({
where: { isSuperAdmin: true, deletedAt: null, status: 'ACTIVE', isSystemAccount: false },

View File

@@ -3,6 +3,11 @@ export const BOTFATHER_USER_USERNAME = 'BotFather';
export const BOTFATHER_DISPLAY_NAME = 'BotFather';
export const BOTFATHER_SETTING_USER_ID = 'BOTFATHER_USER_ID';
export const BOTFATHER_SETTING_BOT_ID = 'BOTFATHER_BOT_ID';
export const GET_MY_ID_BOT_USERNAME = 'GetMyIdBot_bot';
export const GET_MY_ID_USER_USERNAME = 'GetMyIdBot';
export const GET_MY_ID_DISPLAY_NAME = 'GetMyIdBot';
export const GET_MY_ID_SETTING_USER_ID = 'GET_MY_ID_BOT_USER_ID';
export const GET_MY_ID_SETTING_BOT_ID = 'GET_MY_ID_BOT_ID';
export const SYSTEM_BOT_OWNER_EMAIL = 'system-bot-owner@internal.lendry.id';
export function resolvePublicFrontendUrl() {

View File

@@ -34,7 +34,7 @@ export class BotInboundService {
const event = await this.createMessageEvent(bot.id, chat.id, senderUserId, chat.telegramChatId, trimmedText);
await this.dispatchEvent(event);
if (bot.isSystemBot) {
void this.assistant.handleUserMessage(senderUserId, trimmedText).catch(() => undefined);
void this.assistant.handleUserMessage(bot.id, senderUserId, trimmedText).catch(() => undefined);
}
return {
@@ -89,7 +89,7 @@ export class BotInboundService {
await this.dispatchEvent(event);
if (bot.isSystemBot) {
void this.assistant.handleCallbackQuery(senderUserId, trimmedData).catch(() => undefined);
void this.assistant.handleCallbackQuery(bot.id, senderUserId, trimmedData).catch(() => undefined);
}
return {