forked from soxtoby/SlackNet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CounterDemo.cs
98 lines (89 loc) · 3.69 KB
/
CounterDemo.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System.Text.RegularExpressions;
using SlackNet;
using SlackNet.Blocks;
using SlackNet.Events;
using SlackNet.Interaction;
using SlackNet.WebApi;
namespace SlackNetDemo;
/// <summary>
/// Displays an interactive message that updates itself.
/// </summary>
class CounterDemo : IEventHandler<MessageEvent>, IBlockActionHandler<ButtonAction>
{
private const string ActionPrefix = "add";
public const string Add1 = ActionPrefix + "1";
public const string Add5 = ActionPrefix + "5";
public const string Add10 = ActionPrefix + "10";
public const string Trigger = "counter demo";
private static readonly Regex CounterPattern = new("Counter: (\\d+)");
private readonly ISlackApiClient _slack;
public CounterDemo(ISlackApiClient slack) => _slack = slack;
public async Task Handle(MessageEvent slackEvent)
{
if (slackEvent.Text?.Contains(Trigger, StringComparison.OrdinalIgnoreCase) == true)
{
Console.WriteLine($"{(await _slack.Users.Info(slackEvent.User)).Name} asked for a counter demo in the {(await _slack.Conversations.Info(slackEvent.Channel)).Name} channel");
await _slack.Chat.PostMessage(new Message
{
Channel = slackEvent.Channel,
Blocks = Blocks
});
}
}
public async Task Handle(ButtonAction button, BlockActionRequest request)
{
Console.WriteLine($"{request.User.Name} clicked on the Add {button.Value} button in the {request.Channel.Name} channel");
var counter = SectionBeforeAddButtons(button, request);
if (counter != null)
{
var counterText = CounterPattern.Match(counter.Text.Text ?? string.Empty);
if (counterText.Success)
{
var count = int.Parse(counterText.Groups[1].Value);
var increment = int.Parse(((ButtonAction)request.Action).Value);
counter.Text = $"Counter: {count + increment}";
await _slack.Chat.Update(new MessageUpdate
{
Ts = request.Message.Ts,
Text = request.Message.Text,
Blocks = request.Message.Blocks,
ChannelId = request.Channel.Id
});
}
}
}
private static SectionBlock? SectionBeforeAddButtons(ButtonAction button, BlockActionRequest request)
{
return request.Message.Blocks
.TakeWhile(b => b.BlockId != button.BlockId)
.LastOrDefault() as SectionBlock;
}
static List<Block> Blocks => new()
{
new SectionBlock { Text = "Counter: 0" },
new ActionsBlock
{
Elements =
{
new SlackNet.Blocks.Button
{
ActionId = Add1,
Value = "1",
Text = new PlainText("Add 1")
},
new SlackNet.Blocks.Button
{
ActionId = Add5,
Value = "5",
Text = new PlainText("Add 5")
},
new SlackNet.Blocks.Button
{
ActionId = Add10,
Value = "10",
Text = new PlainText("Add 10")
}
}
}
};
}