mirror of
https://gitlab.com/Kwoth/nadekobot.git
synced 2025-09-11 01:38:27 -04:00
Compare commits
19 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
c050ce2123 | ||
|
27613410dd | ||
|
1513008b4b | ||
|
bf97cffd84 | ||
|
e37d1c46db | ||
|
06c20c6fa4 | ||
|
aa518d60a5 | ||
|
d55ce7accc | ||
|
502c5cec07 | ||
|
ee5c13607b | ||
|
5a681a5194 | ||
|
68395372f0 | ||
|
c8e01bd158 | ||
|
1d57191700 | ||
|
02c7ded457 | ||
|
12c483d222 | ||
|
c80898a7bf | ||
|
aae2805785 | ||
|
fc3695d090 |
37
CHANGELOG.md
37
CHANGELOG.md
@@ -4,7 +4,42 @@ Experimental changelog. Mostly based on [keepachangelog](https://keepachangelog.
|
||||
|
||||
## Unreleased
|
||||
|
||||
## [3.0.7]
|
||||
## [3.0.9] - 21.11.2021
|
||||
|
||||
### Added
|
||||
- Added `.emojiadd` with 3 overloads
|
||||
- `.ea :customEmoji:` which copies another server's emoji
|
||||
- `.ea newName :customEmoji:` which copies emoji under a different name
|
||||
- `.ea emojiName <imagelink.png>` which creates a new emoji from the specified image
|
||||
- Patreon Access and Refresh Tokens should now be automatically updated once a month as long as the user has provided the necessary credentials in creds.yml file:
|
||||
- `Patreon.ClientId`
|
||||
- `Patreon.RefreshToken` (will also get updated once a month but needs an initial value)
|
||||
- `Patreon.ClientSecret`
|
||||
- `Patreon.CampaignId`
|
||||
|
||||
### Fixed
|
||||
- Fixed an error that would show up in the console when a club image couldn't be drawn in certain circumstances
|
||||
|
||||
## [3.0.8] - 03.11.2021
|
||||
|
||||
### Added
|
||||
- Created VotesApi project nad re-worked vote rewards handling
|
||||
- Updated votes entries in creds.yml with explanations on how to set up vote links
|
||||
|
||||
### Fixed
|
||||
- Fixed adding currency to users who don't exist in the database
|
||||
- Memory used by the bot is now correct (thanks to kotz)
|
||||
- Ban/kick will no longer fail due to too long reasons
|
||||
- Fixed some fields not preserving inline after string replacements
|
||||
|
||||
### Changed
|
||||
- `images.json` moved to `images.yml`
|
||||
- Links will use the new cdn url
|
||||
- Heads and Tails images will be updated if you haven't changed them already
|
||||
- `.slot` redesigned (and updated entries in `images.yml`)
|
||||
- Reduced required permissions for .qdel (thanks to tbodt)
|
||||
|
||||
## [3.0.7] - 05.10.2021
|
||||
|
||||
### Added
|
||||
- `.streamsclear` re-added. It will remove all followed streams on the server.
|
||||
|
@@ -21,7 +21,7 @@
|
||||
#### Prerequisites
|
||||
|
||||
- Windows 8 or later (64-bit)
|
||||
- [Create a Discord Bot application and invite the bot to your server](../../creds-guide.md)
|
||||
- [Create a Discord Bot application and invite the bot to your server](../creds-guide.md)
|
||||
|
||||
**Optional**
|
||||
|
||||
|
@@ -28,7 +28,7 @@ namespace NadekoBot
|
||||
private readonly IBotCredentials _creds;
|
||||
private readonly CommandService _commandService;
|
||||
private readonly DbService _db;
|
||||
private readonly BotCredsProvider _credsProvider;
|
||||
private readonly IBotCredsProvider _credsProvider;
|
||||
|
||||
public event Func<GuildConfig, Task> JoinedGuild = delegate { return Task.CompletedTask; };
|
||||
|
||||
@@ -95,8 +95,8 @@ namespace NadekoBot
|
||||
}
|
||||
|
||||
var svcs = new ServiceCollection()
|
||||
.AddTransient<IBotCredentials>(_ => _creds) // bot creds
|
||||
.AddSingleton(_credsProvider)
|
||||
.AddTransient<IBotCredentials>(_ => _credsProvider.GetCreds()) // bot creds
|
||||
.AddSingleton<IBotCredsProvider>(_credsProvider)
|
||||
.AddSingleton(_db) // database
|
||||
.AddRedis(_creds.RedisOptions) // redis
|
||||
.AddSingleton(Client) // discord socket client
|
||||
|
@@ -12,7 +12,7 @@ namespace NadekoBot.Common.Attributes
|
||||
{
|
||||
public override Task<PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo executingCommand, IServiceProvider services)
|
||||
{
|
||||
var creds = services.GetRequiredService<BotCredsProvider>().GetCreds();
|
||||
var creds = services.GetRequiredService<IBotCredsProvider>().GetCreds();
|
||||
|
||||
return Task.FromResult((creds.IsOwner(context.User) || context.Client.CurrentUser.Id == context.User.Id ? PreconditionResult.FromSuccess() : PreconditionResult.FromError("Not owner")));
|
||||
}
|
||||
|
@@ -73,11 +73,6 @@ go to https://www.patreon.com/portal -> my clients -> create client")]
|
||||
Change only if you've changed the coordinator address or port.")]
|
||||
public string CoordinatorUrl { get; set; }
|
||||
|
||||
[YamlIgnore]
|
||||
public string PatreonCampaignId => Patreon?.CampaignId;
|
||||
[YamlIgnore]
|
||||
public string PatreonAccessToken => Patreon?.AccessToken;
|
||||
|
||||
[Comment(@"Api key obtained on https://rapidapi.com (go to MyApps -> Add New App -> Enter Name -> Application key)")]
|
||||
public string RapidApiKey { get; set; }
|
||||
|
||||
@@ -121,11 +116,9 @@ Windows default
|
||||
// todo fixup patreon
|
||||
public sealed record PatreonSettings
|
||||
{
|
||||
[Comment(@"Access token. You have to manually update this 1st of each month by refreshing the token on https://patreon.com/portal")]
|
||||
public string ClientId { get; set; }
|
||||
public string AccessToken { get; set; }
|
||||
[Comment(@"Unused atm")]
|
||||
public string RefreshToken { get; set; }
|
||||
[Comment(@"Unused atm")]
|
||||
public string ClientSecret { get; set; }
|
||||
|
||||
[Comment(@"Campaign ID of your patreon page. Go to your patreon page (make sure you're logged in) and type ""prompt('Campaign ID', window.patreon.bootstrap.creator.data.id);"" in the console. (ctrl + shift + i)")]
|
||||
|
@@ -12,12 +12,11 @@ namespace NadekoBot
|
||||
string GoogleApiKey { get; }
|
||||
ICollection<ulong> OwnerIds { get; }
|
||||
string RapidApiKey { get; }
|
||||
string PatreonAccessToken { get; }
|
||||
|
||||
Creds.DbOptions Db { get; }
|
||||
string OsuApiKey { get; }
|
||||
int TotalShards { get; }
|
||||
string PatreonCampaignId { get; }
|
||||
Creds.PatreonSettings Patreon { get; }
|
||||
string CleverbotApiKey { get; }
|
||||
RestartConfig RestartCommand { get; }
|
||||
Creds.VotesSettings Votes { get; }
|
||||
|
17
src/NadekoBot/Common/TypeReaders/EmoteTypeReader.cs
Normal file
17
src/NadekoBot/Common/TypeReaders/EmoteTypeReader.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.Threading.Tasks;
|
||||
using Discord;
|
||||
using Discord.Commands;
|
||||
|
||||
namespace NadekoBot.Common.TypeReaders
|
||||
{
|
||||
public sealed class EmoteTypeReader : NadekoTypeReader<Emote>
|
||||
{
|
||||
public override Task<TypeReaderResult> ReadAsync(ICommandContext ctx, string input)
|
||||
{
|
||||
if (!Emote.TryParse(input, out var emote))
|
||||
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Input is not a valid emote"));
|
||||
|
||||
return Task.FromResult(TypeReaderResult.FromSuccess(emote));
|
||||
}
|
||||
}
|
||||
}
|
@@ -17,6 +17,12 @@ namespace NadekoBot.Migrations
|
||||
migrationBuilder.Sql("DELETE FROM FilterChannelId WHERE GuildConfigId NOT IN (SELECT Id from GuildConfigs)");
|
||||
migrationBuilder.Sql("DELETE FROM CommandCooldown WHERE GuildConfigId NOT IN (SELECT Id from GuildConfigs)");
|
||||
|
||||
// fix for users who edited their waifuinfo table manually and are unable to update
|
||||
migrationBuilder.Sql("DELETE FROM WaifuInfo where WaifuId not in (SELECT Id from DiscordUser);");
|
||||
|
||||
// fix for users who deleted clubs manually and are unable to update now
|
||||
migrationBuilder.Sql("UPDATE DiscordUser SET ClubId = null WHERE ClubId is not null and ClubId not in (SELECT Id from Clubs);");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ChannelCreated",
|
||||
table: "LogSettings");
|
||||
|
@@ -12,6 +12,8 @@ using LinqToDB;
|
||||
using LinqToDB.EntityFrameworkCore;
|
||||
using NadekoBot.Db;
|
||||
using Serilog;
|
||||
using System.Threading;
|
||||
using System;
|
||||
|
||||
namespace NadekoBot.Modules.Administration.Services
|
||||
{
|
||||
@@ -21,6 +23,11 @@ namespace NadekoBot.Modules.Administration.Services
|
||||
private readonly DiscordSocketClient _client;
|
||||
private readonly ConcurrentDictionary<ulong, IndexedCollection<ReactionRoleMessage>> _models;
|
||||
|
||||
/// <summary>
|
||||
/// Contains the (Message ID, User ID) of reaction roles that are currently being processed.
|
||||
/// </summary>
|
||||
private readonly ConcurrentHashSet<(ulong, ulong)> _reacting = new();
|
||||
|
||||
public RoleCommandsService(DiscordSocketClient client, DbService db,
|
||||
Bot bot)
|
||||
{
|
||||
@@ -38,75 +45,58 @@ namespace NadekoBot.Modules.Administration.Services
|
||||
|
||||
private Task _client_ReactionAdded(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel chan, SocketReaction reaction)
|
||||
{
|
||||
var _ = Task.Run(async () =>
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
if (!reaction.User.IsSpecified ||
|
||||
reaction.User.Value.IsBot ||
|
||||
reaction.User.Value is not SocketGuildUser gusr ||
|
||||
chan is not SocketGuildChannel gch ||
|
||||
!_models.TryGetValue(gch.Guild.Id, out var confs))
|
||||
return;
|
||||
|
||||
var conf = confs.FirstOrDefault(x => x.MessageId == msg.Id);
|
||||
|
||||
if (conf is null)
|
||||
return;
|
||||
|
||||
// compare emote names for backwards compatibility :facepalm:
|
||||
var reactionRole = conf.ReactionRoles.FirstOrDefault(x => x.EmoteName == reaction.Emote.Name || x.EmoteName == reaction.Emote.ToString());
|
||||
|
||||
if (reactionRole != null)
|
||||
{
|
||||
if (!reaction.User.IsSpecified ||
|
||||
reaction.User.Value.IsBot ||
|
||||
!(reaction.User.Value is SocketGuildUser gusr))
|
||||
return;
|
||||
|
||||
if (!(chan is SocketGuildChannel gch))
|
||||
return;
|
||||
|
||||
if (!_models.TryGetValue(gch.Guild.Id, out var confs))
|
||||
return;
|
||||
|
||||
var conf = confs.FirstOrDefault(x => x.MessageId == msg.Id);
|
||||
|
||||
if (conf is null)
|
||||
return;
|
||||
|
||||
// compare emote names for backwards compatibility :facepalm:
|
||||
var reactionRole = conf.ReactionRoles.FirstOrDefault(x => x.EmoteName == reaction.Emote.Name || x.EmoteName == reaction.Emote.ToString());
|
||||
if (reactionRole != null)
|
||||
if (!conf.Exclusive)
|
||||
{
|
||||
if (conf.Exclusive)
|
||||
{
|
||||
var roleIds = conf.ReactionRoles.Select(x => x.RoleId)
|
||||
.Where(x => x != reactionRole.RoleId)
|
||||
.Select(x => gusr.Guild.GetRole(x))
|
||||
.Where(x => x != null);
|
||||
|
||||
var __ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
//if the role is exclusive,
|
||||
// remove all other reactions user added to the message
|
||||
var dl = await msg.GetOrDownloadAsync().ConfigureAwait(false);
|
||||
foreach (var r in dl.Reactions)
|
||||
{
|
||||
if (r.Key.Name == reaction.Emote.Name)
|
||||
continue;
|
||||
try { await dl.RemoveReactionAsync(r.Key, gusr).ConfigureAwait(false); } catch { }
|
||||
await Task.Delay(100).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
await gusr.RemoveRolesAsync(roleIds).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var toAdd = gusr.Guild.GetRole(reactionRole.RoleId);
|
||||
if (toAdd != null && !gusr.Roles.Contains(toAdd))
|
||||
{
|
||||
await gusr.AddRolesAsync(new[] { toAdd }).ConfigureAwait(false);
|
||||
}
|
||||
await AddReactionRoleAsync(gusr, reactionRole);
|
||||
return;
|
||||
}
|
||||
else
|
||||
|
||||
// If same (message, user) are being processed in an exclusive rero, quit
|
||||
if (!_reacting.Add((msg.Id, reaction.UserId)))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var dl = await msg.GetOrDownloadAsync().ConfigureAwait(false);
|
||||
await dl.RemoveReactionAsync(reaction.Emote, dl.Author,
|
||||
new RequestOptions()
|
||||
{
|
||||
RetryMode = RetryMode.RetryRatelimit | RetryMode.Retry502
|
||||
}).ConfigureAwait(false);
|
||||
Log.Warning("User {0} is adding unrelated reactions to the reaction roles message.", dl.Author);
|
||||
var removeExclusiveTask = RemoveExclusiveReactionRoleAsync(msg, gusr, reaction, conf, reactionRole, CancellationToken.None);
|
||||
var addRoleTask = AddReactionRoleAsync(gusr, reactionRole);
|
||||
|
||||
await Task.WhenAll(removeExclusiveTask, addRoleTask).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Free (message/user) for another exclusive rero
|
||||
_reacting.TryRemove((msg.Id, reaction.UserId));
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
else
|
||||
{
|
||||
var dl = await msg.GetOrDownloadAsync().ConfigureAwait(false);
|
||||
await dl.RemoveReactionAsync(reaction.Emote, dl.Author,
|
||||
new RequestOptions()
|
||||
{
|
||||
RetryMode = RetryMode.RetryRatelimit | RetryMode.Retry502
|
||||
}).ConfigureAwait(false);
|
||||
Log.Warning("User {0} is adding unrelated reactions to the reaction roles message.", dl.Author);
|
||||
}
|
||||
});
|
||||
|
||||
return Task.CompletedTask;
|
||||
@@ -114,16 +104,16 @@ namespace NadekoBot.Modules.Administration.Services
|
||||
|
||||
private Task _client_ReactionRemoved(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel chan, SocketReaction reaction)
|
||||
{
|
||||
var _ = Task.Run(async () =>
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!reaction.User.IsSpecified ||
|
||||
reaction.User.Value.IsBot ||
|
||||
!(reaction.User.Value is SocketGuildUser gusr))
|
||||
reaction.User.Value is not SocketGuildUser gusr)
|
||||
return;
|
||||
|
||||
if (!(chan is SocketGuildChannel gch))
|
||||
if (chan is not SocketGuildChannel gch)
|
||||
return;
|
||||
|
||||
if (!_models.TryGetValue(gch.Guild.Id, out var confs))
|
||||
@@ -193,5 +183,71 @@ namespace NadekoBot.Modules.Administration.Services
|
||||
uow.SaveChanges();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a reaction role to the specified user.
|
||||
/// </summary>
|
||||
/// <param name="user">A Discord guild user.</param>
|
||||
/// <param name="dbRero">The database settings of this reaction role.</param>
|
||||
private Task AddReactionRoleAsync(SocketGuildUser user, ReactionRole dbRero)
|
||||
{
|
||||
var toAdd = user.Guild.GetRole(dbRero.RoleId);
|
||||
|
||||
return (toAdd != null && !user.Roles.Contains(toAdd))
|
||||
? user.AddRoleAsync(toAdd)
|
||||
: Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the exclusive reaction roles and reactions from the specified user.
|
||||
/// </summary>
|
||||
/// <param name="reactionMessage">The Discord message that contains the reaction roles.</param>
|
||||
/// <param name="user">A Discord guild user.</param>
|
||||
/// <param name="reaction">The Discord reaction of the user.</param>
|
||||
/// <param name="dbReroMsg">The database entry of the reaction role message.</param>
|
||||
/// <param name="dbRero">The database settings of this reaction role.</param>
|
||||
/// <param name="cToken">A cancellation token to cancel the operation.</param>
|
||||
/// <exception cref="OperationCanceledException">Occurs when the operation is cancelled before it began.</exception>
|
||||
/// <exception cref="TaskCanceledException">Occurs when the operation is cancelled while it's still executing.</exception>
|
||||
private Task RemoveExclusiveReactionRoleAsync(Cacheable<IUserMessage, ulong> reactionMessage, SocketGuildUser user, SocketReaction reaction, ReactionRoleMessage dbReroMsg, ReactionRole dbRero, CancellationToken cToken = default)
|
||||
{
|
||||
cToken.ThrowIfCancellationRequested();
|
||||
|
||||
var roleIds = dbReroMsg.ReactionRoles.Select(x => x.RoleId)
|
||||
.Where(x => x != dbRero.RoleId)
|
||||
.Select(x => user.Guild.GetRole(x))
|
||||
.Where(x => x != null);
|
||||
|
||||
var removeReactionsTask = RemoveOldReactionsAsync(reactionMessage, user, reaction, cToken);
|
||||
|
||||
var removeRolesTask = user.RemoveRolesAsync(roleIds);
|
||||
|
||||
return Task.WhenAll(removeReactionsTask, removeRolesTask);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes old reactions from an exclusive reaction role.
|
||||
/// </summary>
|
||||
/// <param name="reactionMessage">The Discord message that contains the reaction roles.</param>
|
||||
/// <param name="user">A Discord guild user.</param>
|
||||
/// <param name="reaction">The Discord reaction of the user.</param>
|
||||
/// <param name="cToken">A cancellation token to cancel the operation.</param>
|
||||
/// <exception cref="OperationCanceledException">Occurs when the operation is cancelled before it began.</exception>
|
||||
/// <exception cref="TaskCanceledException">Occurs when the operation is cancelled while it's still executing.</exception>
|
||||
private async Task RemoveOldReactionsAsync(Cacheable<IUserMessage, ulong> reactionMessage, SocketGuildUser user, SocketReaction reaction, CancellationToken cToken = default)
|
||||
{
|
||||
cToken.ThrowIfCancellationRequested();
|
||||
|
||||
//if the role is exclusive,
|
||||
// remove all other reactions user added to the message
|
||||
var dl = await reactionMessage.GetOrDownloadAsync().ConfigureAwait(false);
|
||||
foreach (var r in dl.Reactions)
|
||||
{
|
||||
if (r.Key.Name == reaction.Emote.Name)
|
||||
continue;
|
||||
try { await dl.RemoveReactionAsync(r.Key, user).ConfigureAwait(false); } catch { }
|
||||
await Task.Delay(100, cToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -776,23 +776,32 @@ namespace NadekoBot.Modules.Administration
|
||||
return;
|
||||
|
||||
var missing = new List<string>();
|
||||
var banning = new HashSet<IGuildUser>();
|
||||
var banning = new HashSet<IUser>();
|
||||
|
||||
await ctx.Channel.TriggerTypingAsync();
|
||||
foreach (var userStr in userStrings)
|
||||
{
|
||||
if (ulong.TryParse(userStr, out var userId))
|
||||
{
|
||||
var user = await ctx.Guild.GetUserAsync(userId) ??
|
||||
IUser user = await ctx.Guild.GetUserAsync(userId) ??
|
||||
await ((DiscordSocketClient)Context.Client).Rest.GetGuildUserAsync(ctx.Guild.Id, userId);
|
||||
|
||||
if (user is null)
|
||||
{
|
||||
missing.Add(userStr);
|
||||
continue;
|
||||
// if IGuildUser is null, try to get IUser
|
||||
user = await ((DiscordSocketClient)Context.Client).Rest.GetUserAsync(userId);
|
||||
|
||||
// only add to missing if *still* null
|
||||
if (user is null)
|
||||
{
|
||||
missing.Add(userStr);
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (!await CheckRoleHierarchy(user))
|
||||
//Hierachy checks only if the user is in the guild
|
||||
if (user is IGuildUser gu && !await CheckRoleHierarchy(gu))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -820,7 +829,7 @@ namespace NadekoBot.Modules.Administration
|
||||
{
|
||||
try
|
||||
{
|
||||
await toBan.BanAsync(7);
|
||||
await ctx.Guild.AddBanAsync(toBan.Id, 7, $"{ctx.User} | Massban");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
@@ -2,6 +2,7 @@
|
||||
using Discord.Commands;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using NadekoBot.Common;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Services;
|
||||
using NadekoBot.Db;
|
||||
@@ -23,6 +24,7 @@ namespace NadekoBot.Modules.Games
|
||||
_db = db;
|
||||
}
|
||||
|
||||
[NoPublicBot]
|
||||
[NadekoCommand, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[UserPerm(GuildPerm.ManageMessages)]
|
||||
|
@@ -1,23 +1,134 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace NadekoBot.Modules.Utility.Common.Patreon
|
||||
{
|
||||
public class PatreonData
|
||||
public sealed class Attributes
|
||||
{
|
||||
public JObject[] Included { get; set; }
|
||||
public JObject[] Data { get; set; }
|
||||
public PatreonDataLinks Links { get; set; }
|
||||
[JsonPropertyName("full_name")]
|
||||
public string FullName { get; set; }
|
||||
|
||||
[JsonPropertyName("is_follower")]
|
||||
public bool IsFollower { get; set; }
|
||||
|
||||
[JsonPropertyName("last_charge_date")]
|
||||
public DateTime LastChargeDate { get; set; }
|
||||
|
||||
[JsonPropertyName("last_charge_status")]
|
||||
public string LastChargeStatus { get; set; }
|
||||
|
||||
[JsonPropertyName("lifetime_support_cents")]
|
||||
public int LifetimeSupportCents { get; set; }
|
||||
|
||||
[JsonPropertyName("currently_entitled_amount_cents")]
|
||||
public int CurrentlyEntitledAmountCents { get; set; }
|
||||
|
||||
[JsonPropertyName("patron_status")]
|
||||
public string PatronStatus { get; set; }
|
||||
}
|
||||
|
||||
public class PatreonDataLinks
|
||||
public sealed class Data
|
||||
{
|
||||
public string first { get; set; }
|
||||
public string next { get; set; }
|
||||
[JsonPropertyName("id")]
|
||||
public string Id { get; set; }
|
||||
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; }
|
||||
}
|
||||
|
||||
public class PatreonUserAndReward
|
||||
public sealed class Address
|
||||
{
|
||||
public PatreonUser User { get; set; }
|
||||
public PatreonPledge Reward { get; set; }
|
||||
[JsonPropertyName("data")]
|
||||
public Data Data { get; set; }
|
||||
}
|
||||
|
||||
// public sealed class CurrentlyEntitledTiers
|
||||
// {
|
||||
// [JsonPropertyName("data")]
|
||||
// public List<Datum> Data { get; set; }
|
||||
// }
|
||||
|
||||
// public sealed class Relationships
|
||||
// {
|
||||
// [JsonPropertyName("address")]
|
||||
// public Address Address { get; set; }
|
||||
//
|
||||
// // [JsonPropertyName("currently_entitled_tiers")]
|
||||
// // public CurrentlyEntitledTiers CurrentlyEntitledTiers { get; set; }
|
||||
// }
|
||||
|
||||
public sealed class PatreonResponse
|
||||
{
|
||||
[JsonPropertyName("data")]
|
||||
public List<PatreonMember> Data { get; set; }
|
||||
|
||||
[JsonPropertyName("included")]
|
||||
public List<PatreonUser> Included { get; set; }
|
||||
|
||||
[JsonPropertyName("links")]
|
||||
public PatreonLinks Links { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PatreonLinks
|
||||
{
|
||||
[JsonPropertyName("next")]
|
||||
public string Next { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PatreonUser
|
||||
{
|
||||
[JsonPropertyName("attributes")]
|
||||
public PatreonUserAttributes Attributes { get; set; }
|
||||
[JsonPropertyName("id")]
|
||||
public string Id { get; set; }
|
||||
// public string Type { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PatreonUserAttributes
|
||||
{
|
||||
[JsonPropertyName("social_connections")]
|
||||
public PatreonSocials SocialConnections { get; set; }
|
||||
}
|
||||
public sealed class PatreonSocials
|
||||
{
|
||||
[JsonPropertyName("discord")]
|
||||
public DiscordSocial Discord { get; set; }
|
||||
}
|
||||
|
||||
public sealed class DiscordSocial
|
||||
{
|
||||
[JsonPropertyName("user_id")]
|
||||
public string UserId { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PatreonMember
|
||||
{
|
||||
[JsonPropertyName("attributes")]
|
||||
public Attributes Attributes { get; set; }
|
||||
|
||||
[JsonPropertyName("relationships")]
|
||||
public Relationships Relationships { get; set; }
|
||||
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; }
|
||||
}
|
||||
|
||||
public sealed class Relationships
|
||||
{
|
||||
[JsonPropertyName("user")]
|
||||
public PatreonRelationshipUser User { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PatreonRelationshipUser
|
||||
{
|
||||
[JsonPropertyName("data")]
|
||||
public PatreonUserData Data { get; set; }
|
||||
}
|
||||
|
||||
public sealed class PatreonUserData
|
||||
{
|
||||
[JsonPropertyName("id")]
|
||||
public string Id { get; set; }
|
||||
}
|
||||
}
|
||||
|
@@ -1,62 +0,0 @@
|
||||
namespace NadekoBot.Modules.Utility.Common.Patreon
|
||||
{
|
||||
public class Attributes
|
||||
{
|
||||
public int amount_cents { get; set; }
|
||||
public string created_at { get; set; }
|
||||
public object declined_since { get; set; }
|
||||
public bool is_twitch_pledge { get; set; }
|
||||
public bool patron_pays_fees { get; set; }
|
||||
public int? pledge_cap_cents { get; set; }
|
||||
}
|
||||
|
||||
public class Address
|
||||
{
|
||||
public object data { get; set; }
|
||||
}
|
||||
|
||||
public class Data
|
||||
{
|
||||
public string id { get; set; }
|
||||
public string type { get; set; }
|
||||
}
|
||||
|
||||
public class Links
|
||||
{
|
||||
public string related { get; set; }
|
||||
}
|
||||
|
||||
public class Creator
|
||||
{
|
||||
public Data data { get; set; }
|
||||
public Links links { get; set; }
|
||||
}
|
||||
|
||||
public class Patron
|
||||
{
|
||||
public Data data { get; set; }
|
||||
public Links links { get; set; }
|
||||
}
|
||||
|
||||
public class Reward
|
||||
{
|
||||
public Data data { get; set; }
|
||||
public Links links { get; set; }
|
||||
}
|
||||
|
||||
public class Relationships
|
||||
{
|
||||
public Address address { get; set; }
|
||||
public Creator creator { get; set; }
|
||||
public Patron patron { get; set; }
|
||||
public Reward reward { get; set; }
|
||||
}
|
||||
|
||||
public class PatreonPledge
|
||||
{
|
||||
public Attributes attributes { get; set; }
|
||||
public string id { get; set; }
|
||||
public Relationships relationships { get; set; }
|
||||
public string type { get; set; }
|
||||
}
|
||||
}
|
@@ -1,64 +0,0 @@
|
||||
namespace NadekoBot.Modules.Utility.Common.Patreon
|
||||
{
|
||||
public class DiscordConnection
|
||||
{
|
||||
public string user_id { get; set; }
|
||||
}
|
||||
|
||||
public class SocialConnections
|
||||
{
|
||||
public object deviantart { get; set; }
|
||||
public DiscordConnection discord { get; set; }
|
||||
public object facebook { get; set; }
|
||||
public object spotify { get; set; }
|
||||
public object twitch { get; set; }
|
||||
public object twitter { get; set; }
|
||||
public object youtube { get; set; }
|
||||
}
|
||||
|
||||
public class UserAttributes
|
||||
{
|
||||
public string about { get; set; }
|
||||
public string created { get; set; }
|
||||
public object discord_id { get; set; }
|
||||
public string email { get; set; }
|
||||
public object facebook { get; set; }
|
||||
public object facebook_id { get; set; }
|
||||
public string first_name { get; set; }
|
||||
public string full_name { get; set; }
|
||||
public int gender { get; set; }
|
||||
public bool has_password { get; set; }
|
||||
public string image_url { get; set; }
|
||||
public bool is_deleted { get; set; }
|
||||
public bool is_nuked { get; set; }
|
||||
public bool is_suspended { get; set; }
|
||||
public string last_name { get; set; }
|
||||
public SocialConnections social_connections { get; set; }
|
||||
public int status { get; set; }
|
||||
public string thumb_url { get; set; }
|
||||
public object twitch { get; set; }
|
||||
public string twitter { get; set; }
|
||||
public string url { get; set; }
|
||||
public string vanity { get; set; }
|
||||
public object youtube { get; set; }
|
||||
}
|
||||
|
||||
public class Campaign
|
||||
{
|
||||
public Data data { get; set; }
|
||||
public Links links { get; set; }
|
||||
}
|
||||
|
||||
public class UserRelationships
|
||||
{
|
||||
public Campaign campaign { get; set; }
|
||||
}
|
||||
|
||||
public class PatreonUser
|
||||
{
|
||||
public UserAttributes attributes { get; set; }
|
||||
public string id { get; set; }
|
||||
public UserRelationships relationships { get; set; }
|
||||
public string type { get; set; }
|
||||
}
|
||||
}
|
@@ -6,6 +6,7 @@ using NadekoBot.Extensions;
|
||||
using Discord;
|
||||
using NadekoBot.Common.Attributes;
|
||||
using NadekoBot.Modules.Utility.Services;
|
||||
using Serilog;
|
||||
|
||||
namespace NadekoBot.Modules.Utility
|
||||
{
|
||||
@@ -25,8 +26,12 @@ namespace NadekoBot.Modules.Utility
|
||||
[RequireContext(ContextType.DM)]
|
||||
public async Task ClaimPatreonRewards()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_creds.PatreonAccessToken))
|
||||
if (string.IsNullOrWhiteSpace(_creds.Patreon.AccessToken))
|
||||
{
|
||||
Log.Warning("In order to use patreon reward commands, " +
|
||||
"you need to specify CampaignId and AccessToken in creds.yml");
|
||||
return;
|
||||
}
|
||||
|
||||
if (DateTime.UtcNow.Day < 5)
|
||||
{
|
||||
|
@@ -2,17 +2,21 @@
|
||||
using NadekoBot.Services;
|
||||
using NadekoBot.Services.Database.Models;
|
||||
using NadekoBot.Modules.Utility.Common.Patreon;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Discord;
|
||||
using NadekoBot.Modules.Gambling.Services;
|
||||
using NadekoBot.Extensions;
|
||||
using Serilog;
|
||||
using StackExchange.Redis;
|
||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||
|
||||
namespace NadekoBot.Modules.Utility.Services
|
||||
{
|
||||
@@ -20,96 +24,195 @@ namespace NadekoBot.Modules.Utility.Services
|
||||
{
|
||||
private readonly SemaphoreSlim getPledgesLocker = new SemaphoreSlim(1, 1);
|
||||
|
||||
private PatreonUserAndReward[] _pledges;
|
||||
|
||||
private readonly Timer _updater;
|
||||
private readonly SemaphoreSlim claimLockJustInCase = new SemaphoreSlim(1, 1);
|
||||
|
||||
public TimeSpan Interval { get; } = TimeSpan.FromMinutes(3);
|
||||
private readonly IBotCredentials _creds;
|
||||
private readonly DbService _db;
|
||||
private readonly ICurrencyService _currency;
|
||||
private readonly GamblingConfigService _gamblingConfigService;
|
||||
private readonly ConnectionMultiplexer _redis;
|
||||
private readonly IBotCredsProvider _credsProvider;
|
||||
private readonly IHttpClientFactory _httpFactory;
|
||||
private readonly IEmbedBuilderService _eb;
|
||||
private readonly DiscordSocketClient _client;
|
||||
|
||||
public DateTime LastUpdate { get; private set; } = DateTime.UtcNow;
|
||||
|
||||
public PatreonRewardsService(IBotCredentials creds, DbService db,
|
||||
ICurrencyService currency, IHttpClientFactory factory, IEmbedBuilderService eb,
|
||||
DiscordSocketClient client, GamblingConfigService gamblingConfigService)
|
||||
public PatreonRewardsService(
|
||||
DbService db,
|
||||
ICurrencyService currency,
|
||||
IHttpClientFactory factory,
|
||||
IEmbedBuilderService eb,
|
||||
DiscordSocketClient client,
|
||||
GamblingConfigService gamblingConfigService,
|
||||
ConnectionMultiplexer redis,
|
||||
IBotCredsProvider credsProvider)
|
||||
{
|
||||
_creds = creds;
|
||||
_db = db;
|
||||
_currency = currency;
|
||||
_gamblingConfigService = gamblingConfigService;
|
||||
_redis = redis;
|
||||
_credsProvider = credsProvider;
|
||||
_httpFactory = factory;
|
||||
_eb = eb;
|
||||
_client = client;
|
||||
|
||||
if (client.ShardId == 0)
|
||||
_updater = new Timer(async _ => await RefreshPledges().ConfigureAwait(false),
|
||||
_updater = new Timer(async _ => await RefreshPledges(_credsProvider.GetCreds()).ConfigureAwait(false),
|
||||
null, TimeSpan.Zero, Interval);
|
||||
}
|
||||
|
||||
public async Task RefreshPledges()
|
||||
private DateTime LastAccessTokenUpdate(IBotCredentials creds)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_creds.PatreonAccessToken)
|
||||
|| string.IsNullOrWhiteSpace(_creds.PatreonAccessToken))
|
||||
return;
|
||||
var db = _redis.GetDatabase();
|
||||
var val = db.StringGet($"{creds.RedisKey()}_patreon_update");
|
||||
|
||||
if (val == default)
|
||||
return DateTime.MinValue;
|
||||
|
||||
var lastTime = DateTime.FromBinary((long)val);
|
||||
return lastTime;
|
||||
}
|
||||
|
||||
|
||||
private sealed class PatreonRefreshData
|
||||
{
|
||||
[JsonPropertyName("access_token")]
|
||||
public string AccessToken { get; set; }
|
||||
|
||||
[JsonPropertyName("refresh_token")]
|
||||
public string RefreshToken { get; set; }
|
||||
|
||||
[JsonPropertyName("expires_in")]
|
||||
public long ExpiresIn { get; set; }
|
||||
|
||||
[JsonPropertyName("scope")]
|
||||
public string Scope { get; set; }
|
||||
|
||||
[JsonPropertyName("token_type")]
|
||||
public string TokenType { get; set; }
|
||||
}
|
||||
|
||||
private async Task<bool> UpdateAccessToken(IBotCredentials creds)
|
||||
{
|
||||
Log.Information("Updating patreon access token...");
|
||||
try
|
||||
{
|
||||
using var http = _httpFactory.CreateClient();
|
||||
var res = await http.PostAsync($"https://www.patreon.com/api/oauth2/token" +
|
||||
$"?grant_type=refresh_token" +
|
||||
$"&refresh_token={creds.Patreon.RefreshToken}" +
|
||||
$"&client_id={creds.Patreon.ClientId}" +
|
||||
$"&client_secret={creds.Patreon.ClientSecret}",
|
||||
new StringContent(string.Empty));
|
||||
|
||||
res.EnsureSuccessStatusCode();
|
||||
|
||||
var data = await res.Content.ReadFromJsonAsync<PatreonRefreshData>();
|
||||
|
||||
if (data is null)
|
||||
throw new("Invalid patreon response.");
|
||||
|
||||
_credsProvider.ModifyCredsFile(oldData =>
|
||||
{
|
||||
oldData.Patreon.AccessToken = data.AccessToken;
|
||||
oldData.Patreon.RefreshToken = data.RefreshToken;
|
||||
});
|
||||
|
||||
var db = _redis.GetDatabase();
|
||||
await db.StringSetAsync($"{creds.RedisKey()}_patreon_update", DateTime.UtcNow.ToBinary());
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error("Failed updating patreon access token: {ErrorMessage}", ex.ToString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool HasPatreonCreds(IBotCredentials creds)
|
||||
{
|
||||
var _1 = creds.Patreon.ClientId;
|
||||
var _2 = creds.Patreon.ClientSecret;
|
||||
var _4 = creds.Patreon.RefreshToken;
|
||||
return !(string.IsNullOrWhiteSpace(_1)
|
||||
|| string.IsNullOrWhiteSpace(_2)
|
||||
|| string.IsNullOrWhiteSpace(_4));
|
||||
}
|
||||
|
||||
public async Task RefreshPledges(IBotCredentials creds)
|
||||
{
|
||||
if (DateTime.UtcNow.Day < 5)
|
||||
return;
|
||||
|
||||
// if the user has the necessary patreon creds
|
||||
// and the access token expired or doesn't exist
|
||||
// -> update access token
|
||||
if (!HasPatreonCreds(creds))
|
||||
return;
|
||||
|
||||
if (LastAccessTokenUpdate(creds).Month < DateTime.UtcNow.Month
|
||||
|| string.IsNullOrWhiteSpace(creds.Patreon.AccessToken))
|
||||
{
|
||||
var success = await UpdateAccessToken(creds);
|
||||
if (!success)
|
||||
return;
|
||||
}
|
||||
|
||||
LastUpdate = DateTime.UtcNow;
|
||||
await getPledgesLocker.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var rewards = new List<PatreonPledge>();
|
||||
|
||||
var members = new List<PatreonMember>();
|
||||
var users = new List<PatreonUser>();
|
||||
using (var http = _httpFactory.CreateClient())
|
||||
{
|
||||
http.DefaultRequestHeaders.Clear();
|
||||
http.DefaultRequestHeaders.Add("Authorization", "Bearer " + _creds.PatreonAccessToken);
|
||||
var data = new PatreonData()
|
||||
{
|
||||
Links = new PatreonDataLinks()
|
||||
{
|
||||
next = $"https://api.patreon.com/oauth2/api/campaigns/{_creds.PatreonCampaignId}/pledges"
|
||||
}
|
||||
};
|
||||
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
|
||||
$"Bearer {creds.Patreon.AccessToken}");
|
||||
|
||||
var page = $"https://www.patreon.com/api/oauth2/v2/campaigns/{creds.Patreon.CampaignId}/members" +
|
||||
"?fields%5Bmember%5D=full_name,currently_entitled_amount_cents" +
|
||||
"&fields%5Buser%5D=social_connections" +
|
||||
"&include=user";
|
||||
PatreonResponse data = null;
|
||||
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 is null));
|
||||
if (data.Included != null)
|
||||
{
|
||||
users.AddRange(data.Included
|
||||
.Where(x => x["type"].ToString() == "user")
|
||||
.Select(x => JsonConvert.DeserializeObject<PatreonUser>(x.ToString())));
|
||||
}
|
||||
} while (!string.IsNullOrWhiteSpace(data.Links.next));
|
||||
var res = await http.GetStringAsync(page).ConfigureAwait(false);
|
||||
data = JsonSerializer.Deserialize<PatreonResponse>(res);
|
||||
|
||||
if (data is null)
|
||||
break;
|
||||
|
||||
members.AddRange(data.Data);
|
||||
users.AddRange(data.Included);
|
||||
} while (!string.IsNullOrWhiteSpace(page = data?.Links?.Next));
|
||||
}
|
||||
var toSet = rewards.Join(users, (r) => r.relationships?.patron?.data?.id, (u) => u.id, (x, y) => new PatreonUserAndReward()
|
||||
{
|
||||
User = y,
|
||||
Reward = x,
|
||||
}).ToArray();
|
||||
|
||||
_pledges = toSet;
|
||||
|
||||
foreach (var pledge in _pledges)
|
||||
{
|
||||
var userIdStr = pledge.User.attributes?.social_connections?.discord?.user_id;
|
||||
if (userIdStr != null && ulong.TryParse(userIdStr, out var userId))
|
||||
var userData = members.Join(users,
|
||||
(m) => m.Relationships.User.Data.Id,
|
||||
(u) => u.Id,
|
||||
(m, u) => new
|
||||
{
|
||||
await ClaimReward(userId);
|
||||
}
|
||||
PatreonUserId = m.Relationships.User.Data.Id,
|
||||
UserId = ulong.TryParse(u.Attributes?.SocialConnections?.Discord?.UserId ?? string.Empty,
|
||||
out var userId)
|
||||
? userId
|
||||
: 0,
|
||||
EntitledTo = m.Attributes.CurrentlyEntitledAmountCents,
|
||||
})
|
||||
.Where(x => x is
|
||||
{
|
||||
UserId: not 0,
|
||||
EntitledTo: > 0
|
||||
})
|
||||
.ToList();
|
||||
|
||||
foreach (var pledge in userData)
|
||||
{
|
||||
await ClaimReward(pledge.UserId, pledge.PatreonUserId, pledge.EntitledTo);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -123,80 +226,73 @@ namespace NadekoBot.Modules.Utility.Services
|
||||
|
||||
}
|
||||
|
||||
public async Task<int> ClaimReward(ulong userId)
|
||||
public async Task<int> ClaimReward(ulong userId, string patreonUserId, int cents)
|
||||
{
|
||||
await claimLockJustInCase.WaitAsync().ConfigureAwait(false);
|
||||
var settings = _gamblingConfigService.Data;
|
||||
var now = DateTime.UtcNow;
|
||||
try
|
||||
{
|
||||
var datas = _pledges?.Where(x => x.User.attributes?.social_connections?.discord?.user_id == userId.ToString())
|
||||
?? Enumerable.Empty<PatreonUserAndReward>();
|
||||
var eligibleFor = (int)(cents * settings.PatreonCurrencyPerCent);
|
||||
|
||||
var totalAmount = 0;
|
||||
foreach (var data in datas)
|
||||
using (var uow = _db.GetDbContext())
|
||||
{
|
||||
var amount = (int)(data.Reward.attributes.amount_cents * settings.PatreonCurrencyPerCent);
|
||||
var users = uow.Set<RewardedUser>();
|
||||
var usr = await users.FirstOrDefaultAsync(x => x.PatreonUserId == patreonUserId);
|
||||
|
||||
using (var uow = _db.GetDbContext())
|
||||
if (usr is null)
|
||||
{
|
||||
var users = uow.Set<RewardedUser>();
|
||||
var usr = users.FirstOrDefault(x => x.PatreonUserId == data.User.id);
|
||||
|
||||
if (usr is null)
|
||||
users.Add(new RewardedUser()
|
||||
{
|
||||
users.Add(new RewardedUser()
|
||||
{
|
||||
PatreonUserId = data.User.id,
|
||||
LastReward = now,
|
||||
AmountRewardedThisMonth = amount,
|
||||
});
|
||||
PatreonUserId = patreonUserId,
|
||||
LastReward = now,
|
||||
AmountRewardedThisMonth = eligibleFor,
|
||||
});
|
||||
|
||||
await uow.SaveChangesAsync();
|
||||
await uow.SaveChangesAsync();
|
||||
|
||||
await _currency.AddAsync(userId, "Patreon reward - new", amount, gamble: true);
|
||||
totalAmount += amount;
|
||||
|
||||
Log.Information($"Sending new currency reward to {userId}");
|
||||
await SendMessageToUser(userId, $"Thank you for your pledge! " +
|
||||
$"You've been awarded **{amount}**{settings.Currency.Sign} !");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (usr.LastReward.Month != now.Month)
|
||||
{
|
||||
usr.LastReward = now;
|
||||
usr.AmountRewardedThisMonth = amount;
|
||||
|
||||
await uow.SaveChangesAsync();
|
||||
|
||||
await _currency.AddAsync(userId, "Patreon reward - recurring", amount, gamble: true);
|
||||
totalAmount += amount;
|
||||
Log.Information($"Sending recurring currency reward to {userId}");
|
||||
await SendMessageToUser(userId, $"Thank you for your continued support! " +
|
||||
$"You've been awarded **{amount}**{settings.Currency.Sign} for this month's support!");
|
||||
continue;
|
||||
}
|
||||
|
||||
if (usr.AmountRewardedThisMonth < amount)
|
||||
{
|
||||
var toAward = amount - usr.AmountRewardedThisMonth;
|
||||
|
||||
usr.LastReward = now;
|
||||
usr.AmountRewardedThisMonth = amount;
|
||||
await uow.SaveChangesAsync();
|
||||
|
||||
await _currency.AddAsync(userId, "Patreon reward - update", toAward, gamble: true);
|
||||
totalAmount += toAward;
|
||||
Log.Information($"Sending updated currency reward to {userId}");
|
||||
await SendMessageToUser(userId, $"Thank you for increasing your pledge! " +
|
||||
$"You've been awarded an additional **{toAward}**{settings.Currency.Sign} !");
|
||||
continue;
|
||||
}
|
||||
await _currency.AddAsync(userId, "Patreon reward - new", eligibleFor, gamble: true);
|
||||
|
||||
Log.Information($"Sending new currency reward to {userId}");
|
||||
await SendMessageToUser(userId, $"Thank you for your pledge! " +
|
||||
$"You've been awarded **{eligibleFor}**{settings.Currency.Sign} !");
|
||||
return eligibleFor;
|
||||
}
|
||||
}
|
||||
|
||||
return totalAmount;
|
||||
if (usr.LastReward.Month != now.Month)
|
||||
{
|
||||
usr.LastReward = now;
|
||||
usr.AmountRewardedThisMonth = eligibleFor;
|
||||
|
||||
await uow.SaveChangesAsync();
|
||||
|
||||
await _currency.AddAsync(userId, "Patreon reward - recurring", eligibleFor, gamble: true);
|
||||
|
||||
Log.Information($"Sending recurring currency reward to {userId}");
|
||||
await SendMessageToUser(userId, $"Thank you for your continued support! " +
|
||||
$"You've been awarded **{eligibleFor}**{settings.Currency.Sign} for this month's support!");
|
||||
|
||||
return eligibleFor;
|
||||
}
|
||||
|
||||
if (usr.AmountRewardedThisMonth < eligibleFor)
|
||||
{
|
||||
var toAward = eligibleFor - usr.AmountRewardedThisMonth;
|
||||
|
||||
usr.LastReward = now;
|
||||
usr.AmountRewardedThisMonth = toAward;
|
||||
await uow.SaveChangesAsync();
|
||||
|
||||
await _currency.AddAsync(userId, "Patreon reward - update", toAward, gamble: true);
|
||||
|
||||
Log.Information($"Sending updated currency reward to {userId}");
|
||||
await SendMessageToUser(userId, $"Thank you for increasing your pledge! " +
|
||||
$"You've been awarded an additional **{toAward}**{settings.Currency.Sign} !");
|
||||
return toAward;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
@@ -9,6 +9,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -25,15 +26,18 @@ namespace NadekoBot.Modules.Utility
|
||||
private readonly IStatsService _stats;
|
||||
private readonly IBotCredentials _creds;
|
||||
private readonly DownloadTracker _tracker;
|
||||
private readonly IHttpClientFactory _httpFactory;
|
||||
|
||||
public Utility(DiscordSocketClient client, ICoordinator coord,
|
||||
IStatsService stats, IBotCredentials creds, DownloadTracker tracker)
|
||||
IStatsService stats, IBotCredentials creds, DownloadTracker tracker,
|
||||
IHttpClientFactory httpFactory)
|
||||
{
|
||||
_client = client;
|
||||
_coord = coord;
|
||||
_stats = stats;
|
||||
_creds = creds;
|
||||
_tracker = tracker;
|
||||
_httpFactory = httpFactory;
|
||||
}
|
||||
|
||||
[NadekoCommand, Aliases]
|
||||
@@ -278,6 +282,52 @@ namespace NadekoBot.Modules.Utility
|
||||
await ctx.Channel.SendMessageAsync(result.TrimTo(2000)).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
[NadekoCommand, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[RequireBotPermission(GuildPermission.ManageEmojis)]
|
||||
[RequireUserPermission(GuildPermission.ManageEmojis)]
|
||||
[Priority(0)]
|
||||
public Task EmojiAdd(string name, Emote emote)
|
||||
=> EmojiAdd(name, emote.Url);
|
||||
|
||||
[NadekoCommand, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[RequireBotPermission(GuildPermission.ManageEmojis)]
|
||||
[RequireUserPermission(GuildPermission.ManageEmojis)]
|
||||
public Task EmojiAdd(Emote emote)
|
||||
=> EmojiAdd(emote.Name, emote.Url);
|
||||
|
||||
[NadekoCommand, Aliases]
|
||||
[RequireContext(ContextType.Guild)]
|
||||
[RequireBotPermission(GuildPermission.ManageEmojis)]
|
||||
[RequireUserPermission(GuildPermission.ManageEmojis)]
|
||||
public async Task EmojiAdd(string name, string url)
|
||||
{
|
||||
name = name.Trim(':');
|
||||
using var http = _httpFactory.CreateClient();
|
||||
var res = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
|
||||
if (!res.IsImage() || res.GetImageSize() is null or > 262_144)
|
||||
{
|
||||
await ReplyErrorLocalizedAsync(strs.invalid_emoji_link);
|
||||
return;
|
||||
}
|
||||
|
||||
await using var imgStream = await res.Content.ReadAsStreamAsync();
|
||||
Emote em;
|
||||
try
|
||||
{
|
||||
em = await ctx.Guild.CreateEmoteAsync(name, new(imgStream));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Warning(ex, "Error adding emoji on server {GuildId}", ctx.Guild.Id);
|
||||
|
||||
await ReplyErrorLocalizedAsync(strs.emoji_add_error);
|
||||
return;
|
||||
}
|
||||
await ConfirmLocalizedAsync(strs.emoji_added(em.ToString()));
|
||||
}
|
||||
|
||||
[NadekoCommand, Aliases]
|
||||
[OwnerOnly]
|
||||
public async Task ListServers(int page = 1)
|
||||
|
@@ -10,7 +10,14 @@ using Serilog;
|
||||
|
||||
namespace NadekoBot.Services
|
||||
{
|
||||
public sealed class BotCredsProvider
|
||||
public interface IBotCredsProvider
|
||||
{
|
||||
public void Reload();
|
||||
public IBotCredentials GetCreds();
|
||||
public void ModifyCredsFile(Action<Creds> func);
|
||||
}
|
||||
|
||||
public sealed class BotCredsProvider : IBotCredsProvider
|
||||
{
|
||||
private readonly int? _totalShards;
|
||||
private const string _credsFileName = "creds.yml";
|
||||
@@ -27,7 +34,7 @@ namespace NadekoBot.Services
|
||||
|
||||
|
||||
private readonly object reloadLock = new object();
|
||||
private void Reload()
|
||||
public void Reload()
|
||||
{
|
||||
lock (reloadLock)
|
||||
{
|
||||
@@ -102,6 +109,19 @@ namespace NadekoBot.Services
|
||||
Reload();
|
||||
}
|
||||
|
||||
public void ModifyCredsFile(Action<Creds> func)
|
||||
{
|
||||
var ymlData = File.ReadAllText(_credsFileName);
|
||||
var creds = Yaml.Deserializer.Deserialize<Creds>(ymlData);
|
||||
|
||||
func(creds);
|
||||
|
||||
ymlData = Yaml.Serializer.Serialize(creds);
|
||||
File.WriteAllText(_credsFileName, ymlData);
|
||||
|
||||
Reload();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if there's a V2 credentials file present, loads it if it exists,
|
||||
/// converts it to new model, and saves it to YAML. Also backs up old credentials to credentials.json.bak
|
||||
@@ -157,6 +177,6 @@ namespace NadekoBot.Services
|
||||
|
||||
}
|
||||
|
||||
public Creds GetCreds() => _creds;
|
||||
public IBotCredentials GetCreds() => _creds;
|
||||
}
|
||||
}
|
@@ -357,7 +357,7 @@ namespace NadekoBot.Extensions
|
||||
|
||||
public static bool IsImage(this HttpResponseMessage msg, out string mimeType)
|
||||
{
|
||||
mimeType = msg.Content.Headers.ContentType.MediaType;
|
||||
mimeType = msg.Content.Headers.ContentType?.MediaType;
|
||||
if (mimeType == "image/png"
|
||||
|| mimeType == "image/jpeg"
|
||||
|| mimeType == "image/gif")
|
||||
|
@@ -31,11 +31,9 @@ votes:
|
||||
# Patreon auto reward system settings.
|
||||
# go to https://www.patreon.com/portal -> my clients -> create client
|
||||
patreon:
|
||||
# Access token. You have to manually update this 1st of each month by refreshing the token on https://patreon.com/portal
|
||||
clientId:
|
||||
accessToken: ''
|
||||
# Unused atm
|
||||
refreshToken: ''
|
||||
# Unused atm
|
||||
clientSecret: ''
|
||||
# Campaign ID of your patreon page. Go to your patreon page (make sure you're logged in) and type "prompt('Campaign ID', window.patreon.bootstrap.creator.data.id);" in the console. (ctrl + shift + i)
|
||||
campaignId: ''
|
||||
|
@@ -720,6 +720,9 @@ removeperm:
|
||||
showemojis:
|
||||
- showemojis
|
||||
- se
|
||||
emojiadd:
|
||||
- emojiadd
|
||||
- ea
|
||||
deckshuffle:
|
||||
- deckshuffle
|
||||
- dsh
|
||||
|
@@ -1195,6 +1195,16 @@ showemojis:
|
||||
desc: "Shows a name and a link to every SPECIAL emoji in the message."
|
||||
args:
|
||||
- "A message full of SPECIAL emojis"
|
||||
emojiadd:
|
||||
desc: |-
|
||||
Adds the specified emoji to this server.
|
||||
You can specify a name before the emoji to add it under a different name.
|
||||
You can specify a name followed by an image link to add a new emoji from an image.
|
||||
Image size has to be below 256KB.
|
||||
args:
|
||||
- ":someonesCustomEmoji:"
|
||||
- "MyEmojiName :someonesCustomEmoji:"
|
||||
- "owoNice https://cdn.discordapp.com/emojis/587930873811173386.png?size=128"
|
||||
deckshuffle:
|
||||
desc: "Reshuffles all cards back into the deck."
|
||||
args:
|
||||
|
@@ -9,6 +9,9 @@
|
||||
"crr_reset": "Custom reaction with id {0} will no longer add reactions.",
|
||||
"crr_set": "Custom reaction with id {0} will add following reactions to the response message: {1}",
|
||||
"invalid_emojis": "All emojis you've specified are invalid.",
|
||||
"invalid_emoji_link": "Specified link is either not an image or exceeds 256KB.",
|
||||
"emoji_add_error": "Error adding emoji. You either ran out of emoji slots, or image size is inadequate.",
|
||||
"emoji_added": "Added a new emoji: {0}",
|
||||
"fw_cleared": "Removed all filtered words and filtered words channel settings.",
|
||||
"aliases_cleared": "All {0} aliases on this server have been removed.",
|
||||
"no_results": "No results found.",
|
||||
|
Reference in New Issue
Block a user