Applied codestyle to all .cs files

This commit is contained in:
Kwoth
2021-12-29 06:07:16 +01:00
parent 723447c7d4
commit 82000c97a4
543 changed files with 13221 additions and 14059 deletions

View File

@@ -1,11 +1,12 @@
#nullable disable
using Amazon.S3;
using NadekoBot.Modules.Help.Common;
using NadekoBot.Modules.Help.Services;
using NadekoBot.Modules.Permissions.Services;
using Newtonsoft.Json;
using System.Text;
using System.Text.Json;
using Amazon.S3;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace NadekoBot.Modules.Help;
@@ -22,8 +23,13 @@ public class Help : NadekoModule<HelpService>
private readonly AsyncLazy<ulong> _lazyClientId;
public Help(GlobalPermissionService perms, CommandService cmds, BotConfigService bss,
IServiceProvider services, DiscordSocketClient client, IBotStrings strings)
public Help(
GlobalPermissionService perms,
CommandService cmds,
BotConfigService bss,
IServiceProvider services,
DiscordSocketClient client,
IBotStrings strings)
{
_cmds = cmds;
_bss = bss;
@@ -40,57 +46,57 @@ public class Help : NadekoModule<HelpService>
var botSettings = _bss.Data;
if (string.IsNullOrWhiteSpace(botSettings.HelpText) || botSettings.HelpText == "-")
return default;
var clientId = await _lazyClientId.Value;
var r = new ReplacementBuilder()
.WithDefault(Context)
.WithOverride("{0}", () => clientId.ToString())
.WithOverride("{1}", () => Prefix)
.WithOverride("%prefix%", () => Prefix)
.WithOverride("%bot.prefix%", () => Prefix)
.Build();
var r = new ReplacementBuilder().WithDefault(Context)
.WithOverride("{0}", () => clientId.ToString())
.WithOverride("{1}", () => Prefix)
.WithOverride("%prefix%", () => Prefix)
.WithOverride("%bot.prefix%", () => Prefix)
.Build();
var text = SmartText.CreateFrom(botSettings.HelpText);
return r.Replace(text);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Modules(int page = 1)
{
if (--page < 0)
return;
var topLevelModules = _cmds.Modules.GroupBy(m => m.GetTopLevelModule())
.Where(m => !_perms.BlockedModules.Contains(m.Key.Name.ToLowerInvariant()))
.Select(x => x.Key)
.ToList();
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var embed = _eb.Create().WithOkColor()
.WithTitle(GetText(strs.list_of_modules));
.Where(m => !_perms.BlockedModules.Contains(m.Key.Name.ToLowerInvariant()))
.Select(x => x.Key)
.ToList();
var localModules = topLevelModules.Skip(12 * cur)
.Take(12)
.ToList();
if (!localModules.Any())
await ctx.SendPaginatedConfirmAsync(page,
cur =>
{
embed = embed.WithOkColor()
.WithDescription(GetText(strs.module_page_empty));
return embed;
}
localModules
.OrderBy(module => module.Name)
.ToList()
.ForEach(module => embed.AddField($"{GetModuleEmoji(module.Name)} {module.Name}",
GetText(GetModuleLocStr(module.Name)) + "\n" +
Format.Code(GetText(strs.module_footer(Prefix, module.Name.ToLowerInvariant()))),
true));
var embed = _eb.Create().WithOkColor().WithTitle(GetText(strs.list_of_modules));
return embed;
}, topLevelModules.Count(), 12, false);
var localModules = topLevelModules.Skip(12 * cur).Take(12).ToList();
if (!localModules.Any())
{
embed = embed.WithOkColor().WithDescription(GetText(strs.module_page_empty));
return embed;
}
localModules.OrderBy(module => module.Name)
.ToList()
.ForEach(module => embed.AddField($"{GetModuleEmoji(module.Name)} {module.Name}",
GetText(GetModuleLocStr(module.Name))
+ "\n"
+ Format.Code(GetText(strs.module_footer(Prefix, module.Name.ToLowerInvariant()))),
true));
return embed;
},
topLevelModules.Count(),
12,
false);
}
private LocStr GetModuleLocStr(string moduleName)
@@ -121,9 +127,9 @@ public class Help : NadekoModule<HelpService>
return strs.module_description_xp;
default:
return strs.module_description_missing;
}
}
private string GetModuleEmoji(string moduleName)
{
moduleName = moduleName.ToLowerInvariant();
@@ -153,11 +159,11 @@ public class Help : NadekoModule<HelpService>
return "📝";
default:
return "📖";
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[NadekoOptions(typeof(CommandsOptions))]
public async Task Commands(string module = null, params string[] args)
{
@@ -173,11 +179,14 @@ public class Help : NadekoModule<HelpService>
// Find commands for that module
// don't show commands which are blocked
// order by name
var cmds = _cmds.Commands.Where(c => c.Module.GetTopLevelModule().Name.ToUpperInvariant().StartsWith(module, StringComparison.InvariantCulture))
.Where(c => !_perms.BlockedCommands.Contains(c.Aliases[0].ToLowerInvariant()))
.OrderBy(c => c.Aliases[0])
.DistinctBy(x => x.Aliases[0])
.ToList();
var cmds = _cmds.Commands
.Where(c => c.Module.GetTopLevelModule()
.Name.ToUpperInvariant()
.StartsWith(module, StringComparison.InvariantCulture))
.Where(c => !_perms.BlockedCommands.Contains(c.Aliases[0].ToLowerInvariant()))
.OrderBy(c => c.Aliases[0])
.DistinctBy(x => x.Aliases[0])
.ToList();
// check preconditions for all commands, but only if it's not 'all'
@@ -186,22 +195,21 @@ public class Help : NadekoModule<HelpService>
if (opts.View != CommandsOptions.ViewType.All)
{
succ = new((await cmds.Select(async x =>
{
var pre = await x.CheckPreconditionsAsync(Context, _services);
return (Cmd: x, Succ: pre.IsSuccess);
}).WhenAll())
.Where(x => x.Succ)
.Select(x => x.Cmd));
{
var pre = await x.CheckPreconditionsAsync(Context, _services);
return (Cmd: x, Succ: pre.IsSuccess);
})
.WhenAll()).Where(x => x.Succ)
.Select(x => x.Cmd));
if (opts.View == CommandsOptions.ViewType.Hide)
{
// if hidden is specified, completely remove these commands from the list
cmds = cmds.Where(x => succ.Contains(x)).ToList();
}
}
var cmdsWithGroup = cmds.GroupBy(c => c.Module.Name.Replace("Commands", "", StringComparison.InvariantCulture))
.OrderBy(x => x.Key == x.First().Module.Name ? int.MaxValue : x.Count())
.ToList();
.OrderBy(x => x.Key == x.First().Module.Name ? int.MaxValue : x.Count())
.ToList();
if (cmdsWithGroup.Count == 0)
{
@@ -220,40 +228,40 @@ public class Help : NadekoModule<HelpService>
var last = g.Count();
for (var i = 0; i < last; i++)
{
var transformed = g.ElementAt(i).Select(x =>
{
//if cross is specified, and the command doesn't satisfy the requirements, cross it out
if (opts.View == CommandsOptions.ViewType.Cross)
{
return $"{(succ.Contains(x) ? "" : "")}{Prefix + x.Aliases.First(),-15} {"[" + x.Aliases.Skip(1).FirstOrDefault() + "]",-8}";
}
return $"{Prefix + x.Aliases.First(),-15} {"[" + x.Aliases.Skip(1).FirstOrDefault() + "]",-8}";
});
var transformed = g.ElementAt(i)
.Select(x =>
{
//if cross is specified, and the command doesn't satisfy the requirements, cross it out
if (opts.View == CommandsOptions.ViewType.Cross)
return
$"{(succ.Contains(x) ? "" : "")}{Prefix + x.Aliases.First(),-15} {"[" + x.Aliases.Skip(1).FirstOrDefault() + "]",-8}";
return
$"{Prefix + x.Aliases.First(),-15} {"[" + x.Aliases.Skip(1).FirstOrDefault() + "]",-8}";
});
if (i == last - 1 && (i + 1) % 2 != 0)
{
transformed = transformed
.Chunk(2)
.Select(x =>
{
if (x.Count() == 1)
return $"{x.First()}";
else
return String.Concat(x);
});
}
transformed = transformed.Chunk(2)
.Select(x =>
{
if (x.Count() == 1)
return $"{x.First()}";
return string.Concat(x);
});
embed.AddField(g.ElementAt(i).Key, "```css\n" + string.Join("\n", transformed) + "\n```", true);
}
}
embed.WithFooter(GetText(strs.commands_instr(Prefix)));
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[Priority(0)]
public async Task H([Leftover] string fail)
{
var prefixless = _cmds.Commands.FirstOrDefault(x => x.Aliases.Any(cmdName => cmdName.ToLowerInvariant() == fail));
var prefixless =
_cmds.Commands.FirstOrDefault(x => x.Aliases.Any(cmdName => cmdName.ToLowerInvariant() == fail));
if (prefixless != null)
{
await H(prefixless);
@@ -263,7 +271,8 @@ public class Help : NadekoModule<HelpService>
await ReplyErrorLocalizedAsync(strs.command_not_found);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[Priority(1)]
public async Task H([Leftover] CommandInfo com = null)
{
@@ -271,29 +280,30 @@ public class Help : NadekoModule<HelpService>
if (com is null)
{
var ch = channel is ITextChannel
? await ctx.User.CreateDMChannelAsync()
: channel;
var ch = channel is ITextChannel ? await ctx.User.CreateDMChannelAsync() : channel;
try
{
var data = await GetHelpString();
if (data == default)
return;
await ch.SendAsync(data);
try{ await ctx.OkAsync(); } catch { } // ignore if bot can't react
try { await ctx.OkAsync(); }
catch { } // ignore if bot can't react
}
catch (Exception)
{
await ReplyErrorLocalizedAsync(strs.cant_dm);
}
return;
}
var embed = _service.GetCommandHelp(com, ctx.Guild);
await channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public async Task GenCmdList()
{
@@ -301,35 +311,30 @@ public class Help : NadekoModule<HelpService>
// order commands by top level module name
// and make a dictionary of <ModuleName, Array<JsonCommandData>>
var cmdData = _cmds
.Commands
.GroupBy(x => x.Module.GetTopLevelModule().Name)
.OrderBy(x => x.Key)
.ToDictionary(
x => x.Key,
x => x.DistinctBy(c => c.Aliases.First())
.Select(com =>
{
List<string> optHelpStr = null;
var opt = ((NadekoOptionsAttribute)com.Attributes.FirstOrDefault(x => x is NadekoOptionsAttribute))?.OptionType;
if (opt != null)
{
optHelpStr = HelpService.GetCommandOptionHelpList(opt);
}
return new CommandJsonObject
{
Aliases = com.Aliases.Select(alias => Prefix + alias).ToArray(),
Description = com.RealSummary(_strings, ctx.Guild?.Id, Prefix),
Usage = com.RealRemarksArr(_strings, ctx.Guild?.Id, Prefix),
Submodule = com.Module.Name,
Module = com.Module.GetTopLevelModule().Name,
Options = optHelpStr,
Requirements = HelpService.GetCommandRequirements(com),
};
})
.ToList()
);
var cmdData = _cmds.Commands.GroupBy(x => x.Module.GetTopLevelModule().Name)
.OrderBy(x => x.Key)
.ToDictionary(x => x.Key,
x => x.DistinctBy(c => c.Aliases.First())
.Select(com =>
{
List<string> optHelpStr = null;
var opt = ((NadekoOptionsAttribute)com.Attributes.FirstOrDefault(x
=> x is NadekoOptionsAttribute))
?.OptionType;
if (opt != null) optHelpStr = HelpService.GetCommandOptionHelpList(opt);
return new CommandJsonObject
{
Aliases = com.Aliases.Select(alias => Prefix + alias).ToArray(),
Description = com.RealSummary(_strings, ctx.Guild?.Id, Prefix),
Usage = com.RealRemarksArr(_strings, ctx.Guild?.Id, Prefix),
Submodule = com.Module.Name,
Module = com.Module.GetTopLevelModule().Name,
Options = optHelpStr,
Requirements = HelpService.GetCommandRequirements(com)
};
})
.ToList());
var readableData = JsonConvert.SerializeObject(cmdData, Formatting.Indented);
var uploadData = JsonConvert.SerializeObject(cmdData, Formatting.None);
@@ -345,15 +350,14 @@ public class Help : NadekoModule<HelpService>
// if all env vars are set, upload the unindented file (to save space) there
if (!(serviceUrl is null || accessKey is null || secretAcccessKey is null))
{
var config = new AmazonS3Config {ServiceURL = serviceUrl};
var config = new AmazonS3Config { ServiceURL = serviceUrl };
using var dlClient = new AmazonS3Client(accessKey, secretAcccessKey, config);
var oldVersionObject = await dlClient.GetObjectAsync(new()
{
BucketName = "nadeko-pictures",
Key = "cmds/versions.json",
BucketName = "nadeko-pictures", Key = "cmds/versions.json"
});
using (var client = new AmazonS3Client(accessKey, secretAcccessKey, config))
{
await client.PutObjectAsync(new()
@@ -370,19 +374,15 @@ public class Help : NadekoModule<HelpService>
await using var ms = new MemoryStream();
await oldVersionObject.ResponseStream.CopyToAsync(ms);
var versionListString = Encoding.UTF8.GetString(ms.ToArray());
var versionList = System.Text.Json.JsonSerializer.Deserialize<List<string>>(versionListString);
var versionList = JsonSerializer.Deserialize<List<string>>(versionListString);
if (!versionList.Contains(StatsService.BotVersion))
{
// save the file with new version added
// versionList.Add(StatsService.BotVersion);
versionListString = System.Text.Json.JsonSerializer.Serialize(
versionList.Prepend(StatsService.BotVersion),
new JsonSerializerOptions()
{
WriteIndented = true
});
versionListString = JsonSerializer.Serialize(versionList.Prepend(StatsService.BotVersion),
new JsonSerializerOptions { WriteIndented = true });
// upload the updated version list
using var client = new AmazonS3Client(accessKey, secretAcccessKey, config);
await client.PutObjectAsync(new()
@@ -397,8 +397,9 @@ public class Help : NadekoModule<HelpService>
}
else
{
Log.Warning("Version {Version} already exists in the version file. " +
"Did you forget to increment it?", StatsService.BotVersion);
Log.Warning(
"Version {Version} already exists in the version file. " + "Did you forget to increment it?",
StatsService.BotVersion);
}
}
@@ -407,13 +408,14 @@ public class Help : NadekoModule<HelpService>
await ctx.Channel.SendFileAsync(rDataStream, "cmds.json", GetText(strs.commandlist_regen));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Guide()
=> await ConfirmLocalizedAsync(strs.guide(
"https://nadeko.bot/commands",
=> await ConfirmLocalizedAsync(strs.guide("https://nadeko.bot/commands",
"http://nadekobot.readthedocs.io/en/latest/"));
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Donate()
=> await ReplyConfirmLocalizedAsync(strs.donate(PatreonUrl, PaypalUrl));
}
@@ -427,4 +429,4 @@ internal class CommandJsonObject
public string Module { get; set; }
public List<string> Options { get; set; }
public string[] Requirements { get; set; }
}
}