-
Notifications
You must be signed in to change notification settings - Fork 1
/
DiscordProtocol.cs
311 lines (284 loc) · 15.1 KB
/
DiscordProtocol.cs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;
using Discord;
using Discord.WebSocket;
using Newtonsoft.Json;
using System.Globalization;
namespace TrixieBot
{
public class DiscordProtocol : BaseProtocol
{
private DiscordSocketClient bot;
public DiscordProtocol(Config config) : base(config)
{
this.config = config;
}
public override async Task<bool> Start()
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " Discord Protocol starting...");
bot = new DiscordSocketClient(new DiscordSocketConfig()
{
LogLevel = LogSeverity.Warning,
GatewayIntents = GatewayIntents.AllUnprivileged | GatewayIntents.MessageContent, // When creating bot on discord.com/developer, check Message Content Intent
});
// Hook up logging
bot.Log += Log;
// Hook up message handling
bot.MessageReceived += MessageReceived;
// Log in and start bot
await bot.LoginAsync(TokenType.Bot, config.Keys.DiscordToken).ConfigureAwait(false);
await bot.StartAsync().ConfigureAwait(false);
// Wait forever
await Task.Delay(-1).ConfigureAwait(false);
return true;
}
public async void OnTimerTick(object configObject)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " Checking Discord RSS / Atom Feeds...");
// Read Config
var config = JsonConvert.DeserializeObject<Config>(System.IO.File.ReadAllText("config.json"));
// Parse each feed
var writeConfig = false;
for (var thisRss = 0; thisRss < config.Rss.Length; thisRss++)
{
if (string.Equals(config.Rss[thisRss].Protocol, "DISCORD", StringComparison.InvariantCultureIgnoreCase))
{
var newMostRecent = config.Rss[thisRss].MostRecent;
var numFound = 0;
if (string.Equals(config.Rss[thisRss].Format, "RSS", StringComparison.InvariantCultureIgnoreCase))
{
// Parse RSS Format
try
{
var xDocument = XDocument.Load(config.Rss[thisRss].URL);
foreach (var xElement in xDocument.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item"))
{
// Parse xDocument to POCO
var rssItem = new RSSItem
{
Title = xElement.Elements().First(i => i.Name.LocalName == "title").Value,
Link = xElement.Elements().First(i => i.Name.LocalName == "link").Value,
Description = xElement.Elements().First(i => i.Name.LocalName == "description").Value,
};
// Dates in RSS are often in some retarded format
var dateString = xElement.Elements().First(i => i.Name.LocalName == "pubDate").Value;
dateString = dateString.Replace("UTC", "+00:00").Replace("GMT", "+00:00").Replace("EST", "-05:00").Replace("EDT", "-04:00").Replace("CST", "-06:00").Replace("CDT", "-05:00").Replace("MST", "-07:00").Replace("MDT", "-06:00").Replace("PST", "-08:00").Replace("PDT", "-07:00"); // Hack for time zone names instead of UTC offsets
try
{
// Parse the dates using the standard universal date format
rssItem.PubDate = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}
catch
{
try
{
// Try the "r" "S" and "U" formats
var formats = new string[] { "r", "S", "U"};
rssItem.PubDate = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}
catch
{
try
{
// Try RFC822 with 2 and 4 digit year
var formats = new string[] {"ddd, dd MMM yyyy HH:mm:ss zzzzz", "ddd, dd MMM yy HH:mm:ss zzzzz", "ddd, dd MMM yyyy HH:mm:ss zzzz", "ddd, dd MMM yy HH:mm:ss zzzz"};
rssItem.PubDate = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
}
catch
{
// Everything failed. Give up.
rssItem.PubDate = config.Rss[thisRss].MostRecent;
}
}
}
// If this item more recent than our latest pull, output it
if (rssItem.PubDate > config.Rss[thisRss].MostRecent)
{
numFound++;
if (numFound < 2 || config.Rss[thisRss].Type == "All")
{
SendPlainTextMessage(config.Rss[thisRss].Destination, rssItem.Title + "\r\n" + rssItem.Link);
}
newMostRecent = rssItem.PubDate.GetValueOrDefault();
}
}
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " Error reading Discord RSS " + config.Rss[thisRss].URL + ": " + ex.ToString());
}
}
else
{
// Parse Atom Format
try
{
var xDocument = XDocument.Load(config.Rss[thisRss].URL);
foreach (var xElement in xDocument.Root.Descendants().Where(i => i.Name.LocalName == "entry"))
{
// Parse xDocument to POCO
var atomEntry = new AtomEntry
{
Title = xElement.Elements().First(i => i.Name.LocalName == "title").Value,
Link = xElement.Elements().First(i => i.Name.LocalName == "link").Attributes().First(a => a.Name == "href").Value,
Content = xElement.Elements().First(i => i.Name.LocalName == "content").Value,
Updated = DateTime.Parse(xElement.Elements().First(i => i.Name.LocalName == "updated").Value)
};
// If this item more recent than our latest pull, update config
if (atomEntry.Updated > config.Rss[thisRss].MostRecent)
{
numFound++;
if (numFound < 2 || config.Rss[thisRss].Type == "All")
{
SendPlainTextMessage(config.Rss[thisRss].Destination, atomEntry.Title + "\r\n" + atomEntry.Link);
}
newMostRecent = atomEntry.Updated;
}
}
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " Error reading Discord Atom " + config.Rss[thisRss].URL + ": " + ex.ToString());
}
}
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " Found " +numFound + " items on Discord RSS " + config.Rss[thisRss].URL + "...");
// Write back to config if we found anything
if (newMostRecent > config.Rss[thisRss].MostRecent)
{
config.Rss[thisRss].MostRecent = newMostRecent;
writeConfig = true;
}
}
}
// Save Config
if (writeConfig)
{
await System.IO.File.WriteAllTextAsync("config.json", JsonConvert.SerializeObject(config, Formatting.Indented)).ConfigureAwait(false);
}
}
private Task Log(LogMessage log)
{
Console.WriteLine(log.ToString());
return Task.CompletedTask;
}
private Task MessageReceived(SocketMessage message)
{
if(message is SocketUserMessage)
{
var socketUserMessage = message as SocketUserMessage;
Processor.TextMessage(this, config, socketUserMessage.Channel.Id.ToString(), socketUserMessage.Content, socketUserMessage.Author.Username, socketUserMessage.Author.Username);
}
else if(message is SocketSystemMessage)
{
var socketSystemMessage = message as SocketUserMessage;
//// Don't care for now
}
return Task.CompletedTask;
}
public override void SendFile(string destination, string Url, string filename = "", string referrer = "https://duckduckgo.com")
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " " + destination + " > " + Url);
SendStatusTyping(destination);
var httpClient = new ProHttpClient()
{
ReferrerUri = referrer
};
var stream = httpClient.DownloadData(Url).Result;
if (filename?.Length == 0)
{
filename = Url.Substring(Url.LastIndexOf("/", StringComparison.Ordinal) + 1, 9999);
}
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.SendFileAsync(stream, filename);
}
public override void SendImage(string destination, string Url, string caption, string referrer = "https://duckduckgo.com")
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " " + destination + " > " + Url + " : " + caption);
SendStatusTyping(destination);
try
{
var httpClient = new ProHttpClient()
{
ReferrerUri = referrer
};
var stream = httpClient.DownloadData(Url).Result;
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
var extension = ".jpg";
if (Url.Contains(".gif") || Url.Contains("image/gif"))
{
extension = ".gif";
}
else if (Url.Contains(".png") || Url.Contains("image/png"))
{
extension = ".png";
}
else if (Url.Contains(".tif"))
{
extension = ".tif";
}
else if (Url.Contains(".bmp"))
{
extension = ".bmp";
}
SendStatusUploadingPhoto(destination);
channel.SendFileAsync(stream, "image" + extension, caption);
}
catch (System.Net.Http.HttpRequestException ex)
{
Console.WriteLine("Unable to download " + ex.HResult + " " + ex.Message);
SendPlainTextMessage(destination, Url);
}
catch (System.Net.WebException ex)
{
Console.WriteLine("Unable to download " + ex.HResult + " " + ex.Message);
SendPlainTextMessage(destination, Url);
}
catch (Exception ex)
{
Console.WriteLine(Url + " Threw: " + ex.Message);
SendPlainTextMessage(destination, "The Great & Powerful Trixie got bored while waiting for that to download. Try later. " + ex.Message);
}
}
public override void SendHTMLMessage(string destination, string message)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " " + destination + " > " + message);
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.SendMessageAsync(message);
}
public override void SendLocation(string destination, float latitude, float longitude)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " " + destination + " > " + latitude + " + " + longitude);
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.SendMessageAsync("http://maps.google.com/maps?z=12&t=m&q=loc:" + latitude + "+" + longitude);
}
public override void SendMarkdownMessage(string destination, string message)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " " + destination + " > " + message);
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.SendMessageAsync(message);
}
public override void SendPlainTextMessage(string destination, string message)
{
Console.WriteLine(DateTime.Now.ToString("M/d HH:mm") + " " + destination + " > " + message);
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.SendMessageAsync(message);
}
public override void SendStatusTyping(string destination)
{
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.TriggerTypingAsync();
}
public override void SendStatusUploadingFile(string destination)
{
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.TriggerTypingAsync();
}
public override void SendStatusUploadingPhoto(string destination)
{
var channel = bot.GetChannelAsync(Convert.ToUInt64(destination)).Result as IMessageChannel;
channel.TriggerTypingAsync();
}
}
}