Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion Samples/HelloWorld/test.http
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Mimicks a payload slack would send for app_mention events, like "@yourbot dostuff" in this case:
GET http://localhost:5000/
GET http://localhost:1337/
X-Slack-Request-Timestamp: 12331231
X-Slack-Signature: v0:abc123etcetc

Expand All @@ -12,3 +12,13 @@ X-Slack-Signature: v0:abc123etcetc
"channel": "C92QZTVEF"
}
}

###
# Verification request
GET http://localhost:1337

{
"token": "Jhj5dZrVaK7ZwHHjRyZWjbDl",
"challenge": "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P",
"type": "url_verification"
}
5 changes: 3 additions & 2 deletions source/src/Slackbot.Net.Endpoints/Middlewares/Challenge.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;


namespace Slackbot.Net.Endpoints.Middlewares
{
Expand All @@ -20,7 +21,7 @@ public async Task Invoke(HttpContext context)
_logger.LogInformation($"Handling challenge request. Challenge: {challenge}");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonConvert.SerializeObject(new {challenge}));
await context.Response.WriteAsync(JsonSerializer.Serialize(new {challenge}));
}

public static bool ShouldRun(HttpContext ctx)
Expand Down
52 changes: 28 additions & 24 deletions source/src/Slackbot.Net.Endpoints/Middlewares/HttpItemsManager.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Slackbot.Net.Endpoints.Models.Events;
using Slackbot.Net.Endpoints.Models.Interactive;
using Slackbot.Net.Endpoints.Models.Interactive.BlockActions;
Expand Down Expand Up @@ -32,21 +31,23 @@ public async Task Invoke(HttpContext context)

if (body.StartsWith("{"))
{
var jObject = JObject.Parse(body);
var jObject = JsonDocument.Parse(body);
_logger.LogTrace(body);
if (jObject.ContainsKey("challenge"))
JsonElement challengeValue;
bool isChallenge = jObject.RootElement.TryGetProperty("challenge", out challengeValue);
if (isChallenge)
{
context.Items.Add(HttpItemKeys.ChallengeKey, jObject["challenge"]);
context.Items.Add(HttpItemKeys.ChallengeKey, challengeValue);
}
else
{
var metadata = JsonConvert.DeserializeObject<EventMetaData>(body);
if (jObject["event"] is JObject @event)
var metadata = JsonSerializer.Deserialize<EventMetaData>(body, WebOptions);
if (jObject.RootElement.GetProperty("event") is JsonElement @event)
{
var slackEvent = ToEventType(@event, body);
context.Items.Add(HttpItemKeys.EventMetadataKey, metadata);
context.Items.Add(HttpItemKeys.SlackEventKey, slackEvent);
context.Items.Add(HttpItemKeys.EventTypeKey, @event["type"]);
context.Items.Add(HttpItemKeys.EventTypeKey, @event.GetProperty("type"));
}
}
}
Expand All @@ -58,7 +59,7 @@ public async Task Invoke(HttpContext context)
_logger.LogTrace(body);
var payloadJsonUrlEncoded = body.Remove(0,8);
var decodedJson = System.Net.WebUtility.UrlDecode(payloadJsonUrlEncoded);
var payload = JObject.Parse(decodedJson);
var payload = JsonDocument.Parse(decodedJson).RootElement;
var interactivePayloadTyped = ToInteractiveType(payload, body);
context.Items.Add(HttpItemKeys.InteractivePayloadKey, interactivePayloadTyped);
}
Expand All @@ -69,51 +70,54 @@ public async Task Invoke(HttpContext context)
await _next(context);
}

private static SlackEvent ToEventType(JObject eventJson, string raw)
private static JsonSerializerOptions WebOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);

