color typereader fix

delmsgoncmd
guildconfig init
This commit is contained in:
Toastie 2025-03-30 15:06:56 +13:00
parent aa06f62258
commit 57a5993064
Signed by: toastie_t0ast
GPG key ID: 0861BE54AD481DC7
8 changed files with 244 additions and 213 deletions
src
EllieBot.VotesApi/Controllers
EllieBot

View file

@ -14,7 +14,7 @@ namespace EllieBot.VotesApi.Controllers
[Authorize(Policy = Policies.DiscordsAuth)]
public async Task<IActionResult> DiscordsWebhook([FromBody] DiscordsVoteWebhookModel data)
{
if (data.Type != "vote")
if ((data.Type?.Contains("vote") ?? false) == false)
return Ok();
logger.LogInformation("User {UserId} has voted for Bot {BotId} on {Platform}",

View file

@ -225,6 +225,7 @@ public abstract class EllieContext : DbContext
configEntity.Property(x => x.VerboseErrors)
.HasDefaultValue(true);
// end shop
modelBuilder.Entity<PlantedCurrency>().HasIndex(x => x.MessageId).IsUnique();

View file

@ -1,4 +1,3 @@
#nullable disable
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System.ComponentModel.DataAnnotations;
@ -31,39 +30,38 @@ public sealed class GuildFilterConfigEntityConfiguration : IEntityTypeConfigurat
public class GuildConfig : DbEntity
{
public ulong GuildId { get; set; }
public string Prefix { get; set; }
public string? Prefix { get; set; } = null;
public bool DeleteMessageOnCommand { get; set; }
public string AutoAssignRoleIds { get; set; }
public bool DeleteMessageOnCommand { get; set; } = false;
public string? AutoAssignRoleIds { get; set; } = null;
public bool VerbosePermissions { get; set; } = true;
public string PermissionRole { get; set; }
public string? PermissionRole { get; set; } = null;
//filtering
public string MuteRoleName { get; set; }
public string? MuteRoleName { get; set; } = null;
// chatterbot
public bool CleverbotEnabled { get; set; }
public bool CleverbotEnabled { get; set; } = false;
// aliases
public bool WarningsInitialized { get; set; }
public bool WarningsInitialized { get; set; } = false;
public ulong? GameVoiceChannel { get; set; }
public ulong? GameVoiceChannel { get; set; } = null;
public bool VerboseErrors { get; set; } = true;
public bool NotifyStreamOffline { get; set; }
public bool DeleteStreamOnlineMessage { get; set; }
public int WarnExpireHours { get; set; }
public bool NotifyStreamOffline { get; set; } = true;
public bool DeleteStreamOnlineMessage { get; set; } = false;
public int WarnExpireHours { get; set; } = 0;
public WarnExpireAction WarnExpireAction { get; set; } = WarnExpireAction.Clear;
public bool DisableGlobalExpressions { get; set; } = false;
public bool StickyRoles { get; set; }
public bool StickyRoles { get; set; } = false;
public string TimeZoneId { get; set; }
public string Locale { get; set; }
public string? TimeZoneId { get; set; } = null;
public string? Locale { get; set; } = null;
public List<Permissionv2> Permissions { get; set; } = [];
}

View file

@ -124,7 +124,7 @@ public partial class Administration : EllieModule<AdministrationService>
[Priority(1)]
public async Task Delmsgoncmd(Server _ = Server.Server)
{
var enabled = await _service.ToggleDeleteMessageOnCommand(ctx.Guild.Id);
var enabled = await _service.ToggleDelMsgOnCmd(ctx.Guild.Id);
if (enabled)
{
await Response().Confirm(strs.delmsg_on).SendAsync();

View file

@ -1,7 +1,5 @@
#nullable disable
using LinqToDB;
using LinqToDB.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using EllieBot.Common.ModuleBehaviors;
using EllieBot.Db.Models;
using EllieBot.Modules.Administration._common.results;
@ -10,8 +8,8 @@ namespace EllieBot.Modules.Administration;
public class AdministrationService : IEService, IReadyExecutor
{
private ConcurrentHashSet<ulong> deleteMessagesOnCommand;
private ConcurrentDictionary<ulong, bool> delMsgOnCmdChannels;
private ConcurrentHashSet<ulong> _deleteMessagesOnCommand;
private ConcurrentDictionary<ulong, bool> _delMsgOnCmdChannels;
private readonly DbService _db;
private readonly IReplacementService _repSvc;
@ -39,13 +37,14 @@ public class AdministrationService : IEService, IReadyExecutor
public async Task OnReadyAsync()
{
await using var uow = _db.GetDbContext();
deleteMessagesOnCommand = new(await uow.GetTable<GuildConfig>()
.Where(x => Queries.GuildOnShard(x.GuildId, _shardData.TotalShards, _shardData.ShardId) && x.DeleteMessageOnCommand)
_deleteMessagesOnCommand = new(await uow.GetTable<GuildConfig>()
.Where(x => Queries.GuildOnShard(x.GuildId, _shardData.TotalShards, _shardData.ShardId) &&
x.DeleteMessageOnCommand)
.Select(x => x.GuildId)
.ToListAsyncLinqToDB());
delMsgOnCmdChannels = (await uow.GetTable<DelMsgOnCmdChannel>()
.Where(x => deleteMessagesOnCommand.Contains(x.GuildId))
_delMsgOnCmdChannels = (await uow.GetTable<DelMsgOnCmdChannel>()
.Where(x => _deleteMessagesOnCommand.Contains(x.GuildId))
.ToDictionaryAsyncLinqToDB(x => x.ChannelId, x => x.State))
.ToConcurrent();
@ -54,7 +53,7 @@ public class AdministrationService : IEService, IReadyExecutor
public async Task<(bool DelMsgOnCmd, IEnumerable<DelMsgOnCmdChannel> channels)> GetDelMsgOnCmdData(ulong guildId)
{
using var uow = _db.GetDbContext();
await using var uow = _db.GetDbContext();
var conf = await uow.GetTable<GuildConfig>()
.Where(x => x.GuildId == guildId)
@ -76,50 +75,50 @@ public class AdministrationService : IEService, IReadyExecutor
_ = Task.Run(async () =>
{
//wat ?!
if (delMsgOnCmdChannels.TryGetValue(channel.Id, out var state))
if (_delMsgOnCmdChannels.TryGetValue(channel.Id, out var state))
{
if (state && cmd.Name != "prune" && cmd.Name != "pick")
{
_logService.AddDeleteIgnore(msg.Id);
try
{ await msg.DeleteAsync(); }
catch { }
{
await msg.DeleteAsync();
}
catch
{
}
}
//if state is false, that means do not do it
}
else if (deleteMessagesOnCommand.Contains(channel.Guild.Id) && cmd.Name != "prune" && cmd.Name != "pick")
else if (_deleteMessagesOnCommand.Contains(channel.Guild.Id) && cmd.Name != "prune" && cmd.Name != "pick")
{
_logService.AddDeleteIgnore(msg.Id);
try
{ await msg.DeleteAsync(); }
catch { }
{
await msg.DeleteAsync();
}
catch
{
}
}
});
return Task.CompletedTask;
}
public async Task<bool> ToggleDeleteMessageOnCommand(ulong guildId)
public async Task<bool> ToggleDelMsgOnCmd(ulong guildId)
{
using var uow = _db.GetDbContext();
await using var uow = _db.GetDbContext();
var conf = await uow.GetTable<GuildConfig>()
.Where(x => x.GuildId == guildId)
.UpdateWithOutputAsync(x => new()
{
DeleteMessageOnCommand = !x.DeleteMessageOnCommand
}, (old, newVal) => newVal);
var gc = uow.GuildConfigsForId(guildId);
gc.DeleteMessageOnCommand = !gc.DeleteMessageOnCommand;
if (conf.Length == 0)
return false;
var val = conf[0].DeleteMessageOnCommand;
if (val)
deleteMessagesOnCommand.Add(guildId);
if (gc.DeleteMessageOnCommand)
_deleteMessagesOnCommand.Add(guildId);
else
deleteMessagesOnCommand.TryRemove(guildId);
_deleteMessagesOnCommand.TryRemove(guildId);
return val;
await uow.SaveChangesAsync();
return gc.DeleteMessageOnCommand;
}
public async Task SetDelMsgOnCmdState(ulong guildId, ulong chId, Administration.State newState)
@ -151,7 +150,7 @@ public class AdministrationService : IEService, IReadyExecutor
}
old.State = newState == Administration.State.Enable;
delMsgOnCmdChannels[chId] = newState == Administration.State.Enable;
_delMsgOnCmdChannels[chId] = newState == Administration.State.Enable;
}
await uow.SaveChangesAsync();
@ -162,11 +161,11 @@ public class AdministrationService : IEService, IReadyExecutor
}
else if (newState == Administration.State.Enable)
{
delMsgOnCmdChannels[chId] = true;
_delMsgOnCmdChannels[chId] = true;
}
else
{
delMsgOnCmdChannels.TryRemove(chId, out _);
_delMsgOnCmdChannels.TryRemove(chId, out _);
}
}
@ -249,5 +248,6 @@ public class AdministrationService : IEService, IReadyExecutor
return SetServerIconResult.Success;
}
private bool IsValidUri(string img) => !string.IsNullOrWhiteSpace(img) && Uri.IsWellFormedUriString(img, UriKind.Absolute);
private bool IsValidUri(string img)
=> !string.IsNullOrWhiteSpace(img) && Uri.IsWellFormedUriString(img, UriKind.Absolute);
}

View file

@ -5,6 +5,7 @@ using SixLabors.ImageSharp.Advanced;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Color = SixLabors.ImageSharp.Color;
using Image = SixLabors.ImageSharp.Image;
namespace EllieBot.Modules.Games;
@ -81,7 +82,15 @@ public partial class Games
using var img = await GetZoomImage(position);
await using var stream = await img.ToStreamAsync();
await ctx.Channel.SendFileAsync(stream, $"zoom_{position}.png");
var eb = CreateEmbed()
.WithOkColor()
.WithImageUrl($"attachment://zoom_{position}.png")
.WithFooter($"`.ncs code color` to set. (.ncs abc green)" );
await Response()
.Embed(eb)
.File(stream, $"zoom_{position}.png")
.SendAsync();
}
private async Task<Image<Rgba32>> GetZoomImage(kwum position)
@ -135,7 +144,7 @@ public partial class Games
}
[Cmd]
public async Task NcSetPixel(kwum position, string colorHex, [Leftover] string text = "")
public async Task NcSetPixel(kwum position, Rgba32 color, [Leftover] string text = "")
{
if (position < 0 || position >= _service.GetWidth() * _service.GetHeight())
{
@ -143,15 +152,6 @@ public partial class Games
return;
}
if (colorHex.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
colorHex = colorHex[2..];
if (!Rgba32.TryParseHex(colorHex, out var clr))
{
await Response().Error(strs.invalid_color).SendAsync();
return;
}
var pixel = await _service.GetPixel(position);
if (pixel is null)
{
@ -171,7 +171,7 @@ public partial class Games
return;
}
var result = await _service.SetPixel(position, clr.PackedValue, text, ctx.User.Id, pixel.Price);
var result = await _service.SetPixel(position, color.PackedValue, text, ctx.User.Id, pixel.Price);
if (result == SetPixelResult.NotEnoughMoney)
{

View file

@ -46,35 +46,45 @@ public sealed class QuestService(
_ = Task.Run(async () =>
{
// Log.Information("Action reported by {UserId}: {EventType} {Metadata}",
// userId,
// eventType,
// metadata.ToJson());
Log.Information("Action reported by {UserId}: {EventType} {Metadata}",
userId,
eventType,
metadata.ToJson());
metadata ??= new();
var now = DateTime.UtcNow;
Log.Information("done?");
var alreadyDone = await botCache.GetAsync(UserCompletedDailiesKey(userId));
if (alreadyDone.IsT0)
return;
Log.Information("not done");
var userQuests = await GetUserQuestsAsync(userId, now);
Log.Information("got quests");
foreach (var (q, uq) in userQuests)
{
// deleted quest
if (q is null)
continue;
Log.Information("not deleted {QuestEventType} - {EventType}", q.EventType, eventType);
// user already completed or incorrect event
if (uq.IsCompleted || q.EventType != eventType)
continue;
Log.Information("Gonna update progress");
var newProgress = q.TryUpdateProgress(metadata, uq.Progress);
// user already did that part of the quest
if (newProgress == uq.Progress)
continue;
Log.Information("new progress");
var isCompleted = newProgress >= q.RequiredAmount;
await using var uow = db.GetDbContext();

View file

@ -8,11 +8,33 @@ public sealed class Rgba32TypeReader : EllieTypeReader<Rgba32>
{
public override ValueTask<TypeReaderResult<Rgba32>> ReadAsync(ICommandContext context, string input)
{
if (!Color.TryParse(input, out var color))
{
Log.Information("Fail");
return ValueTask.FromResult(
TypeReaderResult.FromError<Rgba32>(CommandError.ParseFailed, "Parameter is not a valid color hex."));
}
Log.Information(color.ToHex());
return ValueTask.FromResult(TypeReaderResult.FromSuccess((Rgba32)color));
if (Rgba32.TryParseHex(input, out var clr))
{
return ValueTask.FromResult(TypeReaderResult.FromSuccess(clr));
}
if (!Enum.TryParse<Color>(input, true, out var clrName))
return ValueTask.FromResult(
TypeReaderResult.FromError<Rgba32>(CommandError.ParseFailed,
"Parameter is not a valid color hex."));
Log.Information(clrName.ToString());
if (Rgba32.TryParseHex(clrName.ToHex(), out clr))
{
return ValueTask.FromResult(TypeReaderResult.FromSuccess(clr));
}
return ValueTask.FromResult(
TypeReaderResult.FromError<Rgba32>(CommandError.ParseFailed, "Parameter is not a valid color hex."));
}