77 lines
2.8 KiB
C#
77 lines
2.8 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Net;
|
|
|
|
namespace Global.API.Discord
|
|
{
|
|
public class DiscordWebhook
|
|
{
|
|
/// <summary>
|
|
/// Webhook url
|
|
/// </summary>
|
|
public string Url { get; set; }
|
|
|
|
private void AddField(MemoryStream stream, string bound, string cDisposition, string cType, byte[] data)
|
|
{
|
|
var prefix = stream.Length > 0 ? "\r\n--" : "--";
|
|
var fBegin = $"{prefix}{bound}\r\n";
|
|
|
|
var fBeginBuffer = DiscordUtil.Encode(fBegin);
|
|
var cDispositionBuffer = DiscordUtil.Encode(cDisposition);
|
|
var cTypeBuffer = DiscordUtil.Encode(cType);
|
|
|
|
stream.Write(fBeginBuffer, 0, fBeginBuffer.Length);
|
|
stream.Write(cDispositionBuffer, 0, cDispositionBuffer.Length);
|
|
stream.Write(cTypeBuffer, 0, cTypeBuffer.Length);
|
|
stream.Write(data, 0, data.Length);
|
|
}
|
|
|
|
private void SetJsonPayload(MemoryStream stream, string bound, string json)
|
|
{
|
|
const string cDisposition = "Content-Disposition: form-data; name=\"payload_json\"\r\n";
|
|
const string cType = "Content-Type: application/octet-stream\r\n\r\n";
|
|
AddField(stream, bound, cDisposition, cType, DiscordUtil.Encode(json));
|
|
}
|
|
|
|
private void SetFile(MemoryStream stream, string bound, int index, FileInfo file)
|
|
{
|
|
var cDisposition = $"Content-Disposition: form-data; name=\"file_{index}\"; filename=\"{file.Name}\"\r\n";
|
|
const string cType = "Content-Type: application/octet-stream\r\n\r\n";
|
|
AddField(stream, bound, cDisposition, cType, File.ReadAllBytes(file.FullName));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Send webhook message
|
|
/// </summary>
|
|
public void Send(DiscordMessage message, params FileInfo[] files)
|
|
{
|
|
if (string.IsNullOrEmpty(Url))
|
|
throw new ArgumentNullException($"Invalid Webhook URL {Url}.");
|
|
|
|
var bound = "------------------------" + DateTime.Now.Ticks.ToString("x");
|
|
var webhookRequest = new WebClient();
|
|
webhookRequest.Headers.Add("Content-Type", "multipart/form-data; boundary=" + bound);
|
|
|
|
var stream = new MemoryStream();
|
|
for (var i = 0; i < files.Length; i++)
|
|
SetFile(stream, bound, i, files[i]);
|
|
|
|
var json = message.ToString();
|
|
SetJsonPayload(stream, bound, json);
|
|
|
|
var bodyEnd = DiscordUtil.Encode($"\r\n--{bound}--");
|
|
stream.Write(bodyEnd, 0, bodyEnd.Length);
|
|
|
|
try
|
|
{
|
|
webhookRequest.UploadData(Url, stream.ToArray());
|
|
}
|
|
catch (WebException ex)
|
|
{
|
|
throw new WebException(DiscordUtil.Decode(ex.Response.GetResponseStream()));
|
|
}
|
|
|
|
stream.Dispose();
|
|
}
|
|
}
|
|
} |