private static SlackEvent ToEventType(JsonElement eventJson, string raw)
{
var eventType = GetEventType(eventJson);
string json = eventJson.ToString();
switch (eventType)
{
case EventTypes.AppMention:
return eventJson.ToObject<AppMentionEvent>();
return JsonSerializer.Deserialize<AppMentionEvent>(json, WebOptions);
case EventTypes.MemberJoinedChannel:
return eventJson.ToObject<MemberJoinedChannelEvent>();
return JsonSerializer.Deserialize<MemberJoinedChannelEvent>(json, WebOptions);
case EventTypes.AppHomeOpened:
return eventJson.ToObject<AppHomeOpenedEvent>();
return JsonSerializer.Deserialize<AppHomeOpenedEvent>(json, WebOptions);
default:
UnknownSlackEvent unknownSlackEvent = eventJson.ToObject<UnknownSlackEvent>();
UnknownSlackEvent unknownSlackEvent = JsonSerializer.Deserialize<UnknownSlackEvent>(json, WebOptions);
unknownSlackEvent.RawJson = raw;
return unknownSlackEvent;
}
}

private static Interaction ToInteractiveType(JObject payloadJson, string raw)
private static Interaction ToInteractiveType(JsonElement payloadJson, string raw)
{
var eventType = GetEventType(payloadJson);
switch (eventType)
{
case InteractionTypes.ViewSubmission:
var viewSubmission = payloadJson.ToObject<ViewSubmission>();
var viewSubmission = JsonSerializer.Deserialize<ViewSubmission>(payloadJson.GetString(), WebOptions);

var view = payloadJson["view"] as JObject;
var viewState = view["state"] as JObject;;
viewSubmission.ViewId = view.Value<string>("id");
var view = payloadJson.GetProperty("view");
var viewState = view.GetProperty("state");
viewSubmission.ViewId = view.GetProperty("id").GetString();
viewSubmission.ViewState = viewState;
return viewSubmission;
case InteractionTypes.BlockActions:
return payloadJson.ToObject<BlockActionInteraction>();
return JsonSerializer.Deserialize<BlockActionInteraction>(payloadJson.GetString(), WebOptions);
default:
var unknownSlackEvent = payloadJson.ToObject<UnknownInteractiveMessage>();
var unknownSlackEvent = JsonSerializer.Deserialize<UnknownInteractiveMessage>(payloadJson.GetString(), WebOptions);
unknownSlackEvent.RawJson = raw;
return unknownSlackEvent;
}
}

