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

@@ -438,6 +438,9 @@ model ChatMessage {
metadata Json?
storageKey String?
mimeType String?
isPinned Boolean @default(false)
pinnedAt DateTime?
pinnedById String?
createdAt DateTime @default(now())
editedAt DateTime?
deletedAt DateTime?
@@ -446,6 +449,7 @@ model ChatMessage {
poll ChatPoll?
@@index([roomId, createdAt])
@@index([roomId, isPinned, pinnedAt])
}
model ChatPoll {
@@ -603,6 +607,8 @@ model BotMessage {
text String?
mediaUrl String?
payload Json?
isPinned Boolean @default(false)
pinnedAt DateTime?
createdAt DateTime @default(now())
editedAt DateTime?
bot Bot @relation(fields: [botId], references: [id], onDelete: Cascade)
@@ -610,6 +616,7 @@ model BotMessage {
@@unique([botId, telegramMsgId])
@@index([botChatId])
@@index([botChatId, isPinned, pinnedAt])
}
model BotInboundMessage {

View File

@@ -908,11 +908,15 @@ export class AuthGrpcController {
}
@GrpcMethod('FamilyService', 'SendFamilyInvite')
sendFamilyInvite(command: { requesterId: string; groupId: string; target?: string; inviteeUserId?: string }) {
return this.family.sendInvite(command.requesterId, command.groupId, {
async sendFamilyInvite(command: { requesterId: string; groupId: string; target?: string; inviteeUserId?: string }) {
const invite = await this.family.sendInvite(command.requesterId, command.groupId, {
target: command.target,
inviteeUserId: command.inviteeUserId
});
if (invite.status === 'ACCEPTED') {
await this.chat.syncFamilyChats(command.groupId);
}
return invite;
}
@GrpcMethod('FamilyService', 'SearchFamilyInviteUsers')
@@ -935,20 +939,6 @@ export class AuthGrpcController {
return this.presence.getFamilyPresence(command.requesterId, command.groupId);
}
@GrpcMethod('FamilyService', 'AddBotFatherToFamily')
async addBotFatherToFamily(command: { requesterId: string; groupId: string }) {
const member = await this.family.addBotFatherToFamily(command.requesterId, command.groupId);
await this.chat.syncFamilyChats(command.groupId);
return member;
}
@GrpcMethod('FamilyService', 'AddBotToFamily')
async addBotToFamily(command: { requesterId: string; groupId: string; botId: string }) {
const member = await this.family.addBotToFamily(command.requesterId, command.groupId, command.botId);
await this.chat.syncFamilyChats(command.groupId);
return member;
}
@GrpcMethod('NotificationsService', 'ListNotifications')
listNotifications(command: { userId: string; limit?: number; unreadOnly?: boolean }) {
return this.notifications.list(command.userId, command.limit, command.unreadOnly);
@@ -1066,6 +1056,11 @@ export class AuthGrpcController {
return this.chat.deleteMessage(command.userId, command.messageId);
}
@GrpcMethod('ChatService', 'SetMessagePinned')
setChatMessagePinned(command: { userId: string; messageId: string; pinned: boolean }) {
return this.chat.setMessagePinned(command.userId, command.messageId, Boolean(command.pinned));
}
@GrpcMethod('ChatService', 'ToggleMessageReaction')
toggleMessageReaction(command: { userId: string; messageId: string; emoji: string }) {
return this.chat.toggleMessageReaction(command.userId, command.messageId, command.emoji);

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 {

View File

@@ -607,6 +607,33 @@ export class ChatService {
return response;
}
async setMessagePinned(userId: string, messageId: string, pinned: boolean) {
const message = await this.prisma.chatMessage.findUnique({
where: { id: messageId },
include: { room: { include: { members: true } } }
});
if (!message || message.deletedAt) {
throw new NotFoundException('Сообщение не найдено');
}
if (message.room.type === 'BOT') {
throw new BadRequestException('Сообщения бота закрепляются через Bot API');
}
if (!message.room.members.some((member) => member.userId === userId)) {
throw new ForbiddenException('Вы не состоите в этом чате');
}
await this.prisma.chatMessage.update({
where: { id: messageId },
data: pinned
? { isPinned: true, pinnedAt: new Date(), pinnedById: userId }
: { isPinned: false, pinnedAt: null, pinnedById: null }
});
const response = await this.loadMessageResponse(messageId, userId);
await this.publishRoomEvent(message.room, 'chat_message_updated', response);
return response;
}
async toggleMessageReaction(userId: string, messageId: string, emoji: string) {
const normalizedEmoji = emoji.trim();
if (!normalizedEmoji || normalizedEmoji.length > 16) {
@@ -1016,6 +1043,9 @@ export class ChatService {
storageKey: string | null;
mimeType: string | null;
metadata: unknown;
isPinned?: boolean;
pinnedAt?: Date | null;
pinnedById?: string | null;
createdAt: Date;
editedAt?: Date | null;
deletedAt?: Date | null;
@@ -1060,6 +1090,9 @@ export class ChatService {
isDeleted,
readByAll: message.senderId === viewerId ? readByAll : undefined,
reactions: isDeleted ? [] : this.buildReactionResponses(message.metadata, viewerId),
isPinned: !isDeleted && Boolean(message.isPinned),
pinnedAt: !isDeleted ? message.pinnedAt?.toISOString() : undefined,
pinnedById: !isDeleted ? message.pinnedById ?? undefined : undefined,
poll: !isDeleted && message.poll
? {
id: message.poll.id,
@@ -1202,6 +1235,9 @@ export class ChatService {
isDeleted: false,
readByAll: undefined,
reactions: [],
isPinned: false,
pinnedAt: undefined,
pinnedById: undefined,
poll: undefined
};
}

View File

@@ -9,7 +9,14 @@ import { NotificationsService } from './notifications.service';
import { MinioService } from '../infra/minio.service';
import { BotFatherSeedService } from './bot/bot-father-seed.service';
import { BotFatherService } from './bot/bot-father.service';
import { BOTFATHER_BOT_USERNAME, BOTFATHER_DISPLAY_NAME, BOTFATHER_USER_USERNAME } from './bot/bot-father.constants';
import {
BOTFATHER_BOT_USERNAME,
BOTFATHER_DISPLAY_NAME,
BOTFATHER_USER_USERNAME,
GET_MY_ID_BOT_USERNAME,
GET_MY_ID_DISPLAY_NAME,
GET_MY_ID_USER_USERNAME
} from './bot/bot-father.constants';
import { normalizeBotUsername } from './bot/bot-token.util';
import { HUMAN_USER_WHERE, isProtectedSystemAccount } from './system-account.util';
@@ -386,49 +393,6 @@ export class FamilyService {
async addBotFatherToFamily(requesterId: string, groupId: string) {
const group = await this.getGroupWithMembers(groupId);
this.assertMember(group, requesterId);
const botFatherUserId = await this.botFatherSeed.getBotFatherUserId();
if (group.members.some((member) => member.userId === botFatherUserId)) {
throw new BadRequestException('BotFather уже добавлен в эту семью');
}
return this.addMember(groupId, botFatherUserId, 'bot');
}
async addBotToFamily(requesterId: string, groupId: string, botId: string) {
const group = await this.getGroupWithMembers(groupId);
this.assertMember(group, requesterId);
const bot = await this.prisma.bot.findUnique({
where: { id: botId },
select: { id: true, isActive: true, username: true, name: true }
});
if (!bot) {
throw new NotFoundException('Бот не найден');
}
if (!bot.isActive) {
throw new BadRequestException('Бот деактивирован и не может быть добавлен в семью');
}
const { userId: botSystemUserId } = await this.botFather.ensureBotSystemUser(bot.id);
if (group.members.some((member) => member.userId === botSystemUserId)) {
throw new BadRequestException('Этот бот уже добавлен в семью');
}
return this.addMember(groupId, botSystemUserId, 'bot');
}
async removeMember(requesterId: string, memberId: string) {
const member = await this.prisma.familyMember.findUnique({
@@ -483,7 +447,7 @@ export class FamilyService {
const invitee = options.inviteeUserId
? await this.prisma.user.findFirst({
where: { id: options.inviteeUserId, status: 'ACTIVE', deletedAt: null, ...HUMAN_USER_WHERE }
where: { id: options.inviteeUserId, status: 'ACTIVE', deletedAt: null }
})
: options.target
? await this.findUserByContact(options.target)
@@ -493,10 +457,6 @@ export class FamilyService {
throw new BadRequestException('Пользователь не найден. Выберите его из результатов поиска.');
}
if (isProtectedSystemAccount(invitee)) {
throw new BadRequestException('BotFather добавляется через отдельное действие «Добавить BotFather»');
}
if (invitee.id === requesterId) {
throw new BadRequestException('Нельзя пригласить самого себя');
}
@@ -513,6 +473,35 @@ export class FamilyService {
}
const inviter = await this.prisma.user.findUnique({ where: { id: requesterId } });
const isBotInvite = isProtectedSystemAccount(invitee);
if (isBotInvite) {
const invite = await this.prisma.familyInvite.create({
data: {
groupId,
inviterId: requesterId,
inviteeUserId: invitee.id,
targetEmail: invitee.email ?? undefined,
targetPhone: invitee.phone ?? undefined,
status: 'ACCEPTED',
expiresAt: new Date(Date.now() + INVITE_TTL_DAYS * 24 * 60 * 60 * 1000)
},
include: {
group: true,
inviter: true
}
});
await this.addMember(groupId, invitee.id, 'bot');
await this.notifications.create(
requesterId,
'family_bot_added',
'Бот добавлен в семью',
`${invitee.displayName} добавлен(а) в «${group.name}» по приглашению`,
{ groupId, inviteId: invite.id, botUserId: invitee.id },
{ skipPublish: true }
);
return this.toInvite(invite);
}
const invite = await this.prisma.familyInvite.create({
data: {
groupId,
@@ -555,10 +544,17 @@ export class FamilyService {
.filter((username): username is string => Boolean(username))
);
const botFatherUserId = await this.botFatherSeed.getBotFatherUserId();
const botFatherBotId = await this.botFatherSeed.getBotFatherBotId();
const getMyIdUserId = await this.botFatherSeed.getGetMyIdBotUserId();
const getMyIdBotId = await this.botFatherSeed.getGetMyIdBotId();
const botFatherMatches =
/bot\s*father|бот\s*father|botfather/i.test(trimmed) &&
!excludedIds.includes(botFatherUserId) &&
!excludedBotUsernames.has(BOTFATHER_BOT_USERNAME);
const getMyIdMatches =
/get\s*my\s*id|getmyid|мой\s*id|айди|chat[_\s-]*id/i.test(trimmed) &&
!excludedIds.includes(getMyIdUserId) &&
!excludedBotUsernames.has(GET_MY_ID_BOT_USERNAME);
const digits = trimmed.replace(/\D/g, '');
const normalizedBotQuery = normalizeBotUsername(trimmed.replace(/^@/, ''));
@@ -624,6 +620,8 @@ export class FamilyService {
for (const bot of matchedBots) {
if (excludedBotUsernames.has(bot.username)) continue;
if (botFatherMatches && bot.username === BOTFATHER_BOT_USERNAME) continue;
if (getMyIdMatches && bot.username === GET_MY_ID_BOT_USERNAME) continue;
const { userId } = bot.linkedSystemUser
? { userId: bot.linkedSystemUser.id }
: await this.botFather.ensureBotSystemUser(bot.id);
@@ -672,7 +670,25 @@ export class FamilyService {
verificationIcon: resolveVerificationIcon('bot'),
isBot: true,
botUsername: BOTFATHER_BOT_USERNAME,
botId: undefined,
botId: botFatherBotId,
ownerDisplayName: undefined
}
]
: []),
...(getMyIdMatches
? [
{
id: getMyIdUserId,
displayName: GET_MY_ID_DISPLAY_NAME,
email: undefined,
phone: undefined,
username: GET_MY_ID_USER_USERNAME,
hasAvatar: false,
isVerified: true,
verificationIcon: resolveVerificationIcon('bot'),
isBot: true,
botUsername: GET_MY_ID_BOT_USERNAME,
botId: getMyIdBotId,
ownerDisplayName: undefined
}
]
@@ -1004,6 +1020,10 @@ export class FamilyService {
botFatherAvailable: !group.members.some(
(member) => member.user?.linkedBot?.username === BOTFATHER_BOT_USERNAME
),
getMyIdBotAvailable: !group.members.some(
(member) => member.user?.linkedBot?.username === GET_MY_ID_BOT_USERNAME
)
};

View File

@@ -5,7 +5,7 @@ export type SystemAccountProbe = {
linkedBotId?: string | null;
};
export const RESERVED_SYSTEM_USERNAMES = new Set(['botfather', 'system-bot-owner']);
export const RESERVED_SYSTEM_USERNAMES = new Set(['botfather', 'getmyidbot', 'system-bot-owner']);
export function isProtectedSystemAccount(user: SystemAccountProbe | null | undefined): boolean {
if (!user) return false;