/
CommandHandler.cs
70 lines (63 loc) · 2.49 KB
/
CommandHandler.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
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Reflection;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.Extensions.DependencyInjection;
using StatusBot.Services;
using StatusBot.TypeReaders;
namespace StatusBot
{
public class CommandHandler
{
private CommandService C;
private DiscordSocketClient client;
private IServiceProvider ISP;
private LogService LS;
Stopwatch T = new Stopwatch();
void SWatchStart()
=> T = Stopwatch.StartNew();
void SWatchStop()
=> T.Stop();
public CommandHandler(IServiceProvider provider)
{
ISP = provider;
client = ISP.GetService<DiscordSocketClient>();
client.MessageReceived += HandleCommand;
C = ISP.GetService<CommandService>();
LS = ISP.GetService<LogService>();
}
public async Task ConfigureAsync()
{
C.AddTypeReader(typeof(ChronoString), new ChronoStringTypeReader());
await C.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), services: ISP);
}
public async Task HandleCommand(SocketMessage parameterMessage)
{
SWatchStart();
var ch = parameterMessage.Channel as IGuildChannel;
var G = ch.Guild as IGuild;
//Prevent commands triggered by itself or other bots
if (!(parameterMessage is SocketUserMessage message) || message.Author.IsBot) return;
int argPos = 0;
if (!(message.HasMentionPrefix(client.CurrentUser, ref argPos) || message.HasStringPrefix("s]", ref argPos))) return;
var context = new SocketCommandContext(client, message);
var result = await C.ExecuteAsync(context, argPos, ISP);
//Command success/fail notice message
if (result.IsSuccess)
{
SWatchStop();
await LS.WriteAsync($"Command finished in {T.Elapsed.TotalSeconds.ToString("F3")} seconds", ConsoleColor.DarkMagenta);
}
else
{
//Prevents unknown command exception to be posted as an error message in discord
if (result.Error.Value != CommandError.UnknownCommand)
await message.Channel.SendMessageAsync(result.ToString());
await LS.WriteErrorAsync($"{result}\n{result.ErrorReason}", ConsoleColor.DarkRed);
}
}
}
}