2017-07-17 19:42:36 +00:00
|
|
|
|
using System;
|
2017-05-29 04:13:22 +00:00
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Discord;
|
|
|
|
|
using Discord.WebSocket;
|
2017-07-17 19:42:36 +00:00
|
|
|
|
using NadekoBot.Common.ModuleBehaviors;
|
|
|
|
|
using NadekoBot.Modules.Games.Common;
|
2017-10-13 04:14:54 +00:00
|
|
|
|
using NadekoBot.Core.Services;
|
|
|
|
|
using NadekoBot.Core.Services.Impl;
|
2017-05-29 04:13:22 +00:00
|
|
|
|
using NLog;
|
|
|
|
|
|
2017-07-17 19:42:36 +00:00
|
|
|
|
namespace NadekoBot.Modules.Games.Services
|
2017-05-29 04:13:22 +00:00
|
|
|
|
{
|
2017-07-15 03:04:16 +00:00
|
|
|
|
public class PollService : IEarlyBlockingExecutor, INService
|
2017-05-29 04:13:22 +00:00
|
|
|
|
{
|
|
|
|
|
public ConcurrentDictionary<ulong, Poll> ActivePolls = new ConcurrentDictionary<ulong, Poll>();
|
|
|
|
|
private readonly Logger _log;
|
2017-06-19 13:42:10 +00:00
|
|
|
|
private readonly DiscordSocketClient _client;
|
2017-05-29 04:13:22 +00:00
|
|
|
|
private readonly NadekoStrings _strings;
|
|
|
|
|
|
2017-06-19 13:42:10 +00:00
|
|
|
|
public PollService(DiscordSocketClient client, NadekoStrings strings)
|
2017-05-29 04:13:22 +00:00
|
|
|
|
{
|
|
|
|
|
_log = LogManager.GetCurrentClassLogger();
|
|
|
|
|
_client = client;
|
|
|
|
|
_strings = strings;
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-24 05:23:59 +00:00
|
|
|
|
public async Task<bool?> StartPoll(ITextChannel channel, IUserMessage msg, string arg)
|
2017-05-29 04:13:22 +00:00
|
|
|
|
{
|
|
|
|
|
if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";"))
|
|
|
|
|
return null;
|
|
|
|
|
var data = arg.Split(';');
|
|
|
|
|
if (data.Length < 3)
|
|
|
|
|
return null;
|
|
|
|
|
|
2017-06-24 05:23:59 +00:00
|
|
|
|
var poll = new Poll(_client, _strings, msg, data[0], data.Skip(1));
|
2017-05-29 04:13:22 +00:00
|
|
|
|
if (ActivePolls.TryAdd(channel.Guild.Id, poll))
|
|
|
|
|
{
|
|
|
|
|
poll.OnEnded += (gid) =>
|
|
|
|
|
{
|
|
|
|
|
ActivePolls.TryRemove(gid, out _);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
await poll.StartPoll().ConfigureAwait(false);
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-19 13:42:10 +00:00
|
|
|
|
public async Task<bool> TryExecuteEarly(DiscordSocketClient client, IGuild guild, IUserMessage msg)
|
2017-05-29 04:13:22 +00:00
|
|
|
|
{
|
|
|
|
|
if (guild == null)
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
if (!ActivePolls.TryGetValue(guild.Id, out var poll))
|
|
|
|
|
return false;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
return await poll.TryVote(msg).ConfigureAwait(false);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
_log.Warn(ex);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|