.clparew (Claim patreon rewards) added, needs testing

This commit is contained in:
Kwoth 2017-04-01 21:51:25 +02:00
parent 2b65518649
commit 7e23877fd8
6 changed files with 204 additions and 202 deletions

View File

@ -1,181 +1,183 @@
//using System.Collections.Generic; using System.Collections.Generic;
//using System.Linq; using System.Linq;
//using System.Net.Http; using System.Net.Http;
//using System.Threading.Tasks; using System.Threading.Tasks;
//using Discord.Commands; using Discord.Commands;
//using NadekoBot.Attributes; using NadekoBot.Attributes;
//using NadekoBot.Modules.Utility.Models; using NadekoBot.Modules.Utility.Models;
//using Newtonsoft.Json; using Newtonsoft.Json;
//using System.Threading; using System.Threading;
//using System; using System;
//using System.Collections.Immutable; using System.Collections.Immutable;
//using NadekoBot.Services; using NadekoBot.Services;
//using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
//using NadekoBot.Extensions; using NadekoBot.Extensions;
//namespace NadekoBot.Modules.Utility namespace NadekoBot.Modules.Utility
//{ {
// public partial class Utility public partial class Utility
// { {
// [Group] [Group]
// public class PatreonCommands : NadekoSubmodule public class PatreonCommands : NadekoSubmodule
// { {
// private static readonly PatreonThingy patreon; private static readonly PatreonThingy patreon;
// static PatreonCommands() static PatreonCommands()
// { {
// patreon = PatreonThingy.Instance; patreon = PatreonThingy.Instance;
// } }
// [NadekoCommand, Usage, Description, Aliases] [NadekoCommand, Usage, Description, Aliases]
// public async Task ClaimPatreonRewards() public async Task ClaimPatreonRewards()
// { {
// if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.PatreonAccessToken)) if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.PatreonAccessToken))
// return; return;
// if (DateTime.UtcNow.Day < 5) if (DateTime.UtcNow.Day < 5)
// { {
// await ReplyErrorLocalized("claimpatreon_too_early").ConfigureAwait(false); await ReplyErrorLocalized("clpa_too_early").ConfigureAwait(false);
// } }
// int amount = 0; int amount = 0;
// try try
// { {
// amount = await patreon.ClaimReward(Context.User.Id).ConfigureAwait(false); amount = await patreon.ClaimReward(Context.User.Id).ConfigureAwait(false);
// } }
// catch (Exception ex) catch (Exception ex)
// { {
// _log.Warn(ex); _log.Warn(ex);
// } }
// if (amount > 0) if (amount > 0)
// { {
// await ReplyConfirmLocalized("claimpatreon_success", amount).ConfigureAwait(false); await ReplyConfirmLocalized("clpa_success", amount + NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
// return; return;
// } }
// await Context.Channel.EmbedAsync(new Discord.EmbedBuilder().WithOkColor() await Context.Channel.EmbedAsync(new Discord.EmbedBuilder().WithOkColor()
// .WithDescription(GetText("claimpatreon_fail")) .WithDescription(GetText("clpa_fail"))
// .AddField(efb => efb.WithName("").WithValue("")) .AddField(efb => efb.WithName(GetText("clpa_fail_already_title")).WithValue(GetText("clpa_fail_already")))
// .AddField(efb => efb.WithName("").WithValue("")) .AddField(efb => efb.WithName(GetText("clpa_fail_wait_title")).WithValue(GetText("clpa_fail_wait")))
// .AddField(efb => efb.WithName("").WithValue(""))) .AddField(efb => efb.WithName(GetText("clpa_fail_sup_title")).WithValue(GetText("clpa_fail_sup"))))
// .ConfigureAwait(false); .ConfigureAwait(false);
}
}
// await ReplyErrorLocalized("claimpatreon_fail").ConfigureAwait(false); public class PatreonThingy
// } {
// } public static PatreonThingy _instance = new PatreonThingy();
public static PatreonThingy Instance => _instance;
// public class PatreonThingy private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1);
// {
// public static PatreonThingy _instance = new PatreonThingy();
// public static PatreonThingy Instance => _instance;
// private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1); public ImmutableArray<PatreonUserAndReward> Pledges { get; private set; }
// public ImmutableArray<PatreonUserAndReward> Pledges { get; private set; } private readonly Timer update;
private readonly SemaphoreSlim claimLockJustInCase = new SemaphoreSlim(1, 1);
// private readonly Timer update; private PatreonThingy()
// private readonly SemaphoreSlim claimLockJustInCase = new SemaphoreSlim(1, 1); {
if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.PatreonAccessToken))
return;
update = new Timer(async (_) => await LoadPledges(), null, TimeSpan.Zero, TimeSpan.FromHours(3));
}
// private PatreonThingy() public async Task LoadPledges()
// { {
// if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.PatreonAccessToken)) await getPledgesLocker.WaitAsync(1000).ConfigureAwait(false);
// return; try
// update = new Timer(async (_) => await LoadPledges(), null, TimeSpan.Zero, TimeSpan.FromHours(3)); {
// } var rewards = new List<PatreonPledge>();
var users = new List<PatreonUser>();
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("Authorization", "Bearer " + NadekoBot.Credentials.PatreonAccessToken);
var data = new PatreonData()
{
Links = new PatreonDataLinks()
{
next = "https://api.patreon.com/oauth2/api/campaigns/334038/pledges"
}
};
do
{
var res = await http.GetStringAsync(data.Links.next)
.ConfigureAwait(false);
data = JsonConvert.DeserializeObject<PatreonData>(res);
var pledgers = data.Data.Where(x => x["type"].ToString() == "pledge");
rewards.AddRange(pledgers.Select(x => JsonConvert.DeserializeObject<PatreonPledge>(x.ToString()))
.Where(x => x.attributes.declined_since == null));
users.AddRange(data.Included
.Where(x => x["type"].ToString() == "user")
.Select(x => JsonConvert.DeserializeObject<PatreonUser>(x.ToString())));
} while (!string.IsNullOrWhiteSpace(data.Links.next));
}
Pledges = rewards.Join(users, (r) => r.relationships?.patron?.data?.id, (u) => u.id, (x, y) => new PatreonUserAndReward()
{
User = y,
Reward = x,
}).ToImmutableArray();
}
finally
{
var _ = Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
getPledgesLocker.Release();
});
}
}
// public async Task LoadPledges() public async Task<int> ClaimReward(ulong userId)
// { {
// await getPledgesLocker.WaitAsync(1000).ConfigureAwait(false); await claimLockJustInCase.WaitAsync();
// try try
// { {
// var rewards = new List<PatreonPledge>(); var data = Pledges.FirstOrDefault(x => x.User.id == userId.ToString());
// var users = new List<PatreonUser>();
// using (var http = new HttpClient())
// {
// http.DefaultRequestHeaders.Clear();
// http.DefaultRequestHeaders.Add("Authorization", "Bearer " + NadekoBot.Credentials.PatreonAccessToken);
// var data = new PatreonData()
// {
// Links = new PatreonDataLinks()
// {
// next = "https://api.patreon.com/oauth2/api/campaigns/334038/pledges"
// }
// };
// do
// {
// var res = await http.GetStringAsync(data.Links.next)
// .ConfigureAwait(false);
// data = JsonConvert.DeserializeObject<PatreonData>(res);
// var pledgers = data.Data.Where(x => x["type"].ToString() == "pledge");
// rewards.AddRange(pledgers.Select(x => JsonConvert.DeserializeObject<PatreonPledge>(x.ToString()))
// .Where(x => x.attributes.declined_since == null));
// users.AddRange(data.Included
// .Where(x => x["type"].ToString() == "user")
// .Select(x => JsonConvert.DeserializeObject<PatreonUser>(x.ToString())));
// } while (!string.IsNullOrWhiteSpace(data.Links.next));
// }
// Pledges = rewards.Join(users, (r) => r.relationships?.patron?.data?.id, (u) => u.id, (x, y) => new PatreonUserAndReward()
// {
// User = y,
// Reward = x,
// }).ToImmutableArray();
// }
// finally
// {
// var _ = Task.Run(async () =>
// {
// await Task.Delay(TimeSpan.FromMinutes(5)).ConfigureAwait(false);
// getPledgesLocker.Release();
// });
// } if (data == null)
// } return 0;
// public async Task<int> ClaimReward(ulong userId) var amount = data.Reward.attributes.amount_cents;
// {
// await claimLockJustInCase.WaitAsync();
// try
// {
// var data = Pledges.FirstOrDefault(x => x.User.id == userId.ToString());
// if (data == null) using (var uow = DbHandler.UnitOfWork())
// return 0; {
var users = uow._context.Set<RewardedUser>();
var usr = users.FirstOrDefault(x => x.UserId == userId);
// var amount = data.Reward.attributes.amount_cents; if (usr == null)
{
users.Add(new RewardedUser()
{
UserId = userId,
LastReward = DateTime.UtcNow,
AmountRewardedThisMonth = amount,
});
// using (var uow = DbHandler.UnitOfWork()) await CurrencyHandler.AddCurrencyAsync(usr.UserId, "Patreon reward", amount, uow).ConfigureAwait(false);
// {
// var users = uow._context.Set<RewardedUser>();
// var usr = users.FirstOrDefault(x => x.UserId == userId);
// if (usr == null) await uow.CompleteAsync().ConfigureAwait(false);
// { return amount;
// users.Add(new RewardedUser() }
// {
// UserId = userId,
// LastReward = DateTime.UtcNow,
// AmountRewardedThisMonth = amount,
// });
// await uow.CompleteAsync().ConfigureAwait(false);
// return amount;
// }
// if (usr.AmountRewardedThisMonth < amount) if (usr.AmountRewardedThisMonth < amount)
// { {
// var toAward = amount - usr.AmountRewardedThisMonth; var toAward = amount - usr.AmountRewardedThisMonth;
// usr.LastReward = DateTime.UtcNow; usr.LastReward = DateTime.UtcNow;
// usr.AmountRewardedThisMonth = amount; usr.AmountRewardedThisMonth = amount;
// await uow.CompleteAsync().ConfigureAwait(false); await CurrencyHandler.AddCurrencyAsync(usr.UserId, "Patreon reward", toAward, uow).ConfigureAwait(false);
// return toAward;
// } await uow.CompleteAsync().ConfigureAwait(false);
// } return toAward;
// return 0; }
// } }
// finally return 0;
// { }
// claimLockJustInCase.Release(); finally
// } {
// } claimLockJustInCase.Release();
// } }
// } }
//} }
}
}

