aboutsummaryrefslogtreecommitdiffstats
path: root/DiscordToXIV/DiscordMessenger.cs
blob: a8d51f90cb81c468a5dfc49ae3d8811e5a0fbe3a (plain) (blame)
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
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DiscordToXIV
{
    public class DiscordMessenger
    {
        private readonly string _authorization;
        private readonly string _baseUrl;
        private readonly Plugin Plugin;

        public DiscordMessenger(Plugin plugin, string authorization = "", string baseUrl = "https://discord.com/api/v9/channels/")
        {
            Plugin = plugin;
            _authorization = authorization;
            _baseUrl = baseUrl;
        }

        public async Task SendMessageAsync(string message, string channelId)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create($"{_baseUrl}{channelId}/messages");
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Headers["Authorization"] = _authorization;
                var payload = $"{{\"content\":\"{message}\"}}";
                var data = Encoding.UTF8.GetBytes(payload);
                using (var stream = await request.GetRequestStreamAsync())
                {
                    await stream.WriteAsync(data, 0, data.Length);
                }
                using (var response = (HttpWebResponse)await request.GetResponseAsync())
                {
                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        Plugin.ChatGui.PrintError("Failed to send message!");
                    }
                    else
                    {
                        Plugin.ChatGui.Print(">> " + Plugin.Configuration.ChannelMappings[channelId] + ": " + message);
                    }
                }
            }
            catch (WebException ex)
            {
                Plugin.ChatGui.PrintError($"Error sending message: {ex.Message}");
            }
        }
    }
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage