-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathValkyrja-methods.cs
626 lines (541 loc) · 20.2 KB
/
Valkyrja-methods.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using Discord;
using Valkyrja.entities;
using Discord.Net;
using Discord.Rest;
using Discord.WebSocket;
using guid = System.UInt64;
namespace Valkyrja.core
{
public partial class ValkyrjaClient : IValkyrjaClient, IDisposable
{
public async Task SendRawMessageToChannel(SocketTextChannel channel, string message)
{
//await LogMessage(LogType.Response, channel, this.GlobalConfig.UserId, message);
await channel.SendMessageSafe(message);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsGlobalAdmin(guid id)
{
return this.GlobalConfig.AdminUserId == id;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsSupportTeam(guid id)
{
return this.SupportTeam.Contains(id);
}
public bool IsSubscriber(guid id)
{
return IsGlobalAdmin(id) || this.Subscribers.ContainsKey(id);
}
public bool IsPartner(guid id)
{
return this.PartneredServers.ContainsKey(id);
}
public bool IsPremiumSubscriber(guid id)
{
return IsGlobalAdmin(id) || (this.Subscribers.ContainsKey(id) && this.Subscribers[id].IsPremium);
}
public bool IsBonusSubscriber(guid id)
{
return IsGlobalAdmin(id) || (this.Subscribers.ContainsKey(id) && this.Subscribers[id].HasBonus);
}
public bool IsPremiumPartner(guid id)
{
return this.PartneredServers.ContainsKey(id) && this.PartneredServers[id].IsPremium;
}
public bool IsPremium(Server server)
{
return IsPremiumSubscriber(server.Guild.OwnerId) || IsPremiumPartner(server.Id);
}
public bool IsTrialServer(guid id)
{
ServerContext dbContext = ServerContext.Create(this.DbConnectionString);
bool isTrial = dbContext.ServerStats.AsQueryable().Where(s => s.ServerId == id || s.OwnerId == id).AsEnumerable().Any(s => s.JoinedCount < this.GlobalConfig.VipTrialJoins && (!this.Servers.ContainsKey(id) || this.Servers[s.ServerId] == null || this.Servers[s.ServerId].Guild.CurrentUser == null || this.Servers[s.ServerId].Guild.CurrentUser.JoinedAt == null || DateTime.UtcNow - this.Servers[s.ServerId].Guild.CurrentUser.JoinedAt.Value.ToUniversalTime() < TimeSpan.FromHours(this.GlobalConfig.VipTrialHours)));
dbContext.Dispose();
return isTrial;
}
public async Task LogMessage(LogType logType, SocketTextChannel channel, guid authorId, string message)
{
LogEntry logEntry = new LogEntry(){
Type = logType,
UserId = authorId,
ChannelId = channel.Id,
ServerId = channel.Guild.Id,
DateTime = DateTime.UtcNow,
Message = message
};
await this.Events.LogEntryAdded(logEntry);
}
public async Task LogMessage(LogType logType, SocketTextChannel channel, SocketMessage message)
{
LogEntry logEntry = new LogEntry(){
Type = logType,
UserId = message.Author.Id,
MessageId = message.Id,
ChannelId = channel?.Id ?? 0,
ServerId = channel?.Guild.Id ?? 0,
DateTime = DateTime.UtcNow,
Message = message.Content
};
await this.Events.LogEntryAdded(logEntry);
}
public async Task LogMessageUnknown(LogType logType, guid serverId, string message)
{
LogEntry logEntry = new LogEntry(){
Type = logType,
UserId = 0,
MessageId = 0,
ChannelId = 0,
ServerId = serverId,
DateTime = DateTime.UtcNow,
Message = message
};
await this.Events.LogEntryAdded(logEntry);
}
public async Task LogException(Exception exception, CommandArguments args) =>
await LogException(exception, "--Command: "+ args.Command.Id + " | Parameters: " + args.TrimmedMessage, args.Server.Id);
public async Task LogException(Exception exception, string data, guid serverId = 0)
{
if( (exception is HttpException httpException && (int)httpException.HttpCode >= 500) || data.Contains("Error handling Dispatch") )
{
this.Monitoring.Error500s.Inc();
}
if( (exception is WebSocketClosedException websocketException) )
{
data += $"\nCloseCode:{websocketException.CloseCode}\nReason:{websocketException.Reason}\nTarget:{websocketException.TargetSite}";
}
if( exception.Message == "Server requested a reconnect" ||
exception.Message == "Server missed last heartbeat" ||
exception.Message.Contains("Discord.PermissionTarget") ) //it's a spam
return;
Console.WriteLine($"{exception.GetType()}: {exception.Message}");
Console.WriteLine(exception.StackTrace);
Console.WriteLine($"{data} | ServerId:{serverId}");
if( exception is RateLimitedException || exception.Message.Contains("WebSocket connection was closed") ) //hack to not spam my logs
return;
if( this.Events != null )
{
ExceptionEntry exceptionEntry = new ExceptionEntry(){
Type = exception.GetType().ToString(),
Message = exception.Message,
Stack = exception.StackTrace,
Data = data,
DateTime = DateTime.UtcNow,
ServerId = serverId,
ShardId = this.CurrentShard?.Id ?? 0
};
await this.Events.Exception(exceptionEntry);
}
if( exception.InnerException != null && exception.Message != exception.InnerException.Message )
await LogException(exception.InnerException, "InnerException | " + data, serverId);
}
public List<UserData> GetMentionedUsersData(ServerContext dbContext, CommandArguments e) //todo - Move this elsewhere...
{
List<guid> mentionedUserIds = GetMentionedUserIds(e);
if( !mentionedUserIds.Any() )
return new List<UserData>();
List<UserData> found = dbContext.UserDatabase.AsQueryable().Where(u => u.ServerId == e.Server.Id).AsEnumerable().Where(u => mentionedUserIds.Contains(u.UserId)).ToList();
if( found.Count < mentionedUserIds.Count )
{
for( int i = 0; i < mentionedUserIds.Count; i++ )
{
if(found.Any(u => u.UserId == mentionedUserIds[i]))
continue;
UserData newUserData = new UserData(){
ServerId = e.Server.Id,
UserId = mentionedUserIds[i]
};
dbContext.UserDatabase.Add(newUserData); //No need to save this here.
dbContext.SaveChanges();
found.Add(newUserData);
}
}
return found;
}
public Task<List<IGuildUser>> GetMentionedGuildUsers(CommandArguments e) //todo - Move this elsewhere...
{
return GetMentionedGuildUsers(e.Server, e.MessageArgs);
}
public async Task<List<IGuildUser>> GetMentionedGuildUsers(Server server, string[] messageArgs) //todo - Move this elsewhere...
{
if( messageArgs == null || messageArgs.Length == 0 )
return new List<IGuildUser>();
List<IGuildUser> mentionedUsers = new List<IGuildUser>();
for( int i = 0; i < messageArgs.Length; i++ )
{
guid id;
if( !guid.TryParse(messageArgs[i].Trim('<','@','!','>'), out id) || id == 0 )
break;
IGuildUser user = server.Guild.GetUser(id);
if( user == null )
user = await this.DiscordClient.Rest.GetGuildUserAsync(server.Id, id);
if( user == null )
continue;
if( mentionedUsers.Contains(user) )
{
List<string> newArgs = new List<string>(messageArgs);
newArgs.RemoveAt(i);
messageArgs = newArgs.ToArray();
continue;
}
mentionedUsers.Add(user);
}
return mentionedUsers;
}
public List<guid> GetMentionedUserIds(CommandArguments e, bool endOnFailure = true) //todo - Move this elsewhere...
{
List<guid> mentionedIds = new List<guid>();
/*if( e.Message.MentionedUsers != null && e.Message.MentionedUsers.Any() )
{
mentionedIds.AddRange(e.Message.MentionedUsers.Select(u => u.Id));
}
else*/ if( e.MessageArgs != null && e.MessageArgs.Length > 0 )
{
for( int i = 0; i < e.MessageArgs.Length; i++)
{
guid id;
if( !guid.TryParse(e.MessageArgs[i].Trim('<','@','!','>'), out id) || id < int.MaxValue )
if( endOnFailure ) break;
else continue;
if( mentionedIds.Contains(id) )
{
//This code is necessary to be able to further parse arguments by some commands (e.g. ban reason)
List<string> newArgs = new List<string>(e.MessageArgs);
newArgs.RemoveAt(i--);
e.MessageArgs = newArgs.ToArray();
continue;
}
mentionedIds.Add(id);
}
}
return mentionedIds;
}
private string GetPatchnotes()
{
if( !Directory.Exists("updates") || !File.Exists(Path.Combine("updates", "changelog")) )
return "This is not the original <https://valkyrja.app>, therefor I can not tell you, what's new here :<";
string changelog = File.ReadAllText(Path.Combine("updates", "changelog"));
int start = changelog.IndexOf("**Valkyrja");
int valkEnd = changelog.Substring(start+1).IndexOf("**Valkyrja") + 1;
int bwEnd = changelog.Substring(start+1).IndexOf("**Valkyrja") + 1;
int end = valkEnd > start ? valkEnd : bwEnd;
int hLength = valkEnd > start ? "**Valkyrja".Length : "**Valkyrja".Length;
if( start >= 0 && end <= changelog.Length && end > start && (changelog = changelog.Substring(start, end-start+hLength)).Length > 0 )
return changelog + "\n\nSee the full changelog and upcoming features at <https://valkyrja.app/updates>!";
return "There is an error in the data so I have failed to retrieve the patchnotes. Sorry mastah!";
}
public async Task<PmErrorCode> SendPmSafe(IUser user, string message, Embed embed = null)
{
if( user == null )
return PmErrorCode.UserNull;
if( this.FailedPmCount.ContainsKey(user.Id) && this.FailedPmCount[user.Id] >= 3 )
return PmErrorCode.ThresholdExceeded;
try
{
await user.SendMessageSafe(message, embed);
return PmErrorCode.Success;
}
catch( HttpException e ) when( (int)e.HttpCode == 403 || (e.DiscordCode.HasValue && e.DiscordCode == DiscordErrorCode.CannotSendMessageToUser) || e.Message.Contains("50007") )
{
if( !this.FailedPmCount.ContainsKey(user.Id) )
this.FailedPmCount.Add(user.Id, 0);
this.FailedPmCount[user.Id]++;
return PmErrorCode.Failed;
}
catch( HttpException e ) when( (int)e.HttpCode >= 500 )
{
this.Monitoring.Error500s.Inc();
return PmErrorCode.Thrown500;
}
catch( Exception e )
{
await LogException(e, "Unknown PM error.", 0);
return PmErrorCode.Unknown;
}
}
private string GetStatusString(TimeSpan latency, Server server)
{
string cpuLoad = Bash.Run("grep 'cpu ' /proc/stat | awk '{print ($2+$4)*100/($2+$4+$5)}'");
string memoryUsed = Bash.Run("free | grep Mem | awk '{print $3/$2 * 100.0}'");
double memoryPercentage = double.Parse(memoryUsed);
string[] temp = Bash.Run("sensors | egrep '(temp1|Tdie|Tctl)' | awk '{print $2}'").Split('\n');
string subscription = IsPartner(server.Id) ? "Partner " : (IsSubscriber(server.Guild.OwnerId) ? "Subscriber" : "");
return "Service Status: <https://status.valkyrja.app>\n" +
$"```md\n" +
$"[ Memory usage ][ {memoryPercentage:#00.00} % ({memoryPercentage / 100 * 128:000.00}/128 GB) ]\n" +
$"[ CPU Load ][ {double.Parse(cpuLoad):#00.00} % ({temp[1]}) ]\n" +
$"[ Shard ID ][ {this.CurrentShard.Id - 1:00} ]\n" +
$"[ Subscription ][ {subscription} ]\n" +
$"```\n" +
$"<:ValkThink:535541641507897354> `{latency.TotalMilliseconds:#00}`ms <:ValkyrjaNomBlob:509485197763543050>";
}
public async Task SendEmbedFromCli(CommandArguments cmdArgs, IUser pmInstead = null)
{
if( string.IsNullOrEmpty(cmdArgs.TrimmedMessage) || cmdArgs.TrimmedMessage == "-h" || cmdArgs.TrimmedMessage == "--help" )
{
await cmdArgs.SendReplySafe("```md\nCreate an embed using the following parameters:\n" +
"[ --channel ] Channel where to send the embed.\n" +
"[ --edit <msgId>] Replace a MessageId with a new embed (use after --channel)\n" +
"[ --text ] Regular content text\n" +
"[ --title ] Title\n" +
"[ --description ] Description\n" +
"[ --footer ] Footer\n" +
"[ --color ] #rrggbb hex color used for the embed stripe.\n" +
"[ --image ] URL of a Hjuge image in the bottom.\n" +
"[ --thumbnail ] URL of a smol image on the side.\n" +
"[ --fieldName ] Create a new field with specified name.\n" +
"[ --fieldValue ] Text value of a field - has to follow a name.\n" +
"[ --fieldInline ] Use to set the field as inline.\n" +
"[ --reactions ] Adds emotes as reactions.\n" +
"Where you can repeat the field* options multiple times.\n```"
);
return;
}
SocketTextChannel channel = null;
bool debug = false;
string text = null;
IMessage msg = null;
EmbedFieldBuilder currentField = null;
EmbedBuilder embedBuilder = new EmbedBuilder();
List<IEmote> emotes = new List<IEmote>();
foreach( Match match in this.RegexCliParam.Matches(cmdArgs.TrimmedMessage) )
{
string matchValue = this.RegexCliEscape.Replace(match.Value, "");
string optionString = this.RegexCliOption.Match(matchValue).Value;
if( optionString == "--debug" )
{
if( IsGlobalAdmin(cmdArgs.Message.Author.Id) || IsSupportTeam(cmdArgs.Message.Author.Id) )
debug = true;
continue;
}
if( optionString == "--fieldInline" )
{
if( currentField == null )
{
await cmdArgs.SendReplySafe($"`fieldInline` can not precede `fieldName`.");
return;
}
currentField.WithIsInline(true);
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Setting inline for field `{currentField.Name}`");
continue;
}
string value;
if( matchValue.Length <= optionString.Length || string.IsNullOrWhiteSpace(value = matchValue.Substring(optionString.Length + 1).Trim()) )
{
await cmdArgs.SendReplySafe($"Invalid value for `{optionString}`");
return;
}
if( value.Length >= UserProfileOption.ValueCharacterLimit )
{
await cmdArgs.SendReplySafe($"`{optionString}` is too long! (It's {value.Length} characters while the limit is {UserProfileOption.ValueCharacterLimit})");
return;
}
switch( optionString )
{
case "--channel":
if( !guid.TryParse(value.Trim('<', '>', '#'), out guid id) || (channel = cmdArgs.Server.Guild.GetTextChannel(id)) == null )
{
await cmdArgs.SendReplySafe($"Channel {value} not found.");
return;
}
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Channel set: `{channel.Name}`");
break;
case "--text":
if( value.Length > GlobalConfig.MessageCharacterLimit )
{
await cmdArgs.SendReplySafe($"`--text` is too long (`{value.Length} > {GlobalConfig.MessageCharacterLimit}`)");
return;
}
text = value;
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Text set: `{value}`");
break;
case "--title":
if( value.Length > 256 )
{
await cmdArgs.SendReplySafe($"`--title` is too long (`{value.Length} > 256`)");
return;
}
embedBuilder.WithTitle(value);
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Title set: `{value}`");
break;
case "--description":
if( value.Length > 2048 )
{
await cmdArgs.SendReplySafe($"`--description` is too long (`{value.Length} > 2048`)");
return;
}
embedBuilder.WithDescription(value);
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Description set: `{value}`");
break;
case "--footer":
if( value.Length > 2048 )
{
await cmdArgs.SendReplySafe($"`--footer` is too long (`{value.Length} > 2048`)");
return;
}
embedBuilder.WithFooter(value);
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Description set: `{value}`");
break;
case "--image":
try
{
embedBuilder.WithImageUrl(value.Trim('<', '>'));
}
catch( Exception )
{
await cmdArgs.SendReplySafe($"`--image` is invalid url");
return;
}
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Image URL set: `{value}`");
break;
case "--thumbnail":
try
{
embedBuilder.WithThumbnailUrl(value.Trim('<', '>'));
}
catch( Exception )
{
await cmdArgs.SendReplySafe($"`--thumbnail` is invalid url");
return;
}
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Thumbnail URL set: `{value}`");
break;
case "--color":
try
{
uint color = uint.Parse(value.TrimStart('#'), System.Globalization.NumberStyles.AllowHexSpecifier);
if( color > uint.Parse("FFFFFF", System.Globalization.NumberStyles.AllowHexSpecifier) )
{
await cmdArgs.SendReplySafe("Color out of range.");
return;
}
embedBuilder.WithColor(color);
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Color `{value}` set.");
}
catch( Exception )
{
await cmdArgs.SendReplySafe("Invalid color format.");
return;
}
break;
case "--fieldName":
if( value.Length > 256 )
{
await cmdArgs.SendReplySafe($"`--fieldName` is too long (`{value.Length} > 256`)\n```\n{value}\n```");
return;
}
if( currentField != null && currentField.Value == null )
{
await cmdArgs.SendReplySafe($"Field `{currentField.Name}` is missing a value!");
return;
}
if( embedBuilder.Fields.Count >= 25 )
{
await cmdArgs.SendReplySafe("Too many fields! (Limit is 25)");
return;
}
embedBuilder.AddField(currentField = new EmbedFieldBuilder().WithName(value));
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Creating new field `{currentField.Name}`");
break;
case "--fieldValue":
if( value.Length > 1024 )
{
await cmdArgs.SendReplySafe($"`--fieldValue` is too long (`{value.Length} > 1024`)\n```\n{value}\n```");
return;
}
if( currentField == null )
{
await cmdArgs.SendReplySafe($"`fieldValue` can not precede `fieldName`.");
return;
}
currentField.WithValue(value);
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Setting value:\n```\n{value}\n```\n...for field:`{currentField.Name}`");
break;
case "--reactions":
MatchCollection words = this.RegexCommandParams.Matches(value);
foreach( Match word in words )
{
if( Emote.TryParse(word.Value, out Emote emote) )
emotes.Add(emote);
else
emotes.Add(new Emoji(word.Value));
}
if( debug )
await cmdArgs.Channel.SendMessageSafe($"Adding emoji reactions:\n```\n{value}\n```");
break;
case "--edit":
if( !guid.TryParse(value, out guid msgId) || (msg = await channel?.GetMessageAsync(msgId)) == null )
{
await cmdArgs.SendReplySafe($"`--edit` did not find a message with ID `{value}` in the <#{(channel?.Id ?? 0)}> channel.");
return;
}
break;
default:
await cmdArgs.SendReplySafe($"Unknown option: `{optionString}`");
return;
}
}
if( currentField != null && currentField.Value == null )
{
await cmdArgs.SendReplySafe($"Field `{currentField.Name}` is missing a value!");
return;
}
switch( msg )
{
case null:
if( pmInstead != null )
msg = await pmInstead.SendMessageAsync(text: text, embed: embedBuilder.Build());
else if( channel == null )
msg = await cmdArgs.SendReplySafe(text: text, embed: embedBuilder.Build());
else
msg = await channel.SendMessageAsync(text: text, embed: embedBuilder.Build());
try
{
foreach( IEmote emote in emotes )
{
await msg.AddReactionAsync(emote);
}
}
catch( Exception )
{
await cmdArgs.SendReplySafe("Failed to add the Emoji Reactions.");
}
break;
case RestUserMessage message:
await message?.ModifyAsync(m => {
m.Content = text;
m.Embed = embedBuilder.Build();
});
break;
case SocketUserMessage message:
await message?.ModifyAsync(m => {
m.Content = text;
m.Embed = embedBuilder.Build();
});
break;
default:
await cmdArgs.SendReplySafe("GetMessage went bork.");
break;
}
}
}
}