View File

@ -1707,7 +1707,7 @@ namespace NadekoBot.Resources {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to claimpatreonrewards. /// Looks up a localized string similar to clparew.
/// </summary> /// </summary>
public static string claimpatreonrewards_cmd { public static string claimpatreonrewards_cmd {
get { get {
@ -1716,7 +1716,7 @@ namespace NadekoBot.Resources {
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to If you&apos;re subscribed to bot owner&apos;s patreon you can user this command to claim your rewards - assuming bot owner did setup has their patreon key.. /// Looks up a localized string similar to Claim patreon rewards. If you&apos;re subscribed to bot owner&apos;s patreon you can user this command to claim your rewards - assuming bot owner did setup has their patreon key..
/// </summary> /// </summary>
public static string claimpatreonrewards_desc { public static string claimpatreonrewards_desc {
get { get {

View File

@ -3322,10 +3322,10 @@
<value>`{0}warnpunish 5 Ban` or `{0}warnpunish 3`</value> <value>`{0}warnpunish 5 Ban` or `{0}warnpunish 3`</value>
</data> </data>
<data name="claimpatreonrewards_cmd" xml:space="preserve"> <data name="claimpatreonrewards_cmd" xml:space="preserve">
<value>claimpatreonrewards</value> <value>clparew</value>
</data> </data>
<data name="claimpatreonrewards_desc" xml:space="preserve"> <data name="claimpatreonrewards_desc" xml:space="preserve">
<value>If you're subscribed to bot owner's patreon you can user this command to claim your rewards - assuming bot owner did setup has their patreon key.</value> <value>Claim patreon rewards. If you're subscribed to bot owner's patreon you can user this command to claim your rewards - assuming bot owner did setup has their patreon key.</value>
</data> </data>
<data name="claimpatreonrewards_usage" xml:space="preserve"> <data name="claimpatreonrewards_usage" xml:space="preserve">
<value>`{0}claimpatreonrewards`</value> <value>`{0}claimpatreonrewards`</value>

View File

@ -6028,81 +6028,81 @@ namespace NadekoBot.Resources {
/// <summary> /// <summary>
/// Looks up a localized string similar to Failed claiming rewards due to one of the following reasons:. /// Looks up a localized string similar to Failed claiming rewards due to one of the following reasons:.
/// </summary> /// </summary>
public static string utility_claimpatreon_fail { public static string utility_clpa_fail {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail", resourceCulture); return ResourceManager.GetString("utility_clpa_fail", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Maybe you have already received your reward for this month. You can receive rewards only once a month unless you increase your pledge.. /// Looks up a localized string similar to Maybe you have already received your reward for this month. You can receive rewards only once a month unless you increase your pledge..
/// </summary> /// </summary>
public static string utility_claimpatreon_fail_already { public static string utility_clpa_fail_already {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail_already", resourceCulture); return ResourceManager.GetString("utility_clpa_fail_already", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Already rewarded. /// Looks up a localized string similar to Already rewarded.
/// </summary> /// </summary>
public static string utility_claimpatreon_fail_already_title { public static string utility_clpa_fail_already_title {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail_already_title", resourceCulture); return ResourceManager.GetString("utility_clpa_fail_already_title", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to In order to be eligible for the reward, you must support the project on patreon. Use {0} command to get the link.. /// Looks up a localized string similar to In order to be eligible for the reward, you must support the project on patreon. Use {0} command to get the link..
/// </summary> /// </summary>
public static string utility_claimpatreon_fail_sup { public static string utility_clpa_fail_sup {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail_sup", resourceCulture); return ResourceManager.GetString("utility_clpa_fail_sup", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Not supporting. /// Looks up a localized string similar to Not supporting.
/// </summary> /// </summary>
public static string utility_claimpatreon_fail_sup_title { public static string utility_clpa_fail_sup_title {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail_sup_title", resourceCulture); return ResourceManager.GetString("utility_clpa_fail_sup_title", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to You have to wait a few hours after making your pledge, if you didn&apos;t, waiut a bit and then try again later.. /// Looks up a localized string similar to You have to wait a few hours after making your pledge, if you didn&apos;t, waiut a bit and then try again later..
/// </summary> /// </summary>
public static string utility_claimpatreon_fail_wait { public static string utility_clpa_fail_wait {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail_wait", resourceCulture); return ResourceManager.GetString("utility_clpa_fail_wait", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Wait some time. /// Looks up a localized string similar to Wait some time.
/// </summary> /// </summary>
public static string utility_claimpatreon_fail_wait_title { public static string utility_clpa_fail_wait_title {
get { get {
return ResourceManager.GetString("utility_claimpatreon_fail_wait_title", resourceCulture); return ResourceManager.GetString("utility_clpa_fail_wait_title", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to You&apos;ve received {0}. Thanks for supporting the project!. /// Looks up a localized string similar to You&apos;ve received {0}. Thanks for supporting the project!.
/// </summary> /// </summary>
public static string utility_claimpatreon_success { public static string utility_clpa_success {
get { get {
return ResourceManager.GetString("utility_claimpatreon_success", resourceCulture); return ResourceManager.GetString("utility_clpa_success", resourceCulture);
} }
} }
/// <summary> /// <summary>
/// Looks up a localized string similar to Rewards can be claimed on or after 5th of each month.. /// Looks up a localized string similar to Rewards can be claimed on or after 5th of each month..
/// </summary> /// </summary>
public static string utility_claimpatreon_too_early { public static string utility_clpa_too_early {
get { get {
return ResourceManager.GetString("utility_claimpatreon_too_early", resourceCulture); return ResourceManager.GetString("utility_clpa_too_early", resourceCulture);
} }
} }

View File

@ -2369,31 +2369,31 @@ Owner ID: {2}</value>
<data name="administration_slowmodewl_user_stop" xml:space="preserve"> <data name="administration_slowmodewl_user_stop" xml:space="preserve">
<value>Slowmode will no longer ignore user {0}</value> <value>Slowmode will no longer ignore user {0}</value>
</data> </data>
<data name="utility_claimpatreon_fail" xml:space="preserve"> <data name="utility_clpa_fail" xml:space="preserve">
<value>Failed claiming rewards due to one of the following reasons:</value> <value>Failed claiming rewards due to one of the following reasons:</value>
</data> </data>
<data name="utility_claimpatreon_fail_already" xml:space="preserve"> <data name="utility_clpa_fail_already" xml:space="preserve">
<value>Maybe you have already received your reward for this month. You can receive rewards only once a month unless you increase your pledge.</value> <value>Maybe you have already received your reward for this month. You can receive rewards only once a month unless you increase your pledge.</value>
</data> </data>
<data name="utility_claimpatreon_fail_already_title" xml:space="preserve"> <data name="utility_clpa_fail_already_title" xml:space="preserve">
<value>Already rewarded</value> <value>Already rewarded</value>
</data> </data>
<data name="utility_claimpatreon_fail_sup" xml:space="preserve"> <data name="utility_clpa_fail_sup" xml:space="preserve">
<value>In order to be eligible for the reward, you must support the project on patreon. Use {0} command to get the link.</value> <value>In order to be eligible for the reward, you must support the project on patreon. Use {0} command to get the link.</value>
</data> </data>
<data name="utility_claimpatreon_fail_sup_title" xml:space="preserve"> <data name="utility_clpa_fail_sup_title" xml:space="preserve">
<value>Not supporting</value> <value>Not supporting</value>
</data> </data>
<data name="utility_claimpatreon_fail_wait" xml:space="preserve"> <data name="utility_clpa_fail_wait" xml:space="preserve">
<value>You have to wait a few hours after making your pledge, if you didn't, waiut a bit and then try again later.</value> <value>You have to wait a few hours after making your pledge, if you didn't, waiut a bit and then try again later.</value>
</data> </data>
<data name="utility_claimpatreon_fail_wait_title" xml:space="preserve"> <data name="utility_clpa_fail_wait_title" xml:space="preserve">
<value>Wait some time</value> <value>Wait some time</value>
</data> </data>
<data name="utility_claimpatreon_success" xml:space="preserve"> <data name="utility_clpa_success" xml:space="preserve">
<value>You've received {0}. Thanks for supporting the project!</value> <value>You've received {0}. Thanks for supporting the project!</value>
</data> </data>
<data name="utility_claimpatreon_too_early" xml:space="preserve"> <data name="utility_clpa_too_early" xml:space="preserve">
<value>Rewards can be claimed on or after 5th of each month.</value> <value>Rewards can be claimed on or after 5th of each month.</value>
</data> </data>
</root> </root>

View File

@ -1,11 +1,11 @@
//using System; using System;
//namespace NadekoBot.Services.Database.Models namespace NadekoBot.Services.Database.Models
//{ {
// public class RewardedUser public class RewardedUser
// { {
// public ulong UserId { get; set; } public ulong UserId { get; set; }
// public int AmountRewardedThisMonth { get; set; } public int AmountRewardedThisMonth { get; set; }
// public DateTime LastReward { get; set; } public DateTime LastReward { get; set; }
// } }
//} }