-
Notifications
You must be signed in to change notification settings - Fork 177
/
Copy pathSlackHelper.cs
461 lines (400 loc) · 16.7 KB
/
SlackHelper.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Bot.Builder.Community.Adapters.Slack.Model;
using Bot.Builder.Community.Adapters.Slack.Model.Events;
using Microsoft.AspNetCore.Http;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SlackAPI;
#if SIGNASSEMBLY
[assembly: InternalsVisibleTo("Bot.Builder.Community.Adapters.Slack.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Bot.Builder.Community.Adapters.Slack.Tests")]
#endif
namespace Bot.Builder.Community.Adapters.Slack
{
internal static class SlackHelper
{
private const string SlackServiceUrl = "https://slack.botframework.com/";
/// <summary>
/// Formats a BotBuilder activity into an outgoing Slack message.
/// </summary>
/// <param name="activity">A BotBuilder Activity object.</param>
/// <returns>A Slack message object with {text, attachments, channel, thread ts} as well as any fields found in activity.channelData.</returns>
public static NewSlackMessage ActivityToSlack(Activity activity)
{
if (activity == null)
{
throw new ArgumentNullException(nameof(activity));
}
var message = new NewSlackMessage();
if (activity.Timestamp != null)
{
message.Ts = activity.Timestamp.Value.DateTime.ToString(CultureInfo.InvariantCulture);
}
message.Text = activity.Text;
if (activity.Attachments != null)
{
var attachments = new List<SlackAttachment>();
foreach (var att in activity.Attachments)
{
if (att.Name == "blocks")
{
message.Blocks = att.Content;
}
else if (att.ContentType == HeroCard.ContentType)
{
message.Blocks = HeroCardToBlockKit((HeroCard)att.Content);
}
else
{
var newAttachment = new SlackAttachment()
{
AuthorName = att.Name,
ThumbUrl = new Uri(att.ThumbnailUrl),
};
attachments.Add(newAttachment);
}
}
if (attachments.Count > 0)
{
message.Attachments = attachments;
}
}
message.Channel = activity.Conversation.Id;
if (!string.IsNullOrWhiteSpace(activity.Conversation.Properties["thread_ts"]?.ToString()))
{
message.ThreadTs = activity.Conversation.Properties["thread_ts"].ToString();
}
// if channelData is specified, overwrite any fields in message object
if (activity.ChannelData != null)
{
message = activity.GetChannelData<NewSlackMessage>();
}
// should this message be sent as an ephemeral message
if (!string.IsNullOrWhiteSpace(message.Ephemeral))
{
message.User = activity.Recipient.Id;
}
return message;
}
/// <summary>
/// Writes the HttpResponse.
/// </summary>
/// <param name="response">The httpResponse.</param>
/// <param name="code">The status code to be written.</param>
/// <param name="text">The text to be written.</param>
/// <param name="encoding">The encoding for the text.</param>
/// <param name="cancellationToken">A cancellation token for the task.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public static async Task WriteAsync(HttpResponse response, HttpStatusCode code, string text, Encoding encoding, CancellationToken cancellationToken = default)
{
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
response.ContentType = "text/plain";
response.StatusCode = (int)code;
var data = encoding.GetBytes(text);
await response.Body.WriteAsync(data, 0, data.Length, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates an activity based on the slack event payload.
/// </summary>
/// <param name="slackPayload">The payload of the slack event.</param>
/// <returns>An activity containing the event data.</returns>
public static Activity PayloadToActivity(InteractionPayload slackPayload)
{
if (slackPayload == null)
{
throw new ArgumentNullException(nameof(slackPayload));
}
var activity = new Activity()
{
Timestamp = default,
ChannelId = "slack",
Conversation = new ConversationAccount()
{
Id = slackPayload.Channel.id,
},
From = new ChannelAccount()
{
Id = slackPayload.User.id ?? slackPayload.Message?.BotId,
},
Recipient = new ChannelAccount()
{
Id = null,
},
ChannelData = slackPayload,
Text = null,
Type = ActivityTypes.Event,
Value = slackPayload
};
if (slackPayload.ThreadTs != null)
{
activity.Conversation.Properties["thread_ts"] = slackPayload.ThreadTs;
}
if (slackPayload.Actions != null && slackPayload.Actions.Any())
{
var action = slackPayload.Actions[0];
switch (action.Type)
{
case "button":
activity.Text = action.Value;
break;
case "select":
activity.Text = slackPayload.Actions[0].SelectedOptions[0]?.Value ?? slackPayload.Actions[0].SelectedOption?.Value;
break;
case "static_select":
activity.Text = slackPayload.Actions[0].SelectedOption.Value;
break;
default:
break;
}
if (!string.IsNullOrEmpty(activity.Text))
{
activity.Type = ActivityTypes.Message;
}
}
return activity;
}
/// <summary>
/// Creates an activity based on the slack event data.
/// </summary>
/// <param name="eventRequest">The data of the slack event.</param>
/// <param name="client">The Slack client.</param>
/// <returns>An activity containing the event data.</returns>
public static Activity EventToActivity(EventRequest eventRequest, SlackClientWrapper client)
{
if (eventRequest == null)
{
throw new ArgumentNullException(nameof(eventRequest));
}
var innerEvent = eventRequest.Event;
var activity = new Activity
{
Id = innerEvent.EventTs,
Timestamp = default,
ChannelId = "slack",
Conversation =
new ConversationAccount()
{
Id = innerEvent.Channel ?? innerEvent.ChannelId ?? eventRequest.TeamId
},
From = new ChannelAccount()
{
Id = innerEvent.User ?? innerEvent.BotId ?? eventRequest.TeamId
},
ChannelData = eventRequest,
Type = ActivityTypes.Event,
ServiceUrl = SlackServiceUrl
};
activity.Recipient = new ChannelAccount()
{
Id = client.GetBotUserIdentity(activity)
};
if (!string.IsNullOrEmpty(innerEvent.ThreadTs))
{
activity.Conversation.Properties["thread_ts"] = innerEvent.ThreadTs;
}
if (innerEvent.Type == "message" && innerEvent.BotId == null)
{
var message = JObject.FromObject(innerEvent).ToObject<MessageEvent>();
if (message.SubType == null || message.SubType == "file_share")
{
activity.Type = ActivityTypes.Message;
activity.Text = message.Text;
if (message.AdditionalProperties.ContainsKey("files"))
{
var attachments = new List<Microsoft.Bot.Schema.Attachment>();
foreach (var attachment in message.AdditionalProperties["files"])
{
var attachmentProperties = attachment.Value<JObject>().Properties();
var contentType = string.Empty;
var contentUrl = string.Empty;
var name = string.Empty;
foreach (var property in attachmentProperties)
{
if (property.Name == "mimetype")
{
contentType = property.Value.ToString();
}
if (property.Name == "url_private_download")
{
contentUrl = property.Value.ToString();
}
if (property.Name == "name")
{
name = property.Value.ToString();
}
}
attachments.Add(new Microsoft.Bot.Schema.Attachment
{
ContentType = contentType,
ContentUrl = contentUrl,
Name = name
});
}
activity.Attachments = attachments;
}
}
activity.Conversation.Properties["channel_type"] = message.ChannelType;
activity.Value = innerEvent;
}
else
{
activity.Name = innerEvent.Type;
activity.Value = innerEvent;
}
return activity;
}
/// <summary>
/// Creates an activity based on a slack event related to a slash command.
/// </summary>
/// <param name="commandRequest">The data of the slack command request.</param>
/// <param name="client">The Slack client.</param>
/// <returns>An activity containing the event data.</returns>
public static Activity CommandToActivity(CommandPayload commandRequest, SlackClientWrapper client)
{
if (commandRequest == null)
{
throw new ArgumentNullException(nameof(commandRequest));
}
var activity = new Activity()
{
Id = commandRequest.TriggerId,
Timestamp = default,
ChannelId = "slack",
Conversation = new ConversationAccount()
{
Id = commandRequest.ChannelId,
},
From = new ChannelAccount()
{
Id = commandRequest.UserId,
},
ChannelData = commandRequest,
Type = ActivityTypes.Event,
Name = "Command",
Value = commandRequest.Command
};
activity.Recipient = new ChannelAccount()
{
Id = client.GetBotUserIdentity(activity)
};
activity.Conversation.Properties["team"] = commandRequest.TeamId;
return activity;
}
/// <summary>
/// Converts a query string to a dictionary with key-value pairs.
/// </summary>
/// <param name="query">The query string to convert.</param>
/// <returns>A dictionary with the query values.</returns>
public static Dictionary<string, string> QueryStringToDictionary(string query)
{
var values = new Dictionary<string, string>();
if (string.IsNullOrWhiteSpace(query))
{
return values;
}
var pairs = query.Replace("+", "%20").Split('&');
foreach (var p in pairs)
{
var pair = p.Split('=');
var key = pair[0];
var value = Uri.UnescapeDataString(pair[1]);
values.Add(key, value);
}
return values;
}
private static JArray HeroCardToBlockKit(HeroCard heroCard)
{
var blockKitContent = new List<IBlock>();
if (!string.IsNullOrWhiteSpace(heroCard.Title))
{
blockKitContent.Add(new HeaderBlock
{
text = new Text
{
type = TextTypes.PlainText,
text = heroCard.Title
}
});
}
if (!string.IsNullOrWhiteSpace(heroCard.Subtitle))
{
blockKitContent.Add(new ContextBlock
{
elements = new IElement[]
{
new Text
{
type = TextTypes.Markdown,
text = heroCard.Subtitle
}
}
});
}
if (heroCard.Images?.Any() == true)
{
foreach (var image in heroCard.Images)
{
blockKitContent.Add(new ImageBlock
{
image_url = image.Url,
alt_text = !string.IsNullOrWhiteSpace(image.Alt) ? image.Alt : "Image" // Slack doesn't allow alt_text to be null/empty.
});
}
}
if (!string.IsNullOrWhiteSpace(heroCard.Text))
{
blockKitContent.Add(new SectionBlock
{
text = new Text
{
type = TextTypes.Markdown,
text = heroCard.Text
}
});
}
if (heroCard.Buttons?.Any() == true)
{
var actionsBlock = new ActionsBlock
{
elements = heroCard.Buttons.Select(button => new ButtonElement
{
text = new Text
{
type = TextTypes.PlainText,
text = button.Title ?? button.Text ?? button.DisplayText,
emoji = true,
},
// value/url get a little tricky if the button is an OpenUrl since CardAction.Value is meant for the URL.
// We don't want to set value if it's an OpenUrl, because then the URL gets displayed in chat and sent to the bot.
value = button.Type == ActionTypes.OpenUrl ? null : button.Value.ToString() ?? button.DisplayText ?? button.Text,
url = button.Type == ActionTypes.OpenUrl ? button.Value.ToString() : null
}).ToArray()
};
blockKitContent.Add(new DividerBlock());
blockKitContent.Add(actionsBlock);
}
return JArray.FromObject(blockKitContent, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore });
}
}
}