This commit is contained in:
slothdpal
2024-05-23 20:55:23 +03:00
parent 25abcc4bda
commit 8233be32a3
6 changed files with 453 additions and 19 deletions

103
Discord/DiscordWebHook.cs Normal file
View File

@@ -0,0 +1,103 @@
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Discord.Webhook
{
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)
{
string prefix = stream.Length > 0 ? "\r\n--" : "--";
string fBegin = $"{prefix}{bound}\r\n";
byte[] fBeginBuffer = Utils.Encode(fBegin);
byte[] cDispositionBuffer = Utils.Encode(cDisposition);
byte[] cTypeBuffer = Utils.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)
{
string cDisposition = "Content-Disposition: form-data; name=\"payload_json\"\r\n";
string cType = "Content-Type: application/octet-stream\r\n\r\n";
AddField(stream, bound, cDisposition, cType, Utils.Encode(json));
}
private void SetFile(MemoryStream stream, string bound, int index, FileInfo file)
{
string cDisposition = $"Content-Disposition: form-data; name=\"file_{index}\"; filename=\"{file.Name}\"\r\n";
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.");
string bound = "------------------------" + DateTime.Now.Ticks.ToString("x");
WebClient webhookRequest = new WebClient();
webhookRequest.Headers.Add("Content-Type", "multipart/form-data; boundary=" + bound);
MemoryStream stream = new MemoryStream();
for (int i = 0; i < files.Length; i++)
SetFile(stream, bound, i, files[i]);
string json = message.ToString();
SetJsonPayload(stream, bound, json);
byte[] bodyEnd = Utils.Encode($"\r\n--{bound}--");
stream.Write(bodyEnd, 0, bodyEnd.Length);
//byte[] beginBodyBuffer = Encoding.UTF8.GetBytes("--" + bound + "\r\n");
//stream.Write(beginBodyBuffer, 0, beginBodyBuffer.Length);
//bool flag = file != null && file.Exists;
//if (flag)
//{
// string fileBody = "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.Name + "\"\r\nContent-Type: application/octet-stream\r\n\r\n";
// byte[] fileBodyBuffer = Encoding.UTF8.GetBytes(fileBody);
// stream.Write(fileBodyBuffer, 0, fileBodyBuffer.Length);
// byte[] fileBuffer = File.ReadAllBytes(file.FullName);
// stream.Write(fileBuffer, 0, fileBuffer.Length);
// string fileBodyEnd = "\r\n--" + bound + "\r\n";
// byte[] fileBodyEndBuffer = Encoding.UTF8.GetBytes(fileBodyEnd);
// stream.Write(fileBodyEndBuffer, 0, fileBodyEndBuffer.Length);
//}
//string jsonBody = string.Concat(new string[]
//{
// "Content-Disposition: form-data; name=\"payload_json\"\r\nContent-Type: application/json\r\n\r\n",
// string.Format("{0}\r\n", message),
// "--",
// bound,
// "--"
//});
//byte[] jsonBodyBuffer = Encoding.UTF8.GetBytes(jsonBody);
//stream.Write(jsonBodyBuffer, 0, jsonBodyBuffer.Length);
try
{
webhookRequest.UploadData(this.Url, stream.ToArray());
}
catch (WebException ex)
{
throw new WebException(Utils.Decode(ex.Response.GetResponseStream()));
}
stream.Dispose();
}
}
}

229
Discord/Structs.cs Normal file
View File

@@ -0,0 +1,229 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Discord
{
/// <summary>
/// Discord message data object
/// </summary>
public struct DiscordMessage
{
/// <summary>
/// Message content
/// </summary>
public string Content;
/// <summary>
/// Read message to everyone on the channel
/// </summary>
public bool TTS;
/// <summary>
/// Webhook profile username to be shown
/// </summary>
public string Username;
/// <summary>
/// Webhook profile avater to be shown
/// </summary>
public string AvatarUrl;
/// <summary>
/// List of embeds
/// </summary>
public List<DiscordEmbed> Embeds;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
/// <summary>
/// Discord embed data object
/// </summary>
public struct DiscordEmbed
{
/// <summary>
/// Embed title
/// </summary>
public string Title;
/// <summary>
/// Embed description
/// </summary>
public string Description;
/// <summary>
/// Embed url
/// </summary>
public string Url;
/// <summary>
/// Embed timestamp
/// </summary>
public DateTime? Timestamp;
/// <summary>
/// Embed color
/// </summary>
public Color? Color;
/// <summary>
/// Embed footer
/// </summary>
public EmbedFooter? Footer;
/// <summary>
/// Embed image
/// </summary>
public EmbedMedia? Image;
/// <summary>
/// Embed thumbnail
/// </summary>
public EmbedMedia? Thumbnail;
/// <summary>
/// Embed video
/// </summary>
public EmbedMedia? Video;
/// <summary>
/// Embed provider
/// </summary>
public EmbedProvider? Provider;
/// <summary>
/// Embed author
/// </summary>
public EmbedAuthor? Author;
/// <summary>
/// Embed fields list
/// </summary>
public List<EmbedField> Fields;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
/// <summary>
/// Discord embed footer data object
/// </summary>
public struct EmbedFooter
{
/// <summary>
/// Footer text
/// </summary>
public string Text;
/// <summary>
/// Footer icon
/// </summary>
public string IconUrl;
/// <summary>
/// Footer icon proxy
/// </summary>
public string ProxyIconUrl;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
/// <summary>
/// Discord embed media data object (images/thumbs/videos)
/// </summary>
public struct EmbedMedia
{
/// <summary>
/// Media url
/// </summary>
public string Url;
/// <summary>
/// Media proxy url
/// </summary>
public string ProxyUrl;
/// <summary>
/// Media height
/// </summary>
public int? Height;
/// <summary>
/// Media width
/// </summary>
public int? Width;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
/// <summary>
/// Discord embed provider data object
/// </summary>
public struct EmbedProvider
{
/// <summary>
/// Provider name
/// </summary>
public string Name;
/// <summary>
/// Provider url
/// </summary>
public string Url;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
/// <summary>
/// Discord embed author data object
/// </summary>
public struct EmbedAuthor
{
/// <summary>
/// Author name
/// </summary>
public string Name;
/// <summary>
/// Author url
/// </summary>
public string Url;
/// <summary>
/// Author icon
/// </summary>
public string IconUrl;
/// <summary>
/// Author icon proxy
/// </summary>
public string ProxyIconUrl;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
/// <summary>
/// Discord embed field data object
/// </summary>
public struct EmbedField
{
/// <summary>
/// Field name
/// </summary>
public string Name;
/// <summary>
/// Field value
/// </summary>
public string Value;
/// <summary>
/// Field align
/// </summary>
public bool InLine;
public override string ToString() => Utils.StructToJson(this).ToString(Formatting.None);
}
}

108
Discord/Utils.cs Normal file
View File

@@ -0,0 +1,108 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Discord
{
public static class Utils
{
/// <summary>
/// Convert Color object into hex integer
/// </summary>
/// <param name="color">Color to be converted</param>
/// <returns>Converted hex integer</returns>
public static int ColorToHex(Color color)
{
string HS =
color.R.ToString("X2") +
color.G.ToString("X2") +
color.B.ToString("X2");
return int.Parse(HS, System.Globalization.NumberStyles.HexNumber);
}
internal static JObject StructToJson(object @struct)
{
Type type = @struct.GetType();
JObject json = new JObject();
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo field in fields)
{
string name = FieldNameToJsonName(field.Name);
object value = field.GetValue(@struct);
if (value == null)
continue;
if (value is bool)
json.Add(name, (bool)value);
else if (value is int)
json.Add(name, (int)value);
else if (value is Color)
json.Add(name, ColorToHex((Color)value));
else if (value is string)
json.Add(name, value as string);
else if (value is DateTime)
json.Add(name, ((DateTime)value).ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz"));
else if (value is IList && value.GetType().IsGenericType)
{
JArray array = new JArray();
foreach (object obj in value as IList)
array.Add(StructToJson(obj));
json.Add(name, array);
}
else json.Add(name, StructToJson(value));
}
return json;
}
static string[] ignore = { "InLine" };
internal static string FieldNameToJsonName(string name)
{
if (ignore.ToList().Contains(name))
return name.ToLower();
List<char> result = new List<char>();
if (IsFullUpper(name))
result.AddRange(name.ToLower().ToCharArray());
else
for (int i = 0; i < name.Length; i++)
{
if (i > 0 && char.IsUpper(name[i]))
result.AddRange(new[] { '_', char.ToLower(name[i]) });
else result.Add(char.ToLower(name[i]));
}
return string.Join("", result);
}
internal static bool IsFullUpper(string str)
{
bool upper = true;
for (int i = 0; i < str.Length; i++)
{
if (!char.IsUpper(str[i]))
{
upper = false;
break;
}
}
return upper;
}
public static string Decode(Stream source)
{
using (StreamReader reader = new StreamReader(source))
return reader.ReadToEnd();
}
public static byte[] Encode(string source, string encoding = "utf-8")
=> Encoding.GetEncoding(encoding).GetBytes(source);
}
}

View File

@@ -67,6 +67,9 @@
<SpecificVersion>False</SpecificVersion>
<HintPath>.\CSharpDiscordWebhook.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
@@ -80,6 +83,9 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Discord\DiscordWebHook.cs" />
<Compile Include="Discord\Structs.cs" />
<Compile Include="Discord\Utils.cs" />
<Compile Include="Form1.cs">
<SubType>Form</SubType>
</Compile>
@@ -112,6 +118,7 @@
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
@@ -142,7 +149,7 @@
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>copy $(ProjectDir)\CSharpDiscordWebhook\CSharpDiscordWebhook\$(OutDir)\* $(TargetDir)
copy $(ProjectDir)\CSharpDiscordWebhook\CSharpDiscordWebhook\$(OutDir)\* $(ProjectDir)</PreBuildEvent>
<PreBuildEvent>rem copy $(ProjectDir)\CSharpDiscordWebhook\CSharpDiscordWebhook\$(OutDir)\* $(TargetDir)
rem copy $(ProjectDir)\CSharpDiscordWebhook\CSharpDiscordWebhook\$(OutDir)\* $(ProjectDir)</PreBuildEvent>
</PropertyGroup>
</Project>

View File

@@ -4,11 +4,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00
VisualStudioVersion = 17.9.34622.214
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Process Auto Relaunch", "Process Auto Relaunch.csproj", "{B48F106C-F4E2-4BFB-9BAA-42FC13C03FDD}"
ProjectSection(ProjectDependencies) = postProject
{11C71B78-004A-471F-B29D-C2CBE4673579} = {11C71B78-004A-471F-B29D-C2CBE4673579}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpDiscordWebhook", "CSharpDiscordWebhook\CSharpDiscordWebhook\CSharpDiscordWebhook.csproj", "{11C71B78-004A-471F-B29D-C2CBE4673579}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -32,18 +27,6 @@ Global
{B48F106C-F4E2-4BFB-9BAA-42FC13C03FDD}.Release|Any CPU.Build.0 = Release|Any CPU
{B48F106C-F4E2-4BFB-9BAA-42FC13C03FDD}.Release|x64.ActiveCfg = Release|x64
{B48F106C-F4E2-4BFB-9BAA-42FC13C03FDD}.Release|x64.Build.0 = Release|x64
{11C71B78-004A-471F-B29D-C2CBE4673579}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Debug|Any CPU.Build.0 = Debug|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Debug|x64.ActiveCfg = Debug|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Debug|x64.Build.0 = Debug|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.DebugFULL|Any CPU.ActiveCfg = Debug|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.DebugFULL|Any CPU.Build.0 = Debug|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.DebugFULL|x64.ActiveCfg = DebugFULL|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.DebugFULL|x64.Build.0 = DebugFULL|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Release|Any CPU.ActiveCfg = Release|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Release|Any CPU.Build.0 = Release|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Release|x64.ActiveCfg = Release|Any CPU
{11C71B78-004A-471F-B29D-C2CBE4673579}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

4
packages.config Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
</packages>