Skip to content

Commit

Permalink
move deprecated gift command to .NET
Browse files Browse the repository at this point in the history
  • Loading branch information
adamgauthier committed Dec 4, 2023
1 parent 96842be commit d9f481a
Show file tree
Hide file tree
Showing 16 changed files with 211 additions and 344 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,39 +11,22 @@

namespace TaylorBot.Net.Commands.DiscordNet;

public class CommandExecutedHandler
{
private readonly ILogger<CommandExecutedHandler> _logger;
private readonly IOngoingCommandRepository _ongoingCommandRepository;
private readonly ICommandUsageRepository _commandUsageRepository;
private readonly IIgnoredUserRepository _ignoredUserRepository;
private readonly PageMessageReactionsHandler _pageMessageReactionsHandler;
private readonly UserNotIgnoredPrecondition _userNotIgnoredPrecondition;

public CommandExecutedHandler(
ILogger<CommandExecutedHandler> logger,
IOngoingCommandRepository ongoingCommandRepository,
ICommandUsageRepository commandUsageRepository,
IIgnoredUserRepository ignoredUserRepository,
PageMessageReactionsHandler pageMessageReactionsHandler,
UserNotIgnoredPrecondition userNotIgnoredPrecondition
public class CommandExecutedHandler(
ILogger<CommandExecutedHandler> logger,
IOngoingCommandRepository ongoingCommandRepository,
ICommandUsageRepository commandUsageRepository,
IIgnoredUserRepository ignoredUserRepository,
PageMessageReactionsHandler pageMessageReactionsHandler,
UserNotIgnoredPrecondition userNotIgnoredPrecondition
)
{
_logger = logger;
_ongoingCommandRepository = ongoingCommandRepository;
_commandUsageRepository = commandUsageRepository;
_ignoredUserRepository = ignoredUserRepository;
_pageMessageReactionsHandler = pageMessageReactionsHandler;
_userNotIgnoredPrecondition = userNotIgnoredPrecondition;
}

{
public async Task OnCommandExecutedAsync(Optional<CommandInfo> optCommandInfo, ICommandContext context, IResult result)
{
var commandContext = (ITaylorBotCommandContext)context;

if (result.Error != CommandError.UnknownCommand)
{
_logger.LogInformation($"{context.User.FormatLog()} used '{context.Message.Content.Replace("\n", "\\n")}' in {context.Channel.FormatLog()}");
logger.LogInformation($"{context.User.FormatLog()} used '{context.Message.Content.Replace("\n", "\\n")}' in {context.Channel.FormatLog()}");

if (result.IsSuccess)
{
Expand All @@ -68,7 +51,7 @@ await context.Channel.SendMessageAsync(

case PageMessageResult pageResult:
var sentPageMessage = await pageResult.PageMessage.SendAsync(context.User, context.Channel);
await sentPageMessage.SendReactionsAsync(_pageMessageReactionsHandler, _logger);
await sentPageMessage.SendReactionsAsync(pageMessageReactionsHandler, logger);
break;

case RateLimitedResult rateLimited:
Expand All @@ -91,7 +74,7 @@ await context.Channel.SendMessageAsync(
.Append($"You won't stop despite being warned, **I think you are a bot and will ignore you for {ignoreTime.Humanize(culture: TaylorBotCulture.Culture)}.**")
.ToArray();

await _ignoredUserRepository.IgnoreUntilAsync(context.User, DateTimeOffset.Now + ignoreTime);
await ignoredUserRepository.IgnoreUntilAsync(context.User, DateTimeOffset.Now + ignoreTime);
}

await context.Channel.SendMessageAsync(
Expand All @@ -104,7 +87,7 @@ await context.Channel.SendMessageAsync(
break;

case PreconditionFailed failed:
_logger.LogInformation($"{commandContext.User.FormatLog()} precondition failure: {failed.PrivateReason}.");
logger.LogInformation($"{commandContext.User.FormatLog()} precondition failure: {failed.PrivateReason}.");
if (!failed.UserReason.HideInPrefixCommands)
{
await context.Channel.SendMessageAsync(embed: new EmbedBuilder()
Expand All @@ -121,7 +104,7 @@ await context.Channel.SendMessageAsync(
throw new InvalidOperationException($"Unexpected command success result: {innerResult.GetType()}");
}
if (optCommandInfo.IsSpecified)
_commandUsageRepository.QueueIncrementSuccessfulUseCount(optCommandInfo.Value.Aliases[0]);
commandUsageRepository.QueueIncrementSuccessfulUseCount(optCommandInfo.Value.Aliases[0]);
}
else
{
Expand All @@ -131,11 +114,11 @@ await context.Channel.SendMessageAsync(
switch (result.Error)
{
case CommandError.Exception:
_logger.LogError(executeResult.Exception, "Unhandled exception in command:");
logger.LogError(executeResult.Exception, "Unhandled exception in command:");
break;

default:
_logger.LogError(executeResult.Exception, $"Unhandled error in command - {result.Error}, {result.ErrorReason}:");
logger.LogError(executeResult.Exception, $"Unhandled error in command - {result.Error}, {result.ErrorReason}:");
break;
}
await context.Channel.SendMessageAsync(
Expand All @@ -144,12 +127,12 @@ await context.Channel.SendMessageAsync(
embed: CreateUnknownErrorEmbed()
);
if (optCommandInfo.IsSpecified)
_commandUsageRepository.QueueIncrementUnhandledErrorCount(optCommandInfo.Value.Aliases[0]);
commandUsageRepository.QueueIncrementUnhandledErrorCount(optCommandInfo.Value.Aliases[0]);
break;

case ParseResult parseResult:
// Preconditions have not been executed, we must make sure the user is not ignored.
var runResult = await _userNotIgnoredPrecondition.CanRunAsync(
var runResult = await userNotIgnoredPrecondition.CanRunAsync(
new Command(DiscordNetContextMapper.MapToCommandMetadata(commandContext), () => new()),
DiscordNetContextMapper.MapToRunContext(commandContext)
);
Expand All @@ -168,12 +151,12 @@ await context.Channel.SendMessageAsync(
}
else
{
_logger.LogInformation($"{commandContext.User.FormatLog()} precondition failure: {failed.PrivateReason}.");
logger.LogInformation($"{commandContext.User.FormatLog()} precondition failure: {failed.PrivateReason}.");
}
break;

default:
_logger.LogError($"Unhandled error in command - {result.Error}, {result.ErrorReason}");
logger.LogError($"Unhandled error in command - {result.Error}, {result.ErrorReason}");
await context.Channel.SendMessageAsync(
messageReference: new(context.Message.Id),
allowedMentions: new AllowedMentions { MentionRepliedUser = false },
Expand All @@ -186,7 +169,7 @@ await context.Channel.SendMessageAsync(

if (commandContext.RunContext?.OnGoing.OnGoingCommandAddedToPool != null)
{
await _ongoingCommandRepository.RemoveOngoingCommandAsync(context.User, commandContext.RunContext.OnGoing.OnGoingCommandAddedToPool);
await ongoingCommandRepository.RemoveOngoingCommandAsync(context.User, commandContext.RunContext.OnGoing.OnGoingCommandAddedToPool);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,8 @@

namespace TaylorBot.Net.Commands.DiscordNet;

public class TaylorBotResult : RuntimeResult
public class TaylorBotResult(ICommandResult result, RunContext context) : RuntimeResult(error: null, reason: null)
{
public ICommandResult Result { get; }
public RunContext Context { get; }

public TaylorBotResult(ICommandResult result, RunContext context) : base(error: null, reason: null)
{
Result = result;
Context = context;
}
public ICommandResult Result { get; } = result;
public RunContext Context { get; } = context;
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
commandService.AddTypeReader<IMentionedUser<IUser>>(_serviceProvider.GetRequiredService<MentionedUserTypeReader<IUser>>());
commandService.AddTypeReader<IMentionedUser<IGuildUser>>(_serviceProvider.GetRequiredService<MentionedUserTypeReader<IGuildUser>>());
commandService.AddTypeReader<IMentionedUserNotAuthor<IUser>>(_serviceProvider.GetRequiredService<MentionedUserNotAuthorTypeReader<IUser>>());
commandService.AddTypeReader<IReadOnlyCollection<IMentionedUserNotAuthor<IUser>>>(_serviceProvider.GetRequiredService<MentionedUsersNotAuthorTypeReader<IUser>>());
commandService.AddTypeReader<IReadOnlyList<IMentionedUserNotAuthor<IUser>>>(_serviceProvider.GetRequiredService<MentionedUsersNotAuthorTypeReader<IUser>>());
commandService.AddTypeReader<IMentionedUserNotAuthor<IGuildUser>>(_serviceProvider.GetRequiredService<MentionedUserNotAuthorTypeReader<IGuildUser>>());
commandService.AddTypeReader<IMentionedUserNotAuthorOrClient<IGuildUser>>(_serviceProvider.GetRequiredService<MentionedUserNotAuthorOrClientTypeReader<IGuildUser>>());
commandService.AddTypeReader<RoleArgument<IRole>>(_serviceProvider.GetRequiredService<CustomRoleTypeReader<IRole>>());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,18 @@ namespace TaylorBot.Net.Commands.Types;

public interface IMentionedUserNotAuthor<T> : IUserArgument<T> where T : class, IUser { }

public class MentionedUserNotAuthorTypeReader<T> : TypeReader
public class MentionedUserNotAuthorTypeReader<T>(MentionedUserTypeReader<T> mentionedUserTypeReader) : TypeReader
where T : class, IUser
{
private readonly MentionedUserTypeReader<T> _mentionedUserTypeReader;

public MentionedUserNotAuthorTypeReader(MentionedUserTypeReader<T> mentionedUserTypeReader)
{
_mentionedUserTypeReader = mentionedUserTypeReader;
}

public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
var result = await _mentionedUserTypeReader.ReadAsync(context, input, services);
var result = await mentionedUserTypeReader.ReadAsync(context, input, services);
if (result.Values != null)
{
var mentioned = (IUserArgument<T>)result.BestMatch;
if (mentioned.UserId == context.User.Id)
{
return TypeReaderResult.FromError(CommandError.ParseFailed, $"You can't mention yourself.");
return TypeReaderResult.FromError(CommandError.ParseFailed, "You can't mention yourself.");
}
return TypeReaderResult.FromSuccess(mentioned);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,21 @@

namespace TaylorBot.Net.Commands.Types;

public class MentionedUsersNotAuthorTypeReader<T> : TypeReader
public class MentionedUsersNotAuthorTypeReader<T>(MentionedUserNotAuthorTypeReader<T> mentionedUserNotAuthorTypeReader) : TypeReader
where T : class, IUser
{
private readonly MentionedUserNotAuthorTypeReader<T> _mentionedUserNotAuthorTypeReader;

public MentionedUsersNotAuthorTypeReader(MentionedUserNotAuthorTypeReader<T> mentionedUserNotAuthorTypeReader)
{
_mentionedUserNotAuthorTypeReader = mentionedUserNotAuthorTypeReader;
}
private const int MaxMentionCount = 25;

public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
var split = input.Split(' ').Where(i => i != string.Empty);
var split = input.Split(' ').Select(u => u.Trim()).Where(i => i != string.Empty).ToList();


var results = new List<IMentionedUserNotAuthor<T>>();

foreach (var mention in split)
{
var result = await _mentionedUserNotAuthorTypeReader.ReadAsync(context, mention, services);
var result = await mentionedUserNotAuthorTypeReader.ReadAsync(context, mention, services);
if (result.Values != null)
{
results.Add((IMentionedUserNotAuthor<T>)result.BestMatch);
Expand All @@ -32,8 +28,13 @@ public override async Task<TypeReaderResult> ReadAsync(ICommandContext context,
}
}

var distinct = results.GroupBy(r => r.UserId).Select(g => g.First());
var distinct = results.DistinctBy(r => r.UserId).ToList();

if (distinct.Count > MaxMentionCount)
{
return TypeReaderResult.FromError(CommandError.ParseFailed, $"You can't mention more than {MaxMentionCount} people.");
}

return TypeReaderResult.FromSuccess(distinct.ToList());
return TypeReaderResult.FromSuccess(distinct);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,16 @@
namespace TaylorBot.Net.Commands.Discord.Program.Modules.TaypointReward.Commands;

[Name("Reward 🎖")]
public class RewardModule : TaylorBotModule
public class RewardModule(ICommandRunner commandRunner, ITaypointRewardRepository taypointRepository) : TaylorBotModule
{
private readonly ICommandRunner _commandRunner;
private readonly ITaypointRewardRepository _taypointRepository;

public RewardModule(ICommandRunner commandRunner, ITaypointRewardRepository taypointRepository)
{
_commandRunner = commandRunner;
_taypointRepository = taypointRepository;
}

[Command("reward")]
[Summary("Rewards a specified amount of taypoints to pinged users.")]
public async Task<RuntimeResult> RewardAsync(
[Summary("How much taypoints do you want to reward each user?")]
PositiveInt32 taypoints,
[Remainder]
[Summary("What users would you like to reward taypoints to (must be mentioned)?")]
IReadOnlyCollection<IMentionedUserNotAuthor<IUser>> users
IReadOnlyList<IMentionedUserNotAuthor<IUser>> users
)
{
var command = new Command(
Expand All @@ -43,23 +34,25 @@ IReadOnlyCollection<IMentionedUserNotAuthor<IUser>> users
trackedUsers.Add(await user.GetTrackedUserAsync());
}
var rewardedUsers = await _taypointRepository.RewardUsersAsync(trackedUsers, taypoints.Parsed);
var rewardedUsers = await taypointRepository.RewardUsersAsync(trackedUsers, taypoints.Parsed);
return new EmbedResult(new EmbedBuilder()
.WithUserAsAuthor(Context.User)
.WithColor(TaylorBotColors.SuccessColor)
.WithDescription(string.Join('\n', new[] {
$"Successfully rewarded {"taypoint".ToQuantity(taypoints.Parsed, TaylorBotFormats.BoldReadable)} to:"
}.Concat(rewardedUsers.Select(
u => $"{MentionUtils.MentionUser(u.UserId.Id)} - now has {u.NewTaypointCount.ToString(TaylorBotFormats.BoldReadable)}"
))).Truncate(EmbedBuilder.MaxDescriptionLength))
.WithDescription(
$"""
Successfully rewarded {"taypoint".ToQuantity(taypoints.Parsed, TaylorBotFormats.BoldReadable)} to:
{string.Join('\n', rewardedUsers.Select(
u => $"{MentionUtils.MentionUser(u.UserId)} - now has {u.NewTaypointCount.ToString(TaylorBotFormats.BoldReadable)}"
))}
""".Truncate(EmbedBuilder.MaxDescriptionLength))
.Build());
},
Preconditions: new[] { new TaylorBotOwnerPrecondition() }
);

var context = DiscordNetContextMapper.MapToRunContext(Context);
var result = await _commandRunner.RunAsync(command, context);
var result = await commandRunner.RunAsync(command, context);

return new TaylorBotResult(result, context);
}
Expand Down
Loading

0 comments on commit d9f481a

Please sign in to comment.