fixes
All checks were successful
SonarQube / Build and analyze (push) Successful in 2m57s

This commit is contained in:
Leonid Pershin
2025-10-22 03:28:48 +03:00
parent 1996fec14f
commit 0e5c418a0e
8 changed files with 492 additions and 64 deletions

28
ChatBot/.dockerignore Normal file
View File

@@ -0,0 +1,28 @@
# Build artifacts
bin/
obj/
out/
publish/
# IDE and editor files
.vs/
.vscode/
.idea/
*.suo
*.user
*.userosscache
*.sln.docstates
# Environment files (will be injected via secrets)
.env
.env.*
!.env.example
# Logs
logs/
*.log
# Test results
TestResults/
*.trx
*.coverage

42
ChatBot/Dockerfile Normal file
View File

@@ -0,0 +1,42 @@
# Build stage
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
# Copy project file
COPY ChatBot.csproj ./
# Restore dependencies
RUN dotnet restore
# Copy all source files
COPY . .
# Build the application
RUN dotnet build -c Release -o /app/build
# Publish stage
FROM build AS publish
RUN dotnet publish -c Release -o /app/publish /p:UseAppHost=false
# Runtime stage
FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS final
WORKDIR /app
# Install PostgreSQL client for healthcheck (optional)
RUN apt-get update && apt-get install -y postgresql-client && rm -rf /var/lib/apt/lists/*
# Copy published application
COPY --from=publish /app/publish .
# Create directory for logs
RUN mkdir -p /app/logs && chmod 777 /app/logs
# Expose ports (if needed for health checks or metrics)
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD dotnet ChatBot.dll --health-check || exit 1
# Run the application
ENTRYPOINT ["dotnet", "ChatBot.dll"]

View File

@@ -1,5 +1,6 @@
using ChatBot.Services.Telegram.Interfaces;
using ChatBot.Services.Telegram.Services;
using Telegram.Bot.Types;
namespace ChatBot.Services.Telegram.Commands
{
@@ -58,51 +59,13 @@ namespace ChatBot.Services.Telegram.Commands
try
{
// Получаем информацию о боте
var botInfo = await _botInfoService.GetBotInfoAsync(cancellationToken);
// Проверяем, нужно ли отвечать на реплай
if (replyInfo != null)
if (!ShouldProcessMessage(messageText, chatId, replyInfo, botInfo))
{
_logger.LogInformation(
"Reply detected: ReplyToUserId={ReplyToUserId}, BotId={BotId}, ChatId={ChatId}",
replyInfo.UserId,
botInfo?.Id,
chatId
);
if (botInfo != null && replyInfo.UserId != botInfo.Id)
{
_logger.LogInformation(
"Ignoring reply to user {ReplyToUserId} (not bot {BotId}) in chat {ChatId}",
replyInfo.UserId,
botInfo.Id,
chatId
);
return string.Empty; // Не отвечаем на реплаи другим пользователям
}
}
else
{
// Если это не реплай, проверяем, обращаются ли к боту или нет упоминаний других пользователей
if (botInfo != null)
{
bool hasBotMention = messageText.Contains($"@{botInfo.Username}");
bool hasOtherMentions = messageText.Contains('@') && !hasBotMention;
if (!hasBotMention && hasOtherMentions)
{
_logger.LogInformation(
"Ignoring message with other user mentions in chat {ChatId}: {MessageText}",
chatId,
messageText
);
return string.Empty; // Не отвечаем на сообщения с упоминанием других пользователей
}
}
return string.Empty;
}
// Создаем контекст команды
var context = TelegramCommandContext.Create(
chatId,
username,
@@ -112,27 +75,11 @@ namespace ChatBot.Services.Telegram.Commands
replyInfo
);
// Ищем команду, которая может обработать сообщение
var command = _commandRegistry.FindCommandForMessage(messageText);
if (command != null)
{
_logger.LogDebug(
"Executing command {CommandName} for chat {ChatId}",
command.CommandName,
chatId
);
return await command.ExecuteAsync(context, cancellationToken);
}
// Если команда не найдена, обрабатываем как обычное сообщение
_logger.LogDebug(
"No command found, processing as regular message for chat {ChatId}",
chatId
);
return await _chatService.ProcessMessageAsync(
return await ExecuteCommandOrProcessMessageAsync(
context,
messageText,
chatId,
username,
messageText,
chatType,
chatTitle,
cancellationToken
@@ -159,5 +106,101 @@ namespace ChatBot.Services.Telegram.Commands
return "Произошла непредвиденная ошибка. Попробуйте еще раз.";
}
}
private bool ShouldProcessMessage(
string messageText,
long chatId,
ReplyInfo? replyInfo,
User? botInfo
)
{
if (replyInfo != null)
{
return ShouldProcessReply(replyInfo, botInfo, chatId);
}
return ShouldProcessNonReplyMessage(messageText, botInfo, chatId);
}
private bool ShouldProcessReply(ReplyInfo replyInfo, User? botInfo, long chatId)
{
_logger.LogInformation(
"Reply detected: ReplyToUserId={ReplyToUserId}, BotId={BotId}, ChatId={ChatId}",
replyInfo.UserId,
botInfo?.Id,
chatId
);
if (botInfo != null && replyInfo.UserId != botInfo.Id)
{
_logger.LogInformation(
"Ignoring reply to user {ReplyToUserId} (not bot {BotId}) in chat {ChatId}",
replyInfo.UserId,
botInfo.Id,
chatId
);
return false;
}
return true;
}
private bool ShouldProcessNonReplyMessage(string messageText, User? botInfo, long chatId)
{
if (botInfo == null)
{
return true;
}
bool hasBotMention = messageText.Contains($"@{botInfo.Username}");
bool hasOtherMentions = messageText.Contains('@') && !hasBotMention;
if (!hasBotMention && hasOtherMentions)
{
_logger.LogInformation(
"Ignoring message with other user mentions in chat {ChatId}: {MessageText}",
chatId,
messageText
);
return false;
}
return true;
}
private async Task<string> ExecuteCommandOrProcessMessageAsync(
TelegramCommandContext context,
string messageText,
long chatId,
string username,
string chatType,
string chatTitle,
CancellationToken cancellationToken
)
{
var command = _commandRegistry.FindCommandForMessage(messageText);
if (command != null)
{
_logger.LogDebug(
"Executing command {CommandName} for chat {ChatId}",
command.CommandName,
chatId
);
return await command.ExecuteAsync(context, cancellationToken);
}
_logger.LogDebug(
"No command found, processing as regular message for chat {ChatId}",
chatId
);
return await _chatService.ProcessMessageAsync(
chatId,
username,
messageText,
chatType,
chatTitle,
cancellationToken
);
}
}
}