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

@@ -10,6 +10,22 @@ namespace NadekoBot.Modules.Utility;
public partial class Utility : NadekoModule
{
public enum CreateInviteType
{
Any,
New
}
public enum MeOrBot { Me, Bot }
private static readonly JsonSerializerOptions _showEmbedSerializerOptions = new()
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = LowerCaseNamingPolicy.Default
};
private static SemaphoreSlim sem = new(1, 1);
private readonly DiscordSocketClient _client;
private readonly ICoordinator _coord;
private readonly IStatsService _stats;
@@ -17,8 +33,12 @@ public partial class Utility : NadekoModule
private readonly DownloadTracker _tracker;
private readonly IHttpClientFactory _httpFactory;
public Utility(DiscordSocketClient client, ICoordinator coord,
IStatsService stats, IBotCredentials creds, DownloadTracker tracker,
public Utility(
DiscordSocketClient client,
ICoordinator coord,
IStatsService stats,
IBotCredentials creds,
DownloadTracker tracker,
IHttpClientFactory httpFactory)
{
_client = client;
@@ -29,29 +49,32 @@ public partial class Utility : NadekoModule
_httpFactory = httpFactory;
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageMessages)]
[Priority(1)]
public async Task Say(ITextChannel channel, [Leftover] SmartText message)
{
var rep = new ReplacementBuilder()
.WithDefault(ctx.User, channel, (SocketGuild)ctx.Guild, (DiscordSocketClient)ctx.Client)
.Build();
.WithDefault(ctx.User, channel, (SocketGuild)ctx.Guild, (DiscordSocketClient)ctx.Client)
.Build();
message = rep.Replace(message);
await channel.SendAsync(message, !((IGuildUser)ctx.User).GuildPermissions.MentionEveryone);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[UserPerm(GuildPerm.ManageMessages)]
[Priority(0)]
public Task Say([Leftover] SmartText message)
=> Say((ITextChannel)ctx.Channel, message);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task WhosPlaying([Leftover] string game)
{
@@ -64,32 +87,36 @@ public partial class Utility : NadekoModule
Log.Warning("Can't cast guild to socket guild.");
return;
}
var rng = new NadekoRandom();
var arr = await Task.Run(() => socketGuild.Users
.Where(u => u.Activities.FirstOrDefault()?.Name?.ToUpperInvariant() == game)
.Select(u => u.Username)
.OrderBy(x => rng.Next())
.Take(60)
.ToArray());
.Where(u => u.Activities.FirstOrDefault()?.Name?.ToUpperInvariant()
== game)
.Select(u => u.Username)
.OrderBy(x => rng.Next())
.Take(60)
.ToArray());
var i = 0;
if (arr.Length == 0)
await ReplyErrorLocalizedAsync(strs.nobody_playing_game);
else
{
await SendConfirmAsync("```css\n" + string.Join("\n", arr.GroupBy(item => i++ / 2)
.Select(ig => string.Concat(ig.Select(el => $"• {el,-27}")))) + "\n```");
}
await SendConfirmAsync("```css\n"
+ string.Join("\n",
arr.GroupBy(item => i++ / 2)
.Select(ig => string.Concat(ig.Select(el => $"• {el,-27}"))))
+ "\n```");
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[Priority(0)]
public async Task InRole(int page, [Leftover] IRole role = null)
{
if (--page < 0)
return;
await ctx.Channel.TriggerTypingAsync();
await _tracker.EnsureUsersDownloadedAsync(ctx.Guild);
@@ -98,75 +125,80 @@ public partial class Utility : NadekoModule
CacheMode.CacheOnly
#endif
);
var roleUsers = users
.Where(u => role is null ? u.RoleIds.Count == 1 : u.RoleIds.Contains(role.Id))
.Select(u => $"`{u.Id, 18}` {u}")
.ToArray();
await ctx.SendPaginatedConfirmAsync(page, cur =>
{
var pageUsers = roleUsers.Skip(cur * 20)
.Take(20)
.ToList();
var roleUsers = users.Where(u => role is null ? u.RoleIds.Count == 1 : u.RoleIds.Contains(role.Id))
.Select(u => $"`{u.Id,18}` {u}")
.ToArray();
if (pageUsers.Count == 0)
return _eb.Create().WithOkColor().WithDescription(GetText(strs.no_user_on_this_page));
await ctx.SendPaginatedConfirmAsync(page,
cur =>
{
var pageUsers = roleUsers.Skip(cur * 20).Take(20).ToList();
return _eb.Create().WithOkColor()
.WithTitle(GetText(strs.inrole_list(Format.Bold(role?.Name ?? "No Role"), roleUsers.Length)))
.WithDescription(string.Join("\n", pageUsers));
}, roleUsers.Length, 20);
if (pageUsers.Count == 0)
return _eb.Create().WithOkColor().WithDescription(GetText(strs.no_user_on_this_page));
return _eb.Create()
.WithOkColor()
.WithTitle(GetText(strs.inrole_list(Format.Bold(role?.Name ?? "No Role"), roleUsers.Length)))
.WithDescription(string.Join("\n", pageUsers));
},
roleUsers.Length,
20);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[Priority(1)]
public Task InRole([Leftover] IRole role = null)
=> InRole(1, role);
public enum MeOrBot { Me, Bot }
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task CheckPerms(MeOrBot who = MeOrBot.Me)
{
var builder = new StringBuilder();
var user = who == MeOrBot.Me
? (IGuildUser)ctx.User
: ((SocketGuild)ctx.Guild).CurrentUser;
var user = who == MeOrBot.Me ? (IGuildUser)ctx.User : ((SocketGuild)ctx.Guild).CurrentUser;
var perms = user.GetPermissions((ITextChannel)ctx.Channel);
foreach (var p in perms.GetType().GetProperties().Where(p => !p.GetGetMethod().GetParameters().Any()))
{
builder.AppendLine($"{p.Name} : {p.GetValue(perms, null)}");
}
await SendConfirmAsync(builder.ToString());
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task UserId([Leftover] IGuildUser target = null)
{
var usr = target ?? ctx.User;
await ReplyConfirmLocalizedAsync(strs.userid("🆔", Format.Bold(usr.ToString()),
await ReplyConfirmLocalizedAsync(strs.userid("🆔",
Format.Bold(usr.ToString()),
Format.Code(usr.Id.ToString())));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task RoleId([Leftover] IRole role)
=> await ReplyConfirmLocalizedAsync(strs.roleid("🆔", Format.Bold(role.ToString()),
=> await ReplyConfirmLocalizedAsync(strs.roleid("🆔",
Format.Bold(role.ToString()),
Format.Code(role.Id.ToString())));
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task ChannelId()
=> await ReplyConfirmLocalizedAsync(strs.channelid("🆔", Format.Code(ctx.Channel.Id.ToString())));
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ServerId()
=> await ReplyConfirmLocalizedAsync(strs.serverid("🆔", Format.Code(ctx.Guild.Id.ToString())));
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task Roles(IGuildUser target, int page = 1)
{
@@ -179,41 +211,43 @@ public partial class Utility : NadekoModule
if (target != null)
{
var roles = target.GetRoles().Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * rolesPerPage).Take(rolesPerPage).ToArray();
var roles = target.GetRoles()
.Except(new[] { guild.EveryoneRole })
.OrderBy(r => -r.Position)
.Skip((page - 1) * rolesPerPage)
.Take(rolesPerPage)
.ToArray();
if (!roles.Any())
{
await ReplyErrorLocalizedAsync(strs.no_roles_on_page);
}
else
{
await SendConfirmAsync(GetText(strs.roles_page(page, Format.Bold(target.ToString()))),
"\n• " + string.Join("\n• ", (IEnumerable<IRole>)roles).SanitizeMentions(true));
}
}
else
{
var roles = guild.Roles.Except(new[] { guild.EveryoneRole }).OrderBy(r => -r.Position).Skip((page - 1) * rolesPerPage).Take(rolesPerPage).ToArray();
var roles = guild.Roles.Except(new[] { guild.EveryoneRole })
.OrderBy(r => -r.Position)
.Skip((page - 1) * rolesPerPage)
.Take(rolesPerPage)
.ToArray();
if (!roles.Any())
{
await ReplyErrorLocalizedAsync(strs.no_roles_on_page);
}
else
{
await SendConfirmAsync(GetText(strs.roles_all_page(page)),
"\n• " + string.Join("\n• ", (IEnumerable<IRole>)roles).SanitizeMentions(true));
}
}
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public Task Roles(int page = 1) =>
Roles(null, page);
public Task Roles(int page = 1)
=> Roles(null, page);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ChannelTopic([Leftover]ITextChannel channel = null)
public async Task ChannelTopic([Leftover] ITextChannel channel = null)
{
if (channel is null)
channel = (ITextChannel)ctx.Channel;
@@ -225,37 +259,44 @@ public partial class Utility : NadekoModule
await SendConfirmAsync(GetText(strs.channel_topic), topic);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
public async Task Stats()
{
var ownerIds = string.Join("\n", _creds.OwnerIds);
if (string.IsNullOrWhiteSpace(ownerIds))
ownerIds = "-";
await ctx.Channel.EmbedAsync(
_eb.Create().WithOkColor()
.WithAuthor($"NadekoBot v{StatsService.BotVersion}",
"https://nadeko-pictures.nyc3.digitaloceanspaces.com/other/avatar.png",
"https://nadekobot.readthedocs.io/en/latest/")
.AddField(GetText(strs.author), _stats.Author, true)
.AddField(GetText(strs.botid), _client.CurrentUser.Id.ToString(), true)
.AddField(GetText(strs.shard), $"#{_client.ShardId} / {_creds.TotalShards}", true)
.AddField(GetText(strs.commands_ran), _stats.CommandsRan.ToString(), true)
.AddField(GetText(strs.messages), $"{_stats.MessageCounter} ({_stats.MessagesPerSecond:F2}/sec)",
true)
.AddField(GetText(strs.memory), FormattableString.Invariant($"{_stats.GetPrivateMemory():F2} MB"), true)
.AddField(GetText(strs.owner_ids), ownerIds, true)
.AddField(GetText(strs.uptime), _stats.GetUptimeString("\n"), true)
.AddField(GetText(strs.presence),
GetText(strs.presence_txt(
_coord.GetGuildCount(),
_stats.TextChannels,
_stats.VoiceChannels)),
true));
await ctx.Channel.EmbedAsync(_eb.Create()
.WithOkColor()
.WithAuthor($"NadekoBot v{StatsService.BotVersion}",
"https://nadeko-pictures.nyc3.digitaloceanspaces.com/other/avatar.png",
"https://nadekobot.readthedocs.io/en/latest/")
.AddField(GetText(strs.author), _stats.Author, true)
.AddField(GetText(strs.botid), _client.CurrentUser.Id.ToString(), true)
.AddField(GetText(strs.shard),
$"#{_client.ShardId} / {_creds.TotalShards}",
true)
.AddField(GetText(strs.commands_ran), _stats.CommandsRan.ToString(), true)
.AddField(GetText(strs.messages),
$"{_stats.MessageCounter} ({_stats.MessagesPerSecond:F2}/sec)",
true)
.AddField(GetText(strs.memory),
FormattableString.Invariant($"{_stats.GetPrivateMemory():F2} MB"),
true)
.AddField(GetText(strs.owner_ids), ownerIds, true)
.AddField(GetText(strs.uptime), _stats.GetUptimeString("\n"), true)
.AddField(GetText(strs.presence),
GetText(strs.presence_txt(_coord.GetGuildCount(),
_stats.TextChannels,
_stats.VoiceChannels)),
true));
}
[NadekoCommand, Aliases]
public async Task Showemojis([Leftover] string _) // need to have the parameter so that the message.tags gets populated
[NadekoCommand]
[Aliases]
public async Task
Showemojis([Leftover] string _) // need to have the parameter so that the message.tags gets populated
{
var tags = ctx.Message.Tags.Where(t => t.Type == TagType.Emoji).Select(t => (Emote)t.Value);
@@ -267,23 +308,26 @@ public partial class Utility : NadekoModule
await ctx.Channel.SendMessageAsync(result.TrimTo(2000));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[BotPerm(GuildPerm.ManageEmojisAndStickers)]
[UserPerm(GuildPerm.ManageEmojisAndStickers)]
[Priority(2)]
public Task EmojiAdd(string name, Emote emote)
=> EmojiAdd(name, emote.Url);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[BotPerm(GuildPerm.ManageEmojisAndStickers)]
[UserPerm(GuildPerm.ManageEmojisAndStickers)]
[Priority(1)]
public Task EmojiAdd(Emote emote)
=> EmojiAdd(emote.Name, emote.Url);
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[BotPerm(GuildPerm.ManageEmojisAndStickers)]
[UserPerm(GuildPerm.ManageEmojisAndStickers)]
@@ -296,7 +340,7 @@ public partial class Utility : NadekoModule
if (url is null)
return;
using var http = _httpFactory.CreateClient();
var res = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
if (!res.IsImage() || res.GetImageSize() is null or > 262_144)
@@ -318,10 +362,12 @@ public partial class Utility : NadekoModule
await ReplyErrorLocalizedAsync(strs.emoji_add_error);
return;
}
await ConfirmLocalizedAsync(strs.emoji_added(em.ToString()));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[OwnerOnly]
public async Task ListServers(int page = 1)
{
@@ -338,29 +384,21 @@ public partial class Utility : NadekoModule
return;
}
var embed = _eb.Create()
.WithOkColor();
var embed = _eb.Create().WithOkColor();
foreach (var guild in guilds)
embed.AddField(guild.Name,
GetText(strs.listservers(guild.Id, guild.MemberCount, guild.OwnerId)),
false);
embed.AddField(guild.Name, GetText(strs.listservers(guild.Id, guild.MemberCount, guild.OwnerId)));
await ctx.Channel.EmbedAsync(embed);
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public Task ShowEmbed(ulong messageId)
=> ShowEmbed((ITextChannel)ctx.Channel, messageId);
private static readonly JsonSerializerOptions _showEmbedSerializerOptions = new()
{
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = LowerCaseNamingPolicy.Default
};
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
public async Task ShowEmbed(ITextChannel ch, ulong messageId)
{
@@ -390,7 +428,8 @@ public partial class Utility : NadekoModule
await SendConfirmAsync(Format.Sanitize(json).Replace("](", "]\\("));
}
[NadekoCommand, Aliases]
[NadekoCommand]
[Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task SaveChat(int cnt)
@@ -400,36 +439,38 @@ public partial class Utility : NadekoModule
var title = $"Chatlog-{ctx.Guild.Name}/#{ctx.Channel.Name}-{DateTime.Now}.txt";
var grouping = msgs.GroupBy(x => $"{x.CreatedAt.Date:dd.MM.yyyy}")
.Select(g => new
{
date = g.Key,
messages = g.OrderBy(x => x.CreatedAt).Select(s =>
{
var msg = $"【{s.Timestamp:HH:mm:ss}】{s.Author}:";
if (string.IsNullOrWhiteSpace(s.ToString()))
{
if (s.Attachments.Any())
{
msg += "FILES_UPLOADED: " + string.Join("\n", s.Attachments.Select(x => x.Url));
}
else if (s.Embeds.Any())
{
msg += "EMBEDS: " + string.Join("\n--------\n", s.Embeds.Select(x => $"Description: {x.Description}"));
}
}
else
{
msg += s.ToString();
}
return msg;
})
});
await using var stream = await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream();
await ctx.User.SendFileAsync(stream, title, title, false);
}
private static SemaphoreSlim sem = new(1, 1);
.Select(g => new
{
date = g.Key,
messages = g.OrderBy(x => x.CreatedAt)
.Select(s =>
{
var msg = $"【{s.Timestamp:HH:mm:ss}】{s.Author}:";
if (string.IsNullOrWhiteSpace(s.ToString()))
{
if (s.Attachments.Any())
msg += "FILES_UPLOADED: "
+ string.Join("\n", s.Attachments.Select(x => x.Url));
else if (s.Embeds.Any())
msg += "EMBEDS: "
+ string.Join("\n--------\n",
s.Embeds.Select(x
=> $"Description: {x.Description}"));
}
else
{
msg += s.ToString();
}
[NadekoCommand, Aliases]
return msg;
})
});
await using var stream = await JsonConvert.SerializeObject(grouping, Formatting.Indented).ToStream();
await ctx.User.SendFileAsync(stream, title, title);
}
[NadekoCommand]
[Aliases]
#if GLOBAL_NADEKO
[Ratelimit(30)]
#endif
@@ -451,14 +492,7 @@ public partial class Utility : NadekoModule
}
}
public enum CreateInviteType
{
Any,
New
}
// [NadekoCommand, Usage, Description, Aliases]
// [RequireContext(ContextType.Guild)]
// public async Task CreateMyInvite(CreateInviteType type = CreateInviteType.Any)
@@ -497,4 +531,4 @@ public partial class Utility : NadekoModule
// return embed;
// }, inviteUsers.Count, 9);
// }
}
}