Stop all bot for a user

This commit is contained in:
2025-08-06 16:03:42 +07:00
parent b70018ba15
commit 93a6f9fd9e
3 changed files with 107 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
using Managing.Application.Abstractions;
using Managing.Application.ManageBot.Commands;
using MediatR;
using Microsoft.Extensions.Logging;
using static Managing.Common.Enums;
namespace Managing.Application.ManageBot
{
public class StopAllUserBotsCommandHandler : IRequestHandler<StopAllUserBotsCommand, bool>
{
private readonly IBotService _botService;
private readonly ILogger<StopAllUserBotsCommandHandler> _logger;
public StopAllUserBotsCommandHandler(IBotService botService, ILogger<StopAllUserBotsCommandHandler> logger)
{
_botService = botService;
_logger = logger;
}
public async Task<bool> Handle(StopAllUserBotsCommand request, CancellationToken cancellationToken)
{
try
{
// Get all bots for the user
var userBots = await _botService.GetBotsByUser(request.User.Id);
// Filter only active bots (status Up)
var activeBots = userBots.Where(bot => bot.Status == BotStatus.Up).ToList();
if (!activeBots.Any())
{
_logger.LogInformation("No active bots found for user {UserName}", request.User.Name);
return true;
}
_logger.LogInformation("Stopping {BotCount} active bots for user {UserName}",
activeBots.Count, request.User.Name);
// Stop each active bot
var stopTasks = activeBots.Select(bot => _botService.StopBot(bot.Identifier));
await Task.WhenAll(stopTasks);
_logger.LogInformation("Successfully stopped {BotCount} bots for user {UserName}",
activeBots.Count, request.User.Name);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error stopping all bots for user {UserName}", request.User.Name);
return false;
}
}
}
}