Last active
June 6, 2016 20:00
-
-
Save mhinze/dcee9eb4de77707f632e900e9a19cbdc to your computer and use it in GitHub Desktop.
slack subroute.io
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net; | |
using Subroute.Common; | |
using System.Configuration; | |
using System.Linq; | |
using System.Collections.Generic; | |
using Newtonsoft.Json; | |
// Slack webhook example | |
namespace Subroute.Container | |
{ | |
public class RouteMethods : BaseController | |
{ | |
static RouteMethods() | |
{ | |
GlobalConfiguration.RequestFormatters.Add(new PostFormatter()); | |
} | |
public RouteResponse Post(RouteRequest request) | |
{ | |
var settings_token = ConfigurationManager.AppSettings.Get("token"); | |
var data = request.ReadBodyWithFormatter<Root>("post"); | |
if (!string.Equals(settings_token, data.token, StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
throw new Exception("Invalid token"); | |
} | |
return Json(HttpStatusCode.OK, new { text = data.ToString() }); | |
} | |
public RouteResponse Head(RouteRequest request) | |
{ | |
return NoContent(); | |
} | |
} | |
public class Root | |
{ | |
public string token; | |
public string team_id; | |
public string team_domain; | |
public string chanel_id; | |
public string timestamp; | |
public string user_id; | |
public string user_name; | |
public string text; | |
public string trigger_word; | |
public override string ToString() | |
{ | |
return string.Format("At {0} {1} ({2}) wrote: `{3}`", timestamp, user_name, user_id, text); | |
} | |
} | |
// a rather crude way to parse post data | |
public class PostFormatter : Subroute.Common.RequestFormatters.IRequestFormatter | |
{ | |
public string Name { get{return "post";}} | |
public object ReadRequestBody(Type bodyType, byte[] body) | |
{ | |
var data = System.Text.Encoding.UTF8.GetString(body); | |
var list = data.Split(new char[]{'\r', '\n', '&'}, StringSplitOptions.RemoveEmptyEntries); | |
var dict = new Dictionary<string, string>(); | |
foreach (var item in list) | |
{ | |
var kvp = item.Split(new char[]{'='}, 2, StringSplitOptions.None); | |
dict.Add(kvp[0], kvp[1]); | |
} | |
var json = JsonConvert.SerializeObject(dict); | |
var obj = JsonConvert.DeserializeObject(json, bodyType); | |
return obj; | |
} | |
} | |
} |
Author
mhinze
commented
Apr 13, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment