Disables role rewards (not configured in real server)

This commit is contained in:
Ben 2024-06-26 11:27:19 +02:00
parent c2712daccb
commit 8341807d92
No known key found for this signature in database
GPG Key ID: 541B9D8C9F1426A1
4 changed files with 92 additions and 74 deletions

View File

@ -1,53 +1,53 @@
using Utils; namespace DiscordRewards
namespace DiscordRewards
{ {
public class RewardRepo public class RewardRepo
{ {
private static string Tag => RewardConfig.UsernameTag; private static string Tag => RewardConfig.UsernameTag;
public RewardConfig[] Rewards { get; } = new RewardConfig[] public RewardConfig[] Rewards { get; } = new RewardConfig[0];
{
// Filled any slot
new RewardConfig(1187039439558541498, $"{Tag} successfully filled their first slot!", new CheckConfig
{
Type = CheckType.HostFilledSlot
}),
// Finished any slot // Example configuration, from test server:
new RewardConfig(1202286165630390339, $"{Tag} successfully finished their first slot!", new CheckConfig //{
{ // // Filled any slot
Type = CheckType.HostFinishedSlot // new RewardConfig(1187039439558541498, $"{Tag} successfully filled their first slot!", new CheckConfig
}), // {
// Type = CheckType.HostFilledSlot
// }),
// Finished a sizable slot // // Finished any slot
new RewardConfig(1202286218738405418, $"{Tag} finished their first 1GB-24h slot! (10mb/5mins for test)", new CheckConfig // new RewardConfig(1202286165630390339, $"{Tag} successfully finished their first slot!", new CheckConfig
{ // {
Type = CheckType.HostFinishedSlot, // Type = CheckType.HostFinishedSlot
MinSlotSize = 10.MB(), // }),
MinDuration = TimeSpan.FromMinutes(5.0),
}),
// Posted any contract // // Finished a sizable slot
new RewardConfig(1202286258370383913, $"{Tag} posted their first contract!", new CheckConfig // new RewardConfig(1202286218738405418, $"{Tag} finished their first 1GB-24h slot! (10mb/5mins for test)", new CheckConfig
{ // {
Type = CheckType.ClientPostedContract // Type = CheckType.HostFinishedSlot,
}), // MinSlotSize = 10.MB(),
// MinDuration = TimeSpan.FromMinutes(5.0),
// }),
// Started any contract // // Posted any contract
new RewardConfig(1202286330873126992, $"A contract created by {Tag} reached Started state for the first time!", new CheckConfig // new RewardConfig(1202286258370383913, $"{Tag} posted their first contract!", new CheckConfig
{ // {
Type = CheckType.ClientStartedContract // Type = CheckType.ClientPostedContract
}), // }),
// Started a sizable contract // // Started any contract
new RewardConfig(1202286381670608909, $"A large contract created by {Tag} reached Started state for the first time! (10mb/5mins for test)", new CheckConfig // new RewardConfig(1202286330873126992, $"A contract created by {Tag} reached Started state for the first time!", new CheckConfig
{ // {
Type = CheckType.ClientStartedContract, // Type = CheckType.ClientStartedContract
MinNumberOfHosts = 4, // }),
MinSlotSize = 10.MB(),
MinDuration = TimeSpan.FromMinutes(5.0), // // Started a sizable contract
}) // new RewardConfig(1202286381670608909, $"A large contract created by {Tag} reached Started state for the first time! (10mb/5mins for test)", new CheckConfig
}; // {
// Type = CheckType.ClientStartedContract,
// MinNumberOfHosts = 4,
// MinSlotSize = 10.MB(),
// MinDuration = TimeSpan.FromMinutes(5.0),
// })
//};
} }
} }

View File

@ -3,6 +3,7 @@ using Discord.WebSocket;
using Discord; using Discord;
using Newtonsoft.Json; using Newtonsoft.Json;
using BiblioTech.Rewards; using BiblioTech.Rewards;
using Logging;
namespace BiblioTech namespace BiblioTech
{ {
@ -10,12 +11,13 @@ namespace BiblioTech
{ {
private readonly DiscordSocketClient client; private readonly DiscordSocketClient client;
private readonly BaseCommand[] commands; private readonly BaseCommand[] commands;
private readonly ILog log;
public CommandHandler(DiscordSocketClient client, params BaseCommand[] commands) public CommandHandler(ILog log, DiscordSocketClient client, params BaseCommand[] commands)
{ {
this.client = client; this.client = client;
this.commands = commands; this.commands = commands;
this.log = log;
client.Ready += Client_Ready; client.Ready += Client_Ready;
client.SlashCommandExecuted += SlashCommandHandler; client.SlashCommandExecuted += SlashCommandHandler;
} }
@ -24,12 +26,12 @@ namespace BiblioTech
{ {
var guild = client.Guilds.Single(g => g.Id == Program.Config.ServerId); var guild = client.Guilds.Single(g => g.Id == Program.Config.ServerId);
Program.AdminChecker.SetGuild(guild); Program.AdminChecker.SetGuild(guild);
Program.Log.Log($"Initializing for guild: '{guild.Name}'"); log.Log($"Initializing for guild: '{guild.Name}'");
var adminChannels = guild.TextChannels.Where(Program.AdminChecker.IsAdminChannel).ToArray(); var adminChannels = guild.TextChannels.Where(Program.AdminChecker.IsAdminChannel).ToArray();
if (adminChannels == null || !adminChannels.Any()) throw new Exception("No admin message channel"); if (adminChannels == null || !adminChannels.Any()) throw new Exception("No admin message channel");
Program.AdminChecker.SetAdminChannel(adminChannels.First()); Program.AdminChecker.SetAdminChannel(adminChannels.First());
Program.RoleDriver = new RoleDriver(client); Program.RoleDriver = new RoleDriver(client, log);
var builders = commands.Select(c => var builders = commands.Select(c =>
{ {
@ -44,7 +46,7 @@ namespace BiblioTech
builder.AddOption(option.Build()); builder.AddOption(option.Build());
} }
Program.Log.Log(msg); log.Log(msg);
return builder; return builder;
}); });
@ -58,7 +60,7 @@ namespace BiblioTech
catch (HttpException exception) catch (HttpException exception)
{ {
var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented); var json = JsonConvert.SerializeObject(exception.Errors, Formatting.Indented);
Program.Log.Error(json); log.Error(json);
} }
} }

View File

@ -73,7 +73,7 @@ namespace BiblioTech
var notifyCommand = new NotifyCommand(); var notifyCommand = new NotifyCommand();
var associateCommand = new UserAssociateCommand(notifyCommand); var associateCommand = new UserAssociateCommand(notifyCommand);
var sprCommand = new SprCommand(); var sprCommand = new SprCommand();
var handler = new CommandHandler(client, var handler = new CommandHandler(Log, client,
new GetBalanceCommand(associateCommand), new GetBalanceCommand(associateCommand),
new MintCommand(associateCommand), new MintCommand(associateCommand),
sprCommand, sprCommand,

View File

@ -1,6 +1,7 @@
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using DiscordRewards; using DiscordRewards;
using Logging;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace BiblioTech.Rewards namespace BiblioTech.Rewards
@ -8,21 +9,22 @@ namespace BiblioTech.Rewards
public class RoleDriver : IDiscordRoleDriver public class RoleDriver : IDiscordRoleDriver
{ {
private readonly DiscordSocketClient client; private readonly DiscordSocketClient client;
private readonly ILog log;
private readonly SocketTextChannel? rewardsChannel; private readonly SocketTextChannel? rewardsChannel;
private readonly SocketTextChannel? eventsChannel; private readonly SocketTextChannel? eventsChannel;
private readonly RewardRepo repo = new RewardRepo(); private readonly RewardRepo repo = new RewardRepo();
public RoleDriver(DiscordSocketClient client) public RoleDriver(DiscordSocketClient client, ILog log)
{ {
this.client = client; this.client = client;
this.log = log;
rewardsChannel = GetChannel(Program.Config.RewardsChannelId); rewardsChannel = GetChannel(Program.Config.RewardsChannelId);
eventsChannel = GetChannel(Program.Config.ChainEventsChannelId); eventsChannel = GetChannel(Program.Config.ChainEventsChannelId);
} }
public async Task GiveRewards(GiveRewardsCommand rewards) public async Task GiveRewards(GiveRewardsCommand rewards)
{ {
Program.Log.Log($"Processing rewards command: '{JsonConvert.SerializeObject(rewards)}'"); log.Log($"Processing rewards command: '{JsonConvert.SerializeObject(rewards)}'");
if (rewards.Rewards.Any()) if (rewards.Rewards.Any())
{ {
@ -34,15 +36,22 @@ namespace BiblioTech.Rewards
private async Task ProcessRewards(GiveRewardsCommand rewards) private async Task ProcessRewards(GiveRewardsCommand rewards)
{ {
var guild = GetGuild(); try
// We load all role and user information first, {
// so we don't ask the server for the same info multiple times. var guild = GetGuild();
var context = new RewardContext( // We load all role and user information first,
await LoadAllUsers(guild), // so we don't ask the server for the same info multiple times.
LookUpAllRoles(guild, rewards), var context = new RewardContext(
rewardsChannel); await LoadAllUsers(guild),
LookUpAllRoles(guild, rewards),
rewardsChannel);
await context.ProcessGiveRewardsCommand(LookUpUsers(rewards)); await context.ProcessGiveRewardsCommand(LookUpUsers(rewards));
}
catch (Exception ex)
{
log.Error("Failed to process rewards: " + ex);
}
} }
private SocketTextChannel? GetChannel(ulong id) private SocketTextChannel? GetChannel(ulong id)
@ -54,22 +63,29 @@ namespace BiblioTech.Rewards
private async Task ProcessChainEvents(string[] eventsOverview) private async Task ProcessChainEvents(string[] eventsOverview)
{ {
if (eventsChannel == null || eventsOverview == null || !eventsOverview.Any()) return; if (eventsChannel == null || eventsOverview == null || !eventsOverview.Any()) return;
await Task.Run(async () => try
{ {
foreach (var e in eventsOverview) await Task.Run(async () =>
{ {
if (!string.IsNullOrEmpty(e)) foreach (var e in eventsOverview)
{ {
await eventsChannel.SendMessageAsync(e); if (!string.IsNullOrEmpty(e))
await Task.Delay(3000); {
await eventsChannel.SendMessageAsync(e);
await Task.Delay(3000);
}
} }
} });
}); }
catch (Exception ex)
{
log.Error("Failed to process chain events: " + ex);
}
} }
private async Task<Dictionary<ulong, IGuildUser>> LoadAllUsers(SocketGuild guild) private async Task<Dictionary<ulong, IGuildUser>> LoadAllUsers(SocketGuild guild)
{ {
Program.Log.Log("Loading all users:"); log.Log("Loading all users..");
var result = new Dictionary<ulong, IGuildUser>(); var result = new Dictionary<ulong, IGuildUser>();
var users = guild.GetUsersAsync(); var users = guild.GetUsersAsync();
await foreach (var ulist in users) await foreach (var ulist in users)
@ -77,8 +93,8 @@ namespace BiblioTech.Rewards
foreach (var u in ulist) foreach (var u in ulist)
{ {
result.Add(u.Id, u); result.Add(u.Id, u);
var roleIds = string.Join(",", u.RoleIds.Select(r => r.ToString()).ToArray()); //var roleIds = string.Join(",", u.RoleIds.Select(r => r.ToString()).ToArray());
Program.Log.Log($" > {u.Id}({u.DisplayName}) has [{roleIds}]"); //log.Log($" > {u.Id}({u.DisplayName}) has [{roleIds}]");
} }
} }
return result; return result;
@ -94,14 +110,14 @@ namespace BiblioTech.Rewards
var rewardConfig = repo.Rewards.SingleOrDefault(rr => rr.RoleId == r.RewardId); var rewardConfig = repo.Rewards.SingleOrDefault(rr => rr.RoleId == r.RewardId);
if (rewardConfig == null) if (rewardConfig == null)
{ {
Program.Log.Log($"No Reward is configured for id '{r.RewardId}'."); log.Log($"No Reward is configured for id '{r.RewardId}'.");
} }
else else
{ {
var socketRole = guild.GetRole(r.RewardId); var socketRole = guild.GetRole(r.RewardId);
if (socketRole == null) if (socketRole == null)
{ {
Program.Log.Log($"Guild Role by id '{r.RewardId}' not found."); log.Log($"Guild Role by id '{r.RewardId}' not found.");
} }
else else
{ {
@ -134,13 +150,13 @@ namespace BiblioTech.Rewards
try try
{ {
var userData = Program.UserRepo.GetUserDataForAddress(new GethPlugin.EthAddress(address)); var userData = Program.UserRepo.GetUserDataForAddress(new GethPlugin.EthAddress(address));
if (userData != null) Program.Log.Log($"User '{userData.Name}' was looked up."); if (userData != null) log.Log($"User '{userData.Name}' was looked up.");
else Program.Log.Log($"Lookup for user was unsuccessful. EthAddress: '{address}'"); else log.Log($"Lookup for user was unsuccessful. EthAddress: '{address}'");
return userData; return userData;
} }
catch (Exception ex) catch (Exception ex)
{ {
Program.Log.Error("Error during UserData lookup: " + ex); log.Error("Error during UserData lookup: " + ex);
return null; return null;
} }
} }