This repository was archived by the owner on Jan 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommandLock.cs
More file actions
59 lines (52 loc) · 1.92 KB
/
CommandLock.cs
File metadata and controls
59 lines (52 loc) · 1.92 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
using DSharpPlus.CommandsNext;
using Palantir.PalantirCommandModule;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Palantir
{
internal class CommandLock
{
ConcurrentDictionary<string, ConcurrentDictionary<ulong, bool>> commandLocks = new();
public void LockCommand(CommandContext ctx)
{
var isSynchronized = ctx.Command.ExecutionChecks.Any(check => check is SynchronizedAttribute);
if (isSynchronized)
{
var commandName = ctx.Command.Name;
var userId = ctx.User.Id;
var lockedUsers = commandLocks.GetOrAdd(commandName, new ConcurrentDictionary<ulong, bool>());
var userIsLocked = false;
lockedUsers.AddOrUpdate(userId, true, (key, value) => {
userIsLocked = value;
return true;
});
if (userIsLocked)
{
throw new TaskCanceledException("User <@" + userId + "> is already executing the command `" + commandName + "`.");
}
}
}
public void UnlockCommand(CommandContext ctx)
{
var isSynchronized = ctx.Command.ExecutionChecks.Any(check => check is SynchronizedAttribute);
if (isSynchronized)
{
var commandName = ctx.Command.Name;
var userId = ctx.User.Id;
var lockedUsers = commandLocks[commandName];
if (lockedUsers != null)
{
lockedUsers.Remove(userId, out var removedUser);
//if(lockedUsers.IsEmpty)
//{
// commandLocks.Remove(commandName, out var removedCommand);
//}
}
}
}
}
}