-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCommandHandler.cs
72 lines (63 loc) · 2.09 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
71
72
using System;
using System.Reflection;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace TheGuide
{
public class CommandHandler
{
public static char CharPrefix = '?';
public CommandService Service;
private DiscordSocketClient _client;
private IDependencyMap _map;
public async Task Install(IDependencyMap map)
{
// Create Command Service, inject it into Dependency Map
_client = map.Get<DiscordSocketClient>();
_map = map;
// Creating a CommandServiceConfig is far from required here, just added it for completion's sake
Service =
new CommandService(new CommandServiceConfig
{
CaseSensitiveCommands = false,
DefaultRunMode = RunMode.Async,
LogLevel = LogSeverity.Verbose
});
Service.Log += ServiceLog;
// Finds modules in our assembly and adds them to our command service
await Service.AddModulesAsync(Assembly.GetEntryAssembly());
_client.MessageReceived += HandleCommand;
}
private Task ServiceLog(LogMessage arg)
{
if (arg.Exception != null)
{
Console.WriteLine(arg.Exception.ToString());
}
return Task.CompletedTask;
}
public async Task HandleCommand(SocketMessage parameterMessage)
{
// Don't handle the command if it is a system message
var message = parameterMessage as SocketUserMessage;
// Mark where the prefix ends and the command begins
int argPos = 0;
// Determine if the message has a valid prefix, adjust argPos
if (message == null
|| message.Author is IWebhookUser
|| message.Author.IsBot
|| !(message.HasMentionPrefix(_client.CurrentUser, ref argPos)
|| message.HasCharPrefix(CharPrefix, ref argPos)))
return;
// Create a Socket Command Context
var context = new SocketCommandContext(_client, message);
// Execute the Command, store the result
var result = await Service.ExecuteAsync(context, argPos, _map, MultiMatchHandling.Exception);
// If the command failed, notify the user
if (!result.IsSuccess)
await message.Channel.SendMessageAsync($"{Format.Bold("Error:")} {result.ErrorReason}");
}
}
}