public static string GetEventType(JObject eventJson)
public static string GetEventType(JsonElement eventJson)
{
if (eventJson != null)
if (eventJson.ValueKind != JsonValueKind.Null)
{
return eventJson["type"].Value<string>();
return eventJson.GetProperty("type").GetString();
}

return "unknown";
Expand Down
3 changes: 0 additions & 3 deletions source/src/Slackbot.Net.Endpoints/Models/Interactive/Team.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using Newtonsoft.Json;

namespace Slackbot.Net.Endpoints.Models.Interactive
{
public class Team
{
[JsonProperty("id")]
public string Id { get; set; }
}
}
3 changes: 0 additions & 3 deletions source/src/Slackbot.Net.Endpoints/Models/Interactive/User.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using Newtonsoft.Json;

namespace Slackbot.Net.Endpoints.Models.Interactive
{
public class User
{
[JsonProperty("user_id")]
public string User_Id { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

using Newtonsoft.Json.Linq;
using System.Text.Json;

namespace Slackbot.Net.Endpoints.Models.Interactive.ViewSubmissions
{
Expand All @@ -9,6 +8,6 @@ public class ViewSubmission : Interaction
public User User { get; set; }

public string ViewId { get; set; }
public JObject ViewState { get; set; }
public JsonElement ViewState { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@
</PropertyGroup>

<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,24 @@
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

using Slackbot.Net.SlackClients.Http.Exceptions;
using Slackbot.Net.SlackClients.Http.Models.Responses;

namespace Slackbot.Net.SlackClients.Http.Extensions
{
internal static class HttpClientExtensions
{
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
private static readonly JsonSerializerOptions JsonSerializerSettings = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};

public static async Task<T> PostJson<T>(this HttpClient httpClient, object payload, string api, Action<string> logger = null) where T:Response
{
var serializedObject = JsonConvert.SerializeObject(payload, JsonSerializerSettings);
var serializedObject = JsonSerializer.Serialize(payload, JsonSerializerSettings);
var httpContent = new StringContent(serializedObject, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, api)
{
Expand All @@ -40,7 +39,7 @@ public static async Task<T> PostJson<T>(this HttpClient httpClient, object paylo

response.EnsureSuccessStatusCode();

var resObj = JsonConvert.DeserializeObject<T>(responseContent, JsonSerializerSettings);
var resObj = JsonSerializer.Deserialize<T>(responseContent, JsonSerializerSettings);

if (!resObj.Ok)
{
Expand Down Expand Up @@ -75,7 +74,7 @@ public static async Task<T> PostParametersAsForm<T>(this HttpClient httpClient,

response.EnsureSuccessStatusCode();

var resObj = JsonConvert.DeserializeObject<T>(responseContent, JsonSerializerSettings);
var resObj = JsonSerializer.Deserialize<T>(responseContent, JsonSerializerSettings);

if(!resObj.Ok)
throw new WellKnownSlackApiException(error: $"{resObj.Error}", responseContent:responseContent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,38 +21,38 @@ public class ChatPostMessageRequest

public class Attachment
{
public string callback_id;
public string fallback;
public string color;
public string pretext;
public string author_name;
public string author_link;
public string author_icon;
public string title;
public string title_link;
public string text;
public Field[] fields;
public string image_url;
public string thumb_url;
public string[] mrkdwn_in;
public AttachmentAction[] actions;
public string footer;
public string footer_icon;
public string callback_id{ get; set; }
public string fallback { get; set; }
public string color { get; set; }
public string pretext { get; set; }
public string author_name { get; set; }
public string author_link { get; set; }
public string author_icon { get; set; }
public string title { get; set; }
public string title_link { get; set; }
public string text { get; set; }
public Field[] fields { get; set; }
public string image_url { get; set; }
public string thumb_url { get; set; }
public string[] mrkdwn_in { get; set; }
public AttachmentAction[] actions { get; set; }
public string footer { get; set; }
public string footer_icon { get; set; }
}

public class Field
{
public string title;
public string value;
public bool @short;
public string title { get; set; }
public string value { get; set; }
public bool @short { get; set; }
}

public class AttachmentAction
{
public string type = "button";
public string style;
public string value;
public ActionConfirm confirm;
public string style { get; set; }
public string value { get; set; }
public ActionConfirm confirm { get; set; }

public AttachmentAction(string name, string text)
{
Expand All @@ -67,9 +67,9 @@ public AttachmentAction(string name, string text)

public class ActionConfirm
{
public string title;
public string text;
public string ok_text;
public string dismiss_text;
public string title { get; set; }
public string text { get; set; }
public string ok_text { get; set; }
public string dismiss_text { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using Newtonsoft.Json;

namespace Slackbot.Net.SlackClients.Http.Models.Requests.ViewPublish
{
public class ViewPublishRequest
Expand All @@ -8,8 +6,7 @@ public ViewPublishRequest(string userId)
{
User_Id = userId;
}

[JsonProperty("user_id")]

public string User_Id { get; }

public View View { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ namespace Slackbot.Net.SlackClients.Http.Models.Responses.ChatPostMessage
{
public class ChatPostMessageResponse : Response
{
public string ts;
public string channel;
public Message message;
public string ts { get; set; }
public string channel { get; set; }
public Message message{ get; set; }
}

public class Message
{
public string text;
public string user;
public string username;
public string type;
public string subtype;
public string ts;
public string text { get; set; }
public string user { get; set; }
public string username { get; set; }
public string type { get; set; }
public string subtype{ get; set; }
public string ts{ get; set; }
}
}
Loading