forked from Sehelitar/Kick.bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBotChatCommander.cs
402 lines (346 loc) · 18.2 KB
/
BotChatCommander.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
/*
Copyright (C) 2023-2024 Sehelitar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using Kick.Models.Events;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using static Kick.Bot.BotClient;
using System.Linq;
using LiteDB;
namespace Kick.Bot
{
internal static class BotChatCommander
{
private static List<BotChatCommand> commands = new List<BotChatCommand>();
public static void ReloadCommands()
{
CPH.LogVerbose($"[Kick] Commands reloaded.");
var oldCommands = commands;
var newCommands = new List<BotChatCommand>();
foreach(StreamerBotCommand botCommand in StreamerBotAppSettings.Commands)
{
var oldMatchRequest = from oldCommand in oldCommands where oldCommand.CommandInfo.Id == botCommand.Id select oldCommand;
if (oldMatchRequest.Count() > 0)
{
var oldChatCommand = oldMatchRequest.First();
oldChatCommand.CommandInfo = botCommand;
newCommands.Add(oldChatCommand);
CPH.LogVerbose($"[Kick] Command updated : {botCommand.Command} (Id={botCommand.Id})");
}
else
{
var bcc = new BotChatCommand()
{
CommandInfo = botCommand
};
newCommands.Add(bcc);
CPH.LogVerbose($"[Kick] Command added : {botCommand.Command} (Id={botCommand.Id})");
}
CPH.RegisterCustomTrigger($"[Kick] {botCommand.Name} ({botCommand.Command.Replace("\r\n", ", ")})", $"kickChatCommand.{botCommand.Id}", new string[] { "Kick", "Commands" });
CPH.RegisterCustomTrigger($"[Kick] {botCommand.Name} [Cooldown] ({botCommand.Command.Replace("\r\n", ", ")})", $"kickChatCommandCooldown.{botCommand.Id}", new string[] { "Kick", "Commands" });
}
commands = newCommands;
CPH.LogVerbose($"[Kick] {commands.Count} commands loaded");
}
public static bool Evaluate(ChatMessageEvent chatMessageEvent)
{
var isCommand = false;
foreach (BotChatCommand botCommand in commands)
{
if (!botCommand.CommandInfo.Enabled)
continue;
/* Vérification de la commande saisie */
bool textCommandMatch = false;
string inputCommand = null;
string[] inputStrings = null;
switch (botCommand.CommandInfo.Mode)
{
// Matching Basic
case 0:
var textCommands = botCommand.CommandInfo.Command.Replace("\r\n", "\n").Split('\n');
foreach (var textCommand in textCommands)
{
var command = textCommand;
// Si le texte de la commande est vide, on ignore
if (command.Length < 2)
continue;
switch (botCommand.CommandInfo.Location)
{
// Début de phrase
case 0:
if (chatMessageEvent.Content.StartsWith(command, botCommand.CommandInfo.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase))
{
textCommandMatch = true;
inputCommand = command;
inputStrings = chatMessageEvent.Content.Substring(command.Length).Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
break;
// Correspondance exacte
case 1:
if (String.Compare(chatMessageEvent.Content, command, botCommand.CommandInfo.CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) == 0)
{
textCommandMatch = true;
inputCommand = chatMessageEvent.Content.Trim();
inputStrings = chatMessageEvent.Content.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
break;
// N'importe où dans la chaine
case 2:
if (botCommand.CommandInfo.CaseSensitive ?
chatMessageEvent.Content.Contains(command) :
chatMessageEvent.Content.ToLower().Contains(command.ToLower()))
{
textCommandMatch = true;
inputCommand = command.Trim();
inputStrings = chatMessageEvent.Content.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
break;
}
// Si ça a matché, pas besoin de tester les autres lignes de texte
if (textCommandMatch)
break;
}
break;
// Matching Regex
case 1:
var regex = new Regex(botCommand.CommandInfo.Command);
textCommandMatch = regex.IsMatch(chatMessageEvent.Content);
inputCommand = botCommand.CommandInfo.Command;
inputStrings = chatMessageEvent.Content.Split(' ');
break;
// Matching Inconnu, on passe à la commande suivante
default: continue;
}
// La commande ne correspond pas, on passe à la suivante
if (!textCommandMatch)
continue;
var rawInput = String.Join(" ", inputStrings);
/* Vérification de la liste des accès */
bool deniedCheck = botCommand.CommandInfo.GrantType == 1;
bool userPermitted = botCommand.CommandInfo.PermittedGroups.Count == 0 ^ deniedCheck;
if (botCommand.CommandInfo.PermittedGroups.Count > 0)
{
var groupMatch = (botCommand.CommandInfo.PermittedGroups.Contains("Moderators") && chatMessageEvent.Sender.IsModerator) ||
(botCommand.CommandInfo.PermittedGroups.Contains("VIPs") && chatMessageEvent.Sender.IsVIP) ||
(botCommand.CommandInfo.PermittedGroups.Contains("Subscribers") && chatMessageEvent.Sender.IsSubscriber);
userPermitted = groupMatch ^ deniedCheck;
}
// Le streamer a tous les droits :)
if (chatMessageEvent.Sender.IsBroadcaster)
userPermitted = true;
// Si l'utilisateur n'est pas autorisé à utiliser cette commande, on passe à la suivante
if (!userPermitted)
{
CPH.LogDebug($"[Kick] Command access denied. Caster={chatMessageEvent.Sender.IsBroadcaster} Mod={chatMessageEvent.Sender.IsModerator} VIP={chatMessageEvent.Sender.IsVIP} OG={chatMessageEvent.Sender.IsOG} Sub={chatMessageEvent.Sender.IsSubscriber}");
continue;
}
CPH.LogVerbose($"[Kick] Command detected! {botCommand.CommandInfo.Command}");
/* Vérification des cooldowns */
bool onCooldown = false;
double globalRem = 0;
double userRem = 0;
if (botCommand.CommandInfo.UserCooldown > 0)
{
if (botCommand.UsersLastExec.TryGetValue(chatMessageEvent.Sender.Id, out var userLastExec) && (userRem = DateTime.Now.Subtract(userLastExec).TotalSeconds) < botCommand.CommandInfo.UserCooldown)
{
onCooldown = true;
userRem = botCommand.CommandInfo.UserCooldown - userRem;
}
else
{
botCommand.UsersLastExec[chatMessageEvent.Sender.Id] = DateTime.Now;
}
}
if (botCommand.CommandInfo.GlobalCooldown > 0)
{
if (botCommand.LastExec.HasValue && (globalRem = DateTime.Now.Subtract(botCommand.LastExec.Value).TotalSeconds) < botCommand.CommandInfo.GlobalCooldown)
{
onCooldown = true;
globalRem = botCommand.CommandInfo.GlobalCooldown - globalRem;
}
else
{
botCommand.LastExec = DateTime.Now;
}
}
int role = 1;
if (chatMessageEvent.Sender.IsVIP)
role = 2;
if (chatMessageEvent.Sender.IsModerator)
role = 3;
if (chatMessageEvent.Sender.IsBroadcaster)
role = 4;
if (onCooldown)
{
// Cooldown actif
var cdArguments = new Dictionary<string, object>() {
{ "command", inputCommand },
{ "commandId", botCommand.CommandInfo.Id },
{ "commandSource", "kick" },
{ "commandType", "message" },
{ "user", chatMessageEvent.Sender.Username },
{ "userName", chatMessageEvent.Sender.Slug },
{ "userId", chatMessageEvent.Sender.Id },
{ "userType", "kick" },
{ "isSubscribed", chatMessageEvent.Sender.IsSubscriber },
{ "isModerator", chatMessageEvent.Sender.IsModerator },
{ "isVip", chatMessageEvent.Sender.IsVIP },
{ "eventSource", "kick" },
{ "cooldownLeft", Convert.ToInt64(Math.Max(globalRem, userRem)) },
{ "globalCooldownLeft", Convert.ToInt64(globalRem) },
{ "userCooldownLeft", Convert.ToInt64(userRem) },
{ "fromKick", true }
};
CPH.TriggerCodeEvent($"kickChatCommandCooldown.{botCommand.CommandInfo.Id}", cdArguments);
CPH.TriggerCodeEvent(BotEventListener.BotEventType.ChatCommandCooldown, cdArguments);
isCommand = true;
continue;
}
/* Incrémentation des compteurs */
var globalCurrentCounter = 0L;
var userCurrentCounter = 0L;
using (var globalCounter = CommandCounter.GlobalCounterForCommand(botCommand.CommandInfo.Id, botCommand.CommandInfo.PersistCounter))
{
globalCurrentCounter = ++globalCounter.Counter;
}
using (var userCounter = CommandCounter.CounterForCommandUser(botCommand.CommandInfo.Id, chatMessageEvent.Sender.Id, botCommand.CommandInfo.PersistUserCounter))
{
userCurrentCounter = ++userCounter.Counter;
}
// Fini ! Si on arrive là, c'est que la commande est valide, on peut la lancer
var arguments = new Dictionary<string, object>() {
{ "command", inputCommand },
{ "commandId", botCommand.CommandInfo.Id },
{ "commandSource", "kick" },
{ "commandType", "message" },
{ "rawInput", rawInput },
{ "rawInputEscaped", rawInput },
{ "rawInputUrlEncoded", System.Net.WebUtility.UrlEncode(rawInput) },
{ "user", chatMessageEvent.Sender.Username },
{ "userName", chatMessageEvent.Sender.Slug },
{ "userId", chatMessageEvent.Sender.Id },
{ "userType", "kick" },
{ "isSubscribed", chatMessageEvent.Sender.IsSubscriber },
{ "isModerator", chatMessageEvent.Sender.IsModerator },
{ "isVip", chatMessageEvent.Sender.IsVIP },
{ "eventSource", "command" },
{ "msgId", chatMessageEvent.Id },
{ "chatroomId", chatMessageEvent.ChatroomId },
{ "role", role },
{ "counter", globalCurrentCounter },
{ "userCounter", userCurrentCounter },
{ "fromKick", true }
};
for(int i = 0; i < inputStrings.Length; ++i)
{
arguments.Add($"input{i}", inputStrings[i]);
arguments.Add($"inputEscaped{i}", inputStrings[i]);
arguments.Add($"inputUrlEncoded{i}", System.Net.WebUtility.UrlEncode(inputStrings[i]));
}
CPH.TriggerCodeEvent($"kickChatCommand.{botCommand.CommandInfo.Id}", arguments);
CPH.TriggerCodeEvent(BotEventListener.BotEventType.ChatCommand, arguments);
isCommand = true;
}
return isCommand;
}
}
internal class BotChatCommand
{
public StreamerBotCommand CommandInfo;
public DateTime? LastExec = null;
public Dictionary<long, DateTime> UsersLastExec = new Dictionary<long, DateTime>();
}
internal class CommandCounter : IDisposable
{
internal const string PersistentCollection = "counters";
internal const string VolatileCollection = "counters_tmp";
[BsonId]
public long Id { get; set; }
public string CommandId { get; set; } = null;
public long? UserId { get; set; } = null;
public long Counter { get; set; } = 0;
[BsonIgnore]
public bool Persist { get; set; } = true;
public void Dispose()
{
try
{
using (var database = new LiteDatabase(@"data\kick-ext.db"))
{
var dbCollection = database.GetCollection<CommandCounter>(Persist ? PersistentCollection : VolatileCollection, BsonAutoId.Int64);
dbCollection.Upsert(this);
dbCollection.EnsureIndex("ByCommand", x => x.CommandId, false);
dbCollection.EnsureIndex("ByUser", x => x.UserId, false);
dbCollection.EnsureIndex("ByKey", BsonExpression.Create("{Command:$.CommandId,User:$.UserId}"), true);
}
}
catch (Exception) {}
}
public static CommandCounter GlobalCounterForCommand(string commandId, bool persist = true)
{
try
{
using (var database = new LiteDatabase(@"data\kick-ext.db"))
{
var dbCollection = database.GetCollection<CommandCounter>(persist ? PersistentCollection : VolatileCollection, BsonAutoId.Int64);
var counterQuery = from counterObject in dbCollection.Query()
where counterObject.CommandId == commandId &&counterObject.UserId == null
select counterObject;
var result = counterQuery.FirstOrDefault() ?? new CommandCounter() { CommandId = commandId, Persist = persist };
result.Persist = persist;
return result;
}
}
catch (Exception)
{
var result = new CommandCounter() { CommandId = commandId, Persist = persist };
result.Persist = persist;
return result;
}
}
public static CommandCounter CounterForCommandUser(string commandId, long userId, bool persist = true)
{
try
{
using (var database = new LiteDatabase(@"data\kick-ext.db"))
{
var dbCollection = database.GetCollection<CommandCounter>(persist ? PersistentCollection : VolatileCollection, BsonAutoId.Int64);
var counterQuery = from counterObject in dbCollection.Query()
where counterObject.CommandId == commandId && counterObject.UserId == userId
select counterObject;
var result = counterQuery.FirstOrDefault() ?? new CommandCounter() { CommandId = commandId, UserId = userId, Persist = persist };
result.Persist = persist;
return result;
}
}
catch (Exception)
{
var result = new CommandCounter() { CommandId = commandId, UserId = userId, Persist = persist };
result.Persist = persist;
return result;
}
}
public static void PruneVolatile()
{
try
{
using (var database = new LiteDatabase(@"data\kick-ext.db"))
{
database.DropCollection(VolatileCollection);
}
}
catch (Exception) { }
}
}
}