Finished new response system

This commit is contained in:
Kwoth
2024-05-02 06:47:01 +00:00
parent a25adefc65
commit fc4858830c
102 changed files with 1811 additions and 1818 deletions

View File

@@ -121,17 +121,19 @@ public partial class Utility
var arr = maps.ToArray();
await ctx.SendPaginatedConfirmAsync(page,
curPage =>
{
return new EmbedBuilder()
.WithOkColor()
.WithTitle(GetText(strs.alias_list))
.WithDescription(string.Join("\n",
arr.Skip(curPage * 10).Take(10).Select(x => $"`{x.Key}` => `{x.Value}`")));
},
arr.Length,
10);
await Response()
.Paginated()
.Items(arr)
.PageSize(10)
.CurrentPage(page)
.Page((items, _) =>
{
return _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.alias_list))
.WithDescription(string.Join("\n", items.Select(x => $"`{x.Key}` => `{x.Value}`")));
})
.SendAsync();
}
}
}

View File

@@ -20,7 +20,7 @@ public partial class Utility
if (setting is null)
{
var configNames = _settingServices.Select(x => x.Name);
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithErrorColor()
.WithDescription(GetText(strs.config_not_found(Format.Code(name))))
.AddField(GetText(strs.config_list), string.Join("\n", configNames));
@@ -43,7 +43,7 @@ public partial class Utility
name = name?.ToLowerInvariant();
if (string.IsNullOrWhiteSpace(name))
{
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.config_list))
.WithDescription(string.Join("\n", configNames));
@@ -58,7 +58,7 @@ public partial class Utility
// if config name is not found, print error and the list of configs
if (setting is null)
{
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithErrorColor()
.WithDescription(GetText(strs.config_not_found(Format.Code(name))))
.AddField(GetText(strs.config_list), string.Join("\n", configNames));
@@ -75,7 +75,7 @@ public partial class Utility
if (string.IsNullOrWhiteSpace(prop))
{
var propStrings = GetPropsAndValuesString(setting, propNames);
var embed = new EmbedBuilder().WithOkColor().WithTitle($"⚙️ {setting.Name}").WithDescription(propStrings);
var embed = _sender.CreateEmbed().WithOkColor().WithTitle($"⚙️ {setting.Name}").WithDescription(propStrings);
await Response().Embed(embed).SendAsync();
@@ -88,7 +88,7 @@ public partial class Utility
if (!exists)
{
var propStrings = GetPropsAndValuesString(setting, propNames);
var propErrorEmbed = new EmbedBuilder()
var propErrorEmbed = _sender.CreateEmbed()
.WithErrorColor()
.WithDescription(GetText(
strs.config_prop_not_found(Format.Code(prop), Format.Code(name))))
@@ -110,7 +110,7 @@ public partial class Utility
if (prop != "currency.sign")
value = Format.Code(Format.Sanitize(value.TrimTo(1000)), "json");
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithOkColor()
.AddField("Config", Format.Code(setting.Name), true)
.AddField("Prop", Format.Code(prop), true)

View File

@@ -17,7 +17,7 @@ public partial class Utility
return;
}
var eb = new EmbedBuilder()
var eb = _sender.CreateEmbed()
.WithPendingColor()
.WithTitle(GetText(strs.giveaway_starting))
.WithDescription(message);
@@ -103,7 +103,7 @@ public partial class Utility
return;
}
var eb = new EmbedBuilder()
var eb = _sender.CreateEmbed()
.WithTitle(GetText(strs.giveaway_list))
.WithOkColor();

View File

@@ -317,7 +317,7 @@ public sealed class GiveawayService : INService, IReadyExecutor
{Format.Code(winner.UserId.ToString())}
""";
var eb = new EmbedBuilder()
var eb = _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.giveaway_ended))
.WithDescription(ga.Message)

View File

@@ -54,7 +54,7 @@ public partial class Utility
if (string.IsNullOrWhiteSpace(features))
features = "-";
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithAuthor(GetText(strs.server_info))
.WithTitle(guild.Name)
.AddField(GetText(strs.id), guild.Id.ToString(), true)
@@ -87,7 +87,7 @@ public partial class Utility
return;
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(ch.Id >> 22);
var usercount = (await ch.GetUsersAsync().FlattenAsync()).Count();
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithTitle(ch.Name)
.WithDescription(ch.Topic?.SanitizeMentions(true))
.AddField(GetText(strs.id), ch.Id.ToString(), true)
@@ -107,7 +107,7 @@ public partial class Utility
var createdAt = new DateTime(2015, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(role.Id >> 22);
var usercount = role.Members.LongCount();
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithTitle(role.Name.TrimTo(128))
.WithDescription(role.Permissions.ToList().Join(" | "))
.AddField(GetText(strs.id), role.Id.ToString(), true)
@@ -133,7 +133,7 @@ public partial class Utility
if (user is null)
return;
var embed = new EmbedBuilder().AddField(GetText(strs.name), $"**{user.Username}**#{user.Discriminator}", true);
var embed = _sender.CreateEmbed().AddField(GetText(strs.name), $"**{user.Username}**#{user.Discriminator}", true);
if (!string.IsNullOrWhiteSpace(user.Nickname))
embed.AddField(GetText(strs.nickname), user.Nickname, true);
@@ -204,7 +204,7 @@ public partial class Utility
kvp.Value)));
}
await Response().Embed(new EmbedBuilder()
await Response().Embed(_sender.CreateEmbed()
.WithTitle(GetText(strs.activity_page(page + 1)))
.WithOkColor()
.WithFooter(GetText(

View File

@@ -47,9 +47,9 @@ public partial class Utility
var i = 1;
if (!invs.Any())
return new EmbedBuilder().WithErrorColor().WithDescription(GetText(strs.no_invites));
return _sender.CreateEmbed().WithErrorColor().WithDescription(GetText(strs.no_invites));
var embed = new EmbedBuilder().WithOkColor();
var embed = _sender.CreateEmbed().WithOkColor();
foreach (var inv in invs)
{
var expiryString = inv.MaxAge is null or 0 || inv.CreatedAt is null

View File

@@ -106,7 +106,10 @@ public partial class Utility
var text = SmartText.CreateFrom(quote.Text);
text = await repSvc.ReplaceAsync(text, repCtx);
await ctx.Channel.SendAsync($"`#{quote.Id}` 📣 " + text, true, replyTo: ctx.Message);
await Response()
.Text($"`#{quote.Id}` 📣 " + text)
.Sanitize()
.SendAsync();
}
[Cmd]
@@ -132,13 +135,13 @@ public partial class Utility
private async Task ShowQuoteData(Quote data)
{
var eb = new EmbedBuilder()
.WithOkColor()
.WithTitle($"{GetText(strs.quote_id($"#{data.Id}"))} | {GetText(strs.response)}:")
.WithDescription(Format.Sanitize(data.Text).Replace("](", "]\\(").TrimTo(4096))
.AddField(GetText(strs.trigger), data.Keyword)
.WithFooter(
GetText(strs.created_by($"{data.AuthorName} ({data.AuthorId})")));
var eb = _sender.CreateEmbed()
.WithOkColor()
.WithTitle($"{GetText(strs.quote_id($"#{data.Id}"))} | {GetText(strs.response)}:")
.WithDescription(Format.Sanitize(data.Text).Replace("](", "]\\(").TrimTo(4096))
.AddField(GetText(strs.trigger), data.Keyword)
.WithFooter(
GetText(strs.created_by($"{data.AuthorName} ({data.AuthorId})")));
if (!(data.Text.Length > 4096))
{
@@ -146,10 +149,12 @@ public partial class Utility
return;
}
// todo all send files should go through response system too
await ctx.Channel.SendFileAsync(
attachment: new FileAttachment(await data.Text.ToStream(), "quote.txt"),
embed: eb.Build());
await using var textStream = await data.Text.ToStream();
await Response()
.Embed(eb)
.File(textStream, "quote.txt")
.SendAsync();
}
private async Task QuoteSearchinternalAsync(string? keyword, string textOrAuthor)
@@ -217,7 +222,10 @@ public partial class Utility
var text = SmartText.CreateFrom(quote.Text);
text = await repSvc.ReplaceAsync(text, repCtx);
await ctx.Channel.SendAsync(infoText + text, true, replyTo: ctx.Message);
await Response()
.Text(infoText + text)
.Sanitize()
.SendAsync();
}
[Cmd]

View File

@@ -96,7 +96,7 @@ public partial class Utility
if (--page < 0)
return;
var embed = new EmbedBuilder()
var embed = _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(isServer ? strs.reminder_server_list : strs.reminder_list));

View File

@@ -208,7 +208,7 @@ public class RemindService : INService, IReadyExecutor, IRemindService
else
{
await _sender.Response(ch)
.Embed(new EmbedBuilder()
.Embed(_sender.CreateEmbed()
.WithOkColor()
.WithTitle("Reminder")
.AddField("Created At",

View File

@@ -64,7 +64,7 @@ public partial class Utility
}
var description = GetRepeaterInfoString(removed);
await Response().Embed(new EmbedBuilder()
await Response().Embed(_sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.repeater_removed(index + 1)))
.WithDescription(description)).SendAsync();
@@ -187,7 +187,7 @@ public partial class Utility
}
var description = GetRepeaterInfoString(runner);
await Response().Embed(new EmbedBuilder()
await Response().Embed(_sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.repeater_created))
.WithDescription(description)).SendAsync();
@@ -205,7 +205,7 @@ public partial class Utility
return;
}
var embed = new EmbedBuilder().WithTitle(GetText(strs.list_of_repeaters)).WithOkColor();
var embed = _sender.CreateEmbed().WithTitle(GetText(strs.list_of_repeaters)).WithOkColor();
var i = 0;
foreach (var runner in repeaters.OrderBy(r => r.Repeater.Id))

View File

@@ -19,24 +19,27 @@ public sealed class RepeaterService : IReadyExecutor, INService
private readonly ConcurrentHashSet<int> _skipNext = new();
private readonly object _queueLocker = new();
private readonly IMessageSenderService _sender;
public RepeaterService(
DiscordSocketClient client,
DbService db,
IReplacementService repSvc,
IBotCredentials creds)
IBotCredentials creds,
IMessageSenderService sender)
{
_db = db;
_repSvc = repSvc;
_creds = creds;
_client = client;
_sender = sender;
using var uow = _db.GetDbContext();
var shardRepeaters = uow.Set<Repeater>()
.Where(x => (int)(x.GuildId / Math.Pow(2, 22)) % _creds.TotalShards
== _client.ShardId)
.AsNoTracking()
.ToList();
.Where(x => (int)(x.GuildId / Math.Pow(2, 22)) % _creds.TotalShards
== _client.ShardId)
.AsNoTracking()
.ToList();
_noRedundant = new(shardRepeaters.Where(x => x.NoRedundant).Select(x => x.Id));
@@ -125,10 +128,11 @@ public sealed class RepeaterService : IReadyExecutor, INService
{
await using var uow = _db.GetDbContext();
var toTrigger = await uow.Set<Repeater>().AsNoTracking()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
var toTrigger = await uow.Set<Repeater>()
.AsNoTracking()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
if (toTrigger is null)
return false;
@@ -265,7 +269,7 @@ public sealed class RepeaterService : IReadyExecutor, INService
var text = SmartText.CreateFrom(repeater.Message);
text = await _repSvc.ReplaceAsync(text, repCtx);
var newMsg = await channel.SendAsync(text);
var newMsg = await _sender.Response(channel).Text(text).SendAsync();
_ = newMsg.AddReactionAsync(new Emoji("🔄"));
if (_noRedundant.Contains(repeater.Id))
@@ -308,12 +312,13 @@ public sealed class RepeaterService : IReadyExecutor, INService
private async Task SetRepeaterLastMessageInternal(int repeaterId, ulong lastMsgId)
{
await using var uow = _db.GetDbContext();
await uow.Set<Repeater>().AsQueryable()
.Where(x => x.Id == repeaterId)
.UpdateAsync(rep => new()
{
LastMessageId = lastMsgId
});
await uow.Set<Repeater>()
.AsQueryable()
.Where(x => x.Id == repeaterId)
.UpdateAsync(rep => new()
{
LastMessageId = lastMsgId
});
}
public async Task<RunningRepeater?> AddRepeaterAsync(
@@ -358,10 +363,11 @@ public sealed class RepeaterService : IReadyExecutor, INService
throw new ArgumentOutOfRangeException(nameof(index));
await using var uow = _db.GetDbContext();
var toRemove = await uow.Set<Repeater>().AsNoTracking()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
var toRemove = await uow.Set<Repeater>()
.AsNoTracking()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
if (toRemove is null)
return null;
@@ -389,10 +395,11 @@ public sealed class RepeaterService : IReadyExecutor, INService
public async Task<bool?> ToggleRedundantAsync(ulong guildId, int index)
{
await using var uow = _db.GetDbContext();
var toToggle = await uow.Set<Repeater>().AsQueryable()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
var toToggle = await uow.Set<Repeater>()
.AsQueryable()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
if (toToggle is null)
return null;
@@ -411,9 +418,9 @@ public sealed class RepeaterService : IReadyExecutor, INService
{
await using var ctx = _db.GetDbContext();
var toSkip = await ctx.Set<Repeater>()
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
.Where(x => x.GuildId == guildId)
.Skip(index)
.FirstOrDefaultAsyncEF();
if (toSkip is null)
return null;

View File

@@ -81,27 +81,27 @@ public partial class Utility
}
private async Task ShowTodosAsync(TodoModel[] todos)
{
await ctx.SendPaginatedConfirmAsync(0,
(curPage) =>
{
var eb = new EmbedBuilder()
.WithOkColor()
.WithTitle(GetText(strs.todo_list));
private Task ShowTodosAsync(TodoModel[] todos)
=> Response()
.Paginated()
.Items(todos)
.PageSize(9)
.Page((items, _) =>
{
var eb = _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.todo_list));
ShowTodoItem(todos, curPage, eb);
ShowTodoItem(items, eb);
return eb;
},
todos.Length,
9);
}
return eb;
})
.SendAsync();
private static void ShowTodoItem(IReadOnlyCollection<TodoModel> todos, int curPage, EmbedBuilder eb)
private static void ShowTodoItem(IReadOnlyCollection<TodoModel> todos, EmbedBuilder eb)
{
var sb = new StringBuilder();
foreach (var todo in todos.Skip(curPage * 9).Take(9))
foreach (var todo in todos)
{
sb.AppendLine($"{(todo.IsDone ? "" : "")} {Format.Code(new kwum(todo.Id).ToString())} {todo.Todo}");
@@ -147,23 +147,25 @@ public partial class Utility
return;
}
await ctx.SendPaginatedConfirmAsync(page,
(curPage) =>
{
var eb = new EmbedBuilder()
.WithTitle(GetText(strs.todo_archive_list))
.WithOkColor();
await Response()
.Paginated()
.Items(archivedTodoLists)
.PageSize(9)
.CurrentPage(page)
.Page((items, _) =>
{
var eb = _sender.CreateEmbed()
.WithTitle(GetText(strs.todo_archive_list))
.WithOkColor();
foreach (var archivedList in archivedTodoLists.Skip(curPage * 9).Take(9))
{
eb.AddField($"id: {archivedList.Id.ToString()}", archivedList.Name, true);
}
foreach (var archivedList in items)
{
eb.AddField($"id: {archivedList.Id.ToString()}", archivedList.Name, true);
}
return eb;
},
archivedTodoLists.Count,
9,
true);
return eb;
})
.SendAsync();
}
[Cmd]
@@ -176,19 +178,21 @@ public partial class Utility
return;
}
await ctx.SendPaginatedConfirmAsync(0,
(curPage) =>
{
var eb = new EmbedBuilder()
.WithOkColor()
.WithTitle(GetText(strs.todo_list));
await Response()
.Paginated()
.Items(list.Items)
.PageSize(9)
.Page((items, _) =>
{
var eb = _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.todo_list));
ShowTodoItem(list.Items, curPage, eb);
ShowTodoItem(items, eb);
return eb;
},
list.Items.Count,
9);
return eb;
})
.SendAsync();
}
[Cmd]

View File

@@ -13,7 +13,7 @@ public partial class Utility
{
var units = await _service.GetUnitsAsync();
var embed = new EmbedBuilder().WithTitle(GetText(strs.convertlist)).WithOkColor();
var embed = _sender.CreateEmbed().WithTitle(GetText(strs.convertlist)).WithOkColor();
foreach (var g in units.GroupBy(x => x.UnitType))

View File

@@ -83,9 +83,10 @@ public partial class Utility : NadekoModule
var repCtx = new ReplacementContext(Context);
message = await repSvc.ReplaceAsync(message, repCtx);
await channel.SendAsync(message,
!((IGuildUser)ctx.User).GuildPermissions.MentionEveryone,
replyTo: ctx.Message);
await Response()
.Text(message)
.UserBasedMentions()
.SendAsync();
}
[Cmd]
@@ -154,21 +155,22 @@ public partial class Utility : NadekoModule
.Select(u => $"`{u.Id,18}` {u}")
.ToArray();
await ctx.SendPaginatedConfirmAsync(page,
cur =>
{
var pageUsers = roleUsers.Skip(cur * 20).Take(20).ToList();
await Response()
.Paginated()
.Items(roleUsers)
.PageSize(20)
.CurrentPage(page)
.Page((pageUsers, _) =>
{
if (pageUsers.Count == 0)
return _sender.CreateEmbed().WithOkColor().WithDescription(GetText(strs.no_user_on_this_page));
if (pageUsers.Count == 0)
return new EmbedBuilder().WithOkColor().WithDescription(GetText(strs.no_user_on_this_page));
return new EmbedBuilder()
.WithOkColor()
.WithTitle(GetText(strs.inrole_list(Format.Bold(role?.Name ?? "No Role"), roleUsers.Length)))
.WithDescription(string.Join("\n", pageUsers));
},
roleUsers.Length,
20);
return _sender.CreateEmbed()
.WithOkColor()
.WithTitle(GetText(strs.inrole_list(Format.Bold(role?.Name ?? "No Role"), roleUsers.Length)))
.WithDescription(string.Join("\n", pageUsers));
})
.SendAsync();
}
[Cmd]
@@ -301,30 +303,32 @@ public partial class Utility : NadekoModule
if (string.IsNullOrWhiteSpace(ownerIds))
ownerIds = "-";
await Response().Embed(new EmbedBuilder()
.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.GetPrivateMemoryMegabytes():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)).SendAsync();
await Response()
.Embed(_sender.CreateEmbed()
.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.GetPrivateMemoryMegabytes():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))
.SendAsync();
}
[Cmd]
@@ -517,7 +521,7 @@ public partial class Utility : NadekoModule
return;
}
var embed = new EmbedBuilder().WithOkColor();
var embed = _sender.CreateEmbed().WithOkColor();
foreach (var guild in guilds)
embed.AddField(guild.Name, GetText(strs.listservers(guild.Id, guild.MemberCount, guild.OwnerId)));
@@ -660,6 +664,7 @@ public partial class Utility : NadekoModule
.WithReferences(this.GetType().Assembly)
.WithImports(
"System",
"System.Linq",
"NadekoBot",
"NadekoBot.Extensions",
"Microsoft.Extensions.DependencyInjection",
@@ -683,10 +688,10 @@ public partial class Utility : NadekoModule
var output = result.ReturnValue?.ToString();
if (!string.IsNullOrWhiteSpace(output))
{
var eb = new EmbedBuilder()
.WithOkColor()
.AddField("Code", scriptText)
.AddField("Output", output.TrimTo(512)!);
var eb = _sender.CreateEmbed()
.WithOkColor()
.AddField("Code", scriptText)
.AddField("Output", output.TrimTo(512)!);
_ = Response().Embed(eb).SendAsync();
}