Skip to content

Instantly share code, notes, and snippets.

@crgrieve
Created October 17, 2020 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crgrieve/20f8c5eba1e3c8784c75728755a7f59d to your computer and use it in GitHub Desktop.
Save crgrieve/20f8c5eba1e3c8784c75728755a7f59d to your computer and use it in GitHub Desktop.
Umbraco Discord Webhook
using System;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Services.Implement;
namespace WebhooksExample.Events
{
[RuntimeLevel(MinLevel = RuntimeLevel.Run)]
public class DiscordWebhookComponent: ComponentComposer<DiscordWebhookComposer>
{
}
public class DiscordWebhookComposer : IComponent
{
public void Initialize()
{
ContentService.Published += ContentService_Published;
}
private void ContentService_Published(Umbraco.Core.Services.IContentService sender, Umbraco.Core.Events.ContentPublishedEventArgs e)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("YOUR_WEBHOOK_URL_HERE");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
foreach (var publishedItem in e.PublishedEntities)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
content = String.Format("Content Published: {0}",publishedItem.Name),
username = "Umbraco bot"
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
public void Terminate()
{
// do something when Umbraco terminates
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment