forked from hantabaru1014/ResoniteScreenshotExtensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiscordWebhookClient.cs
More file actions
73 lines (63 loc) · 2.29 KB
/
DiscordWebhookClient.cs
File metadata and controls
73 lines (63 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using MimeDetective;
namespace ResoniteScreenshotExtensions;
public class DiscordWebhookClient
{
private string _webhookUrl;
private HttpClient _client;
public DiscordWebhookClient(string webhookUrl)
{
_webhookUrl = webhookUrl;
_client = new HttpClient();
}
public async Task<bool> SendImage(string srcPath, string? payloadJson = null)
{
using (var fileStream = File.OpenRead(srcPath))
{
var fileType = fileStream.GetFileType();
fileStream.Seek(0, SeekOrigin.Begin);
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue(fileType.Mime);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"image.{fileType.Extension}",
};
var request = new HttpRequestMessage(HttpMethod.Post, _webhookUrl);
var form = new MultipartFormDataContent();
form.Add(fileContent, "file");
if (payloadJson != null)
{
form.Add(new StringContent(payloadJson), "payload_json");
}
request.Content = form;
var response = await _client.SendAsync(request);
return response.IsSuccessStatusCode;
}
}
public class EmbedField
{
public string Name { get; set; }
public string Value { get; set; }
public bool IsInlined { get; set; }
public EmbedField(string name, string value, bool inlined = true)
{
Name = name;
Value = value;
IsInlined = inlined;
}
public string ToJson()
{
return $"{{\"name\": \"{Name}\", \"value\": \"{Value}\", \"inline\": {(IsInlined ? "true" : "false")} }}";
}
}
public async Task<bool> SendImageWithMetadata(string srcPath, IEnumerable<EmbedField> fields)
{
var json = $"{{\"embeds\": [{{\"fields\": [{fields.Select(f => f.ToJson()).Aggregate((acc, curr) => $"{acc}, {curr}")}]}}]}}";
return await SendImage(srcPath, json);
}
}