-
Notifications
You must be signed in to change notification settings - Fork 2
/
PaginatableEmbedBuilder.cs
executable file
·79 lines (70 loc) · 2.08 KB
/
PaginatableEmbedBuilder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using Discord;
using Discord.WebSocket;
using Moe.Services;
namespace Moe;
public class PaginatableEmbedBuilder<T>
{
private readonly string backId = Guid.NewGuid().ToString();
private readonly string pagesId = Guid.NewGuid().ToString();
private readonly string forwardId = Guid.NewGuid().ToString();
private readonly int itemsPerPage;
private int currentPageNumber = 1;
private readonly int maxPageNumber;
private readonly IEnumerable<T> items;
private readonly Func<IEnumerable<T>, EmbedBuilder> pageBuilder;
public Embed Embed
{
get
{
var pageItems = items
.Skip((currentPageNumber - 1) * itemsPerPage)
.Take(itemsPerPage);
return pageBuilder(pageItems).Build();
}
}
public MessageComponent Components
{
get =>
new ComponentBuilder()
.WithButton("Back", backId, disabled: IsFirstPage())
.WithButton($"{currentPageNumber}/{maxPageNumber}", pagesId, disabled: true)
.WithButton("Forward", forwardId, disabled: IsLastPage())
.Build();
}
public PaginatableEmbedBuilder(int itemsPerPage, IEnumerable<T> items, Func<IEnumerable<T>, EmbedBuilder> pageBuilder)
{
this.itemsPerPage = itemsPerPage;
this.items = items;
this.pageBuilder = pageBuilder;
maxPageNumber = (int)Math.Ceiling(items.Count() / (double)itemsPerPage);
maxPageNumber = Math.Max(1, maxPageNumber);
DiscordService.Discord.ButtonExecuted += OnButtonExecuted;
}
~PaginatableEmbedBuilder()
{
DiscordService.Discord.ButtonExecuted -= OnButtonExecuted;
}
private async Task OnButtonExecuted(SocketMessageComponent component)
{
var id = component.Data.CustomId;
if (id == backId && !IsFirstPage())
{
currentPageNumber--;
}
else if (id == forwardId && !IsLastPage())
{
currentPageNumber++;
}
else
{
return;
}
await component.UpdateAsync(msg =>
{
msg.Embed = Embed;
msg.Components = Components;
});
}
private bool IsFirstPage() => currentPageNumber == 1;
private bool IsLastPage() => currentPageNumber == maxPageNumber;
}