geekbot/Geekbot.net/Commands/ContextHandler.cs

97 lines
No EOL
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace Geekbot.net.Commands
{
public class ContextHandler : IContextHandler
{
private Dictionary<ulong, ContextStore> _store;
private readonly IDiscordClient _client;
private readonly CommandService _commandService;
private readonly IServiceProvider _servicesProvider;
public ContextHandler(IDiscordClient client, CommandService commandService, IServiceProvider servicesProvider)
{
_store = new Dictionary<ulong, ContextStore>();
_commandService = commandService;
_servicesProvider = servicesProvider;
_client = client;
}
public ContextReference HasContext(IUserMessage message)
{
if (_store.ContainsKey(message.Author.Id)) return ContextReference.User;
if (_store.ContainsKey(message.Channel.Id)) return ContextReference.Channel;
return ContextReference.None;
}
public void SaveContext(ContextReference type, ICommandContext context, string commandName)
{
var contextStore = new ContextStore()
{
CommandName = commandName
};
var id = GetId(type, context.Message);
_store.Add(id, contextStore);
}
public async void ExecuteOnContext(ContextReference type, IUserMessage message)
{
var id = GetId(type, message);
var obj = _store[id];
var context = new CommandContext(_client, message);
var rest = await _commandService.ExecuteAsync(context, $"{obj.CommandSearch} {context.Message?.Content}", _servicesProvider);
if (!rest.IsSuccess)
{
await context.Channel.SendMessageAsync(rest.ErrorReason);
}
}
public void ClearContext(ulong id)
{
_store.Remove(id);
}
private ulong GetId(ContextReference type, IUserMessage message)
{
if (type == ContextReference.Channel)
{
return message.Author.Id;
}
if (type == ContextReference.User)
{
return message.Author.Id;
}
throw new Exception("No Context Object Found");
}
private class ContextStore
{
public string CommandName { get; set; }
public string CommandSearch => $"{CommandName} ctx";
}
}
public enum ContextReference
{
User,
Channel,
None
}
public interface IContextHandler
{
ContextReference HasContext(IUserMessage message);
void SaveContext(ContextReference type, ICommandContext context, string commandName);
void ExecuteOnContext(ContextReference type, IUserMessage message);
void ClearContext(ulong id);
}
}