コード例 #1
0
ファイル: Cooldown.cs プロジェクト: alexlyee/hs-bot
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, Discord.Commands.CommandInfo command, IServiceProvider services)
        {
            // Check if the user is administrator and if it needs to apply cooldown for him.
            if (!AdminsAreLimited && context.User is IGuildUser user && user.GuildPermissions.Administrator)
            {
                return(Task.FromResult(PreconditionResult.FromSuccess()));
            }

            var key = new CooldownInfo(context.User.Id, command.GetHashCode());

            // Check if message with the same hash code is already in dictionary
            if (_cooldowns.TryGetValue(key, out DateTime endsAt))
            {
                // Calculate the difference between current time and the time cooldown should end
                var difference = endsAt.Subtract(DateTime.UtcNow);
                // Display message if command is on cooldown
                if (difference.Ticks > 0 && AnnounceCooldownLength)
                {
                    return(Task.FromResult(PreconditionResult.FromError($"You can use this command in {difference.ToString(@"mm\:ss")}")));
                }
                // Update cooldown time
                var time = DateTime.UtcNow.Add(CooldownLength);
                _cooldowns.TryUpdate(key, time, endsAt);
            }
            else
            {
                _cooldowns.TryAdd(key, DateTime.UtcNow.Add(CooldownLength));
            }

            return(Task.FromResult(PreconditionResult.FromSuccess()));
        }