poll is now public poll, private poll removed

This commit is contained in:
Master Kwoth 2017-06-24 07:23:59 +02:00
parent 7ad5c5e02b
commit e27e1005eb
8 changed files with 64 additions and 106 deletions

View File

@ -26,13 +26,7 @@ namespace NadekoBot.Modules.Games
[RequireUserPermission(GuildPermission.ManageMessages)] [RequireUserPermission(GuildPermission.ManageMessages)]
[RequireContext(ContextType.Guild)] [RequireContext(ContextType.Guild)]
public Task Poll([Remainder] string arg = null) public Task Poll([Remainder] string arg = null)
=> InternalStartPoll(arg, false); => InternalStartPoll(arg);
[NadekoCommand, Usage, Description, Aliases]
[RequireUserPermission(GuildPermission.ManageMessages)]
[RequireContext(ContextType.Guild)]
public Task PublicPoll([Remainder] string arg = null)
=> InternalStartPoll(arg, true);
[NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
[RequireUserPermission(GuildPermission.ManageMessages)] [RequireUserPermission(GuildPermission.ManageMessages)]
@ -44,15 +38,10 @@ namespace NadekoBot.Modules.Games
await Context.Channel.EmbedAsync(poll.GetStats(GetText("current_poll_results"))); await Context.Channel.EmbedAsync(poll.GetStats(GetText("current_poll_results")));
} }
//todo enable private polls, or completely remove them
private async Task InternalStartPoll(string arg, bool isPublic = false) private async Task InternalStartPoll(string arg)
{ {
if (isPublic == false) if(await _polls.StartPoll((ITextChannel)Context.Channel, Context.Message, arg) == false)
{
await ReplyErrorLocalized($"Temporarily disabled. Use `{Prefix}ppoll`");
return;
}
if(await _polls.StartPoll((ITextChannel)Context.Channel, Context.Message, arg, isPublic) == false)
await ReplyErrorLocalized("poll_already_running").ConfigureAwait(false); await ReplyErrorLocalized("poll_already_running").ConfigureAwait(false);
} }

View File

@ -290,9 +290,23 @@ namespace NadekoBot
Task SetClientReady() Task SetClientReady()
{ {
var _ = Task.Run(() => var _ = Task.Run(async () =>
{ {
clientReady.TrySetResult(true); clientReady.TrySetResult(true);
try
{
await Task.WhenAll((await Client.GetDMChannelsAsync())
.Select(x => x.CloseAsync()))
.ConfigureAwait(false);
}
catch
{
// ignored
}
finally
{
}
}); });
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -304,8 +318,8 @@ namespace NadekoBot
try try
{ {
Client.LoginAsync(TokenType.Bot, token).GetAwaiter().GetResult(); await Client.LoginAsync(TokenType.Bot, token).ConfigureAwait(false);
Client.StartAsync().GetAwaiter().GetResult(); await Client.StartAsync().ConfigureAwait(false);
Client.Ready += SetClientReady; Client.Ready += SetClientReady;
await clientReady.Task.ConfigureAwait(false); await clientReady.Task.ConfigureAwait(false);
Client.Ready -= SetClientReady; Client.Ready -= SetClientReady;

View File

@ -63,44 +63,44 @@ namespace NadekoBot.Services.Administration
_client.Guilds.SelectMany(g => g.Users); _client.Guilds.SelectMany(g => g.Users);
//todo load owner channels if(client.ShardId == 0)
//LoadOwnerChannels(); LoadOwnerChannels();
}); });
} }
//private void LoadOwnerChannels() private void LoadOwnerChannels()
//{ {
// var hs = new HashSet<ulong>(_creds.OwnerIds); var hs = new HashSet<ulong>(_creds.OwnerIds);
// var channels = new Dictionary<ulong, AsyncLazy<IDMChannel>>(); var channels = new Dictionary<ulong, AsyncLazy<IDMChannel>>();
// if (hs.Count > 0) if (hs.Count > 0)
// { {
// foreach (var g in _client.Guilds) foreach (var g in _client.Guilds)
// { {
// if (hs.Count == 0) if (hs.Count == 0)
// break; break;
// foreach (var u in g.Users) foreach (var u in g.Users)
// { {
// if (hs.Remove(u.Id)) if (hs.Remove(u.Id))
// { {
// channels.Add(u.Id, new AsyncLazy<IDMChannel>(async () => await u.CreateDMChannelAsync())); channels.Add(u.Id, new AsyncLazy<IDMChannel>(async () => await u.CreateDMChannelAsync()));
// if (hs.Count == 0) if (hs.Count == 0)
// break; break;
// } }
// } }
// } }
// } }
// ownerChannels = channels.OrderBy(x => _creds.OwnerIds.IndexOf(x.Key)) ownerChannels = channels.OrderBy(x => _creds.OwnerIds.IndexOf(x.Key))
// .Select(x => x.Value) .Select(x => x.Value)
// .ToImmutableArray(); .ToImmutableArray();
// if (!ownerChannels.Any()) if (!ownerChannels.Any())
// _log.Warn("No owner channels created! Make sure you've specified correct OwnerId in the credentials.json file."); _log.Warn("No owner channels created! Make sure you've specified correct OwnerId in the credentials.json file.");
// else else
// _log.Info($"Created {ownerChannels.Length} out of {_creds.OwnerIds.Length} owner message channels."); _log.Info($"Created {ownerChannels.Length} out of {_creds.OwnerIds.Length} owner message channels.");
//} }
// forwards dms // forwards dms
public async Task LateExecute(DiscordSocketClient client, IGuild guild, IUserMessage msg) public async Task LateExecute(DiscordSocketClient client, IGuild guild, IUserMessage msg)

View File

@ -21,13 +21,10 @@ namespace NadekoBot.Services.Games
private readonly DiscordSocketClient _client; private readonly DiscordSocketClient _client;
private readonly NadekoStrings _strings; private readonly NadekoStrings _strings;
private bool running = false; private bool running = false;
private HashSet<ulong> _guildUsers;
public event Action<ulong> OnEnded = delegate { }; public event Action<ulong> OnEnded = delegate { };
public bool IsPublic { get; } public Poll(DiscordSocketClient client, NadekoStrings strings, IUserMessage umsg, string question, IEnumerable<string> enumerable)
public Poll(DiscordSocketClient client, NadekoStrings strings, IUserMessage umsg, string question, IEnumerable<string> enumerable, bool isPublic = false)
{ {
_client = client; _client = client;
_strings = strings; _strings = strings;
@ -36,7 +33,6 @@ namespace NadekoBot.Services.Games
_guild = ((ITextChannel)umsg.Channel).Guild; _guild = ((ITextChannel)umsg.Channel).Guild;
_question = question; _question = question;
answers = enumerable as string[] ?? enumerable.ToArray(); answers = enumerable as string[] ?? enumerable.ToArray();
IsPublic = isPublic;
} }
public EmbedBuilder GetStats(string title) public EmbedBuilder GetStats(string title)
@ -82,13 +78,7 @@ namespace NadekoBot.Services.Games
var msgToSend = GetText("poll_created", Format.Bold(_originalMessage.Author.Username)) + "\n\n" + Format.Bold(_question) + "\n"; var msgToSend = GetText("poll_created", Format.Bold(_originalMessage.Author.Username)) + "\n\n" + Format.Bold(_question) + "\n";
var num = 1; var num = 1;
msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n"); msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n");
if (!IsPublic) msgToSend += "\n" + Format.Bold(GetText("poll_vote_public"));
msgToSend += "\n" + Format.Bold(GetText("poll_vote_private"));
else
msgToSend += "\n" + Format.Bold(GetText("poll_vote_public"));
if (!IsPublic)
_guildUsers = new HashSet<ulong>((await _guild.GetUsersAsync().ConfigureAwait(false)).Select(x => x.Id));
await _originalMessage.Channel.SendConfirmAsync(msgToSend).ConfigureAwait(false); await _originalMessage.Channel.SendConfirmAsync(msgToSend).ConfigureAwait(false);
running = true; running = true;
@ -114,36 +104,16 @@ namespace NadekoBot.Services.Games
return false; return false;
IMessageChannel ch; IMessageChannel ch;
if (IsPublic) //if public, channel must be the same the poll started in
{ if (_originalMessage.Channel.Id != msg.Channel.Id)
//if public, channel must be the same the poll started in return false;
if (_originalMessage.Channel.Id != msg.Channel.Id) ch = msg.Channel;
return false;
ch = msg.Channel;
}
else
{
//if private, channel must be dm channel
if ((ch = msg.Channel as IDMChannel) == null)
return false;
// user must be a member of the guild this poll is in
if (!_guildUsers.Contains(msg.Author.Id))
return false;
}
//user can vote only once //user can vote only once
if (_participants.TryAdd(msg.Author.Id, vote)) if (_participants.TryAdd(msg.Author.Id, vote))
{ {
if (!IsPublic) var toDelete = await ch.SendConfirmAsync(GetText("poll_voted", Format.Bold(msg.Author.ToString()))).ConfigureAwait(false);
{ toDelete.DeleteAfter(5);
await ch.SendConfirmAsync(GetText("thanks_for_voting", Format.Bold(msg.Author.Username))).ConfigureAwait(false);
}
else
{
var toDelete = await ch.SendConfirmAsync(GetText("poll_voted", Format.Bold(msg.Author.ToString()))).ConfigureAwait(false);
toDelete.DeleteAfter(5);
}
return true; return true;
} }
return false; return false;

View File

@ -23,7 +23,7 @@ namespace NadekoBot.Services.Games
_strings = strings; _strings = strings;
} }
public async Task<bool?> StartPoll(ITextChannel channel, IUserMessage msg, string arg, bool isPublic = false) public async Task<bool?> StartPoll(ITextChannel channel, IUserMessage msg, string arg)
{ {
if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";")) if (string.IsNullOrWhiteSpace(arg) || !arg.Contains(";"))
return null; return null;
@ -31,7 +31,7 @@ namespace NadekoBot.Services.Games
if (data.Length < 3) if (data.Length < 3)
return null; return null;
var poll = new Poll(_client, _strings, msg, data[0], data.Skip(1), isPublic: isPublic); var poll = new Poll(_client, _strings, msg, data[0], data.Skip(1));
if (ActivePolls.TryAdd(channel.Guild.Id, poll)) if (ActivePolls.TryAdd(channel.Guild.Id, poll))
{ {
poll.OnEnded += (gid) => poll.OnEnded += (gid) =>
@ -48,17 +48,7 @@ namespace NadekoBot.Services.Games
public async Task<bool> TryExecuteEarly(DiscordSocketClient client, IGuild guild, IUserMessage msg) public async Task<bool> TryExecuteEarly(DiscordSocketClient client, IGuild guild, IUserMessage msg)
{ {
if (guild == null) if (guild == null)
{
foreach (var kvp in ActivePolls)
{
if (!kvp.Value.IsPublic)
{
if (await kvp.Value.TryVote(msg).ConfigureAwait(false))
return true;
}
}
return false; return false;
}
if (!ActivePolls.TryGetValue(guild.Id, out var poll)) if (!ActivePolls.TryGetValue(guild.Id, out var poll))
return false; return false;

View File

@ -18,7 +18,6 @@ namespace NadekoBot.Services.Utility
public List<ConvertUnit> Units { get; } = new List<ConvertUnit>(); public List<ConvertUnit> Units { get; } = new List<ConvertUnit>();
private readonly Logger _log; private readonly Logger _log;
private readonly Timer _currencyUpdater; private readonly Timer _currencyUpdater;
private readonly Timer _currencyLoader;
private readonly TimeSpan _updateInterval = new TimeSpan(12, 0, 0); private readonly TimeSpan _updateInterval = new TimeSpan(12, 0, 0);
private readonly DbService _db; private readonly DbService _db;

View File

@ -15,7 +15,6 @@ using System.Threading.Tasks;
namespace NadekoBot.Services.Utility namespace NadekoBot.Services.Utility
{ {
//todo periodically load from the database, update only on shard 0
public class PatreonRewardsService public class PatreonRewardsService
{ {
private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1); private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1);
@ -96,15 +95,12 @@ namespace NadekoBot.Services.Utility
{ {
getPledgesLocker.Release(); getPledgesLocker.Release();
} }
Console.WriteLine("Pledges loaded from the website");
} }
else else
{ {
if(File.Exists(cacheFileName)) if(File.Exists(cacheFileName))
Pledges = JsonConvert.DeserializeObject<PatreonUserAndReward[]>(File.ReadAllText("./patreon_rewards.json")) Pledges = JsonConvert.DeserializeObject<PatreonUserAndReward[]>(File.ReadAllText("./patreon_rewards.json"))
.ToImmutableArray(); .ToImmutableArray();
Console.WriteLine("Pledges loaded from the file");
} }
} }

View File

@ -53,7 +53,7 @@ namespace NadekoBot
FileName = Credentials.ShardRunCommand, FileName = Credentials.ShardRunCommand,
Arguments = string.Format(Credentials.ShardRunArguments, i, curProcessId) Arguments = string.Format(Credentials.ShardRunArguments, i, curProcessId)
}); });
await Task.Delay(6500); await Task.Delay(5000);
} }